Java 类com.google.common.collect.ImmutableMap") 实例源码

项目:CustomWorldGen    文件:PersistentRegistryManager.java   
public static void revertToFrozen()
{
    if (!PersistentRegistry.FROZEN.isPopulated())
    {
        FMLLog.warning("Can't revert to frozen GameData state without freezing first.");
        return;
    }
    else
    {
        FMLLog.fine("Reverting to frozen data state.");
    }
    for (Map.Entry<ResourceLocation, FMLControlledNamespacedRegistry<?>> r : PersistentRegistry.ACTIVE.registries.entrySet())
    {
        final Class<? extends IForgeRegistryEntry> registrySuperType = PersistentRegistry.ACTIVE.getRegistrySuperType(r.getKey());
        loadRegistry(r.getKey(), PersistentRegistry.FROZEN, PersistentRegistry.ACTIVE, registrySuperType);
    }
    // the id mapping has reverted, fire remap events for those that care about id changes
    Loader.instance().fireRemapEvent(ImmutableMap.<ResourceLocation, Integer[]>of(), ImmutableMap.<ResourceLocation, Integer[]>of(), true);

    // the id mapping has reverted, ensure we sync up the object holders
    ObjectHolderRegistry.INSTANCE.applyObjectHolders();
    FMLLog.fine("Frozen state restored.");
}
项目:buckaroo    文件:MoreObservablesTest.java   
@Test
public void shouldHandleEmptyInMergedMaps() throws Exception {

    final Observable<Integer> a = Observable.empty();

    final Observable<Integer> b = Observable.create(s -> {
        s.onNext(1);
        s.onNext(2);
        s.onNext(3);
        s.onComplete();
    });

    final ImmutableMap<String, Observable<Integer>> map = ImmutableMap.of(
        "a", a,
        "b", b
    );

    final Observable<ImmutableMap<String, Integer>> observableMap =
        MoreObservables.mergeMaps(map);

    final int error = observableMap
        .reduce(1, (x, y) -> 0)
        .blockingGet();

    assertEquals(0, error);
}
项目:generator-thundr-gae-react    文件:MagicLinkService.java   
public void sendMagicLinkEmail(String loginIdentifier, String next) {
    AppUser user = userService.get(loginIdentifier);
    if (user == null) {
        Logger.error("Sending magic link failed. No such user %s", loginIdentifier);
        return; // fail silently so job doesn't get retry
    }

    String link = next == null
        ? createLinkForUser(user)
        : createLinkForUser(user, next);
    Map<String, Object> model = ImmutableMap.<String, Object>of(
        "magicLink", link);

    mailer.mail()
        .to(user.getEmail())
        .from(mailerSenderEmail)
        .subject("Your News Xtend X2 magic login link")
        .body(new HandlebarsView("user-login-email", model))
        .send();
}
项目:buckaroo    文件:MoreObservablesTest.java   
@Test
public void mergeMaps() throws Exception {

    final Map<String, Observable<Integer>> o = ImmutableMap.of(
        "a", Observable.just(1),
        "b", Observable.just(1, 2, 3),
        "c", Observable.empty()
    );

    final ImmutableMap<String, Integer> expected = ImmutableMap.of(
        "a", 1,
        "b", 3
    );

    final ImmutableMap<String, Integer> actual = MoreObservables.mergeMaps(o)
        .lastElement()
        .blockingGet();

    assertEquals(expected , actual);
}
项目:hashsdn-controller    文件:ShardDataTreeSnapshotTest.java   
@Test
public void testShardDataTreeSnapshotWithMetadata() throws Exception {
    NormalizedNode<?, ?> expectedNode = ImmutableContainerNodeBuilder.create()
            .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME))
            .withChild(ImmutableNodes.leafNode(TestModel.DESC_QNAME, "foo")).build();

    Map<Class<? extends ShardDataTreeSnapshotMetadata<?>>, ShardDataTreeSnapshotMetadata<?>> expMetadata =
            ImmutableMap.of(TestShardDataTreeSnapshotMetadata.class, new TestShardDataTreeSnapshotMetadata("test"));
    MetadataShardDataTreeSnapshot snapshot = new MetadataShardDataTreeSnapshot(expectedNode, expMetadata);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    try (ObjectOutputStream out = new ObjectOutputStream(bos)) {
        snapshot.serialize(out);
    }

    ShardDataTreeSnapshot deserialized;
    try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()))) {
        deserialized = ShardDataTreeSnapshot.deserialize(in);
    }

    Optional<NormalizedNode<?, ?>> actualNode = deserialized.getRootNode();
    assertEquals("rootNode present", true, actualNode.isPresent());
    assertEquals("rootNode", expectedNode, actualNode.get());
    assertEquals("Deserialized type", MetadataShardDataTreeSnapshot.class, deserialized.getClass());
    assertEquals("Metadata", expMetadata, ((MetadataShardDataTreeSnapshot)deserialized).getMetadata());
}
项目:de.flapdoodle.solid    文件:Multimaps.java   
public static <K,V> ImmutableList<ImmutableMap<K, V>> flatten(ImmutableMultimap<K, V> src) {
    ImmutableList.Builder<ImmutableMap<K, V>> listBuilder=ImmutableList.builder();

    if (!src.isEmpty()) {
        ImmutableMap<K, Collection<V>> map = src.asMap();
        int entries=map.values().stream().reduce(1, (s,l) -> s*l.size(), (a,b) -> a*b);

        ImmutableList<Line<K,V>> lines = map.entrySet().stream()
                .map(e -> new Line<>(e.getKey(), e.getValue()))
                .collect(ImmutableList.toImmutableList());

        for (int i=0;i<entries;i++) {
            ImmutableMap.Builder<K, V> mapBuilder = ImmutableMap.builder();

            int fact=1;
            for (Line<K,V> line: lines) {
                mapBuilder.put(line.key, line.get((i/fact) % line.values.length));
                fact=fact*line.values.length;
            }

            listBuilder.add(mapBuilder.build());
        }
    }
    return listBuilder.build();
}
项目:Spring-cloud-gather    文件:ExchangeRatesServiceImplTest.java   
@Test
public void shouldConvertCurrency() {

    ExchangeRatesContainer container = new ExchangeRatesContainer();
    container.setRates(ImmutableMap.of(
            Currency.EUR.name(), new BigDecimal("0.8"),
            Currency.RUB.name(), new BigDecimal("80")
    ));

    when(client.getRates(Currency.getBase())).thenReturn(container);

    final BigDecimal amount = new BigDecimal(100);
    final BigDecimal expectedConvertionResult = new BigDecimal("1.25");

    BigDecimal result = ratesService.convert(Currency.RUB, Currency.USD, amount);

    assertTrue(expectedConvertionResult.compareTo(result) == 0);
}
项目:dotwebstack-framework    文件:RefSchemaMapper.java   
@Override
public Object mapGraphValue(@NonNull RefProperty schema,
    @NonNull GraphEntityContext graphEntityContext,
    @NonNull ValueContext valueContext,
    @NonNull SchemaMapperAdapter schemaMapperAdapter) {

  Model refModel = graphEntityContext.getSwaggerDefinitions().get(schema.getSimpleRef());

  if (refModel == null) {
    throw new SchemaMapperRuntimeException(String.format(
        "Unable to resolve reference to swagger model: '%s'.", schema.getSimpleRef()));
  }

  Builder<String, Object> builder = ImmutableMap.builder();
  refModel.getProperties().forEach((propKey, propValue) -> builder.put(propKey,
      Optional.fromNullable(schemaMapperAdapter.mapGraphValue(propValue, graphEntityContext,
          valueContext, schemaMapperAdapter))));

  return builder.build();
}
项目:radosgw-admin4j    文件:RgwAdminImpl.java   
@Override
public void setUserQuota(String userId, long maxObjects, long maxSizeKB) {
  HttpUrl.Builder urlBuilder =
      HttpUrl.parse(endpoint)
          .newBuilder()
          .addPathSegment("user")
          .query("quota")
          .addQueryParameter("uid", userId)
          .addQueryParameter("quota-type", "user");

  String body =
      gson.toJson(
          ImmutableMap.of(
              "max_objects", String.valueOf(maxObjects),
              "max_size_kb", String.valueOf(maxSizeKB),
              "enabled", "true"));

  Request request =
      new Request.Builder().put(RequestBody.create(null, body)).url(urlBuilder.build()).build();

  safeCall(request);
}
项目:Elasticsearch    文件:Mapping.java   
public Mapping(Version indexCreated, RootObjectMapper rootObjectMapper, MetadataFieldMapper[] metadataMappers, SourceTransform[] sourceTransforms, ImmutableMap<String, Object> meta) {
    this.indexCreated = indexCreated;
    this.metadataMappers = metadataMappers;
    ImmutableMap.Builder<Class<? extends MetadataFieldMapper>, MetadataFieldMapper> builder = ImmutableMap.builder();
    for (MetadataFieldMapper metadataMapper : metadataMappers) {
        if (indexCreated.before(Version.V_2_0_0_beta1) && LEGACY_INCLUDE_IN_OBJECT.contains(metadataMapper.name())) {
            rootObjectMapper = rootObjectMapper.copyAndPutMapper(metadataMapper);
        }
        builder.put(metadataMapper.getClass(), metadataMapper);
    }
    this.root = rootObjectMapper;
    // keep root mappers sorted for consistent serialization
    Arrays.sort(metadataMappers, new Comparator<Mapper>() {
        @Override
        public int compare(Mapper o1, Mapper o2) {
            return o1.name().compareTo(o2.name());
        }
    });
    this.metadataMappersMap = builder.build();
    this.sourceTransforms = sourceTransforms;
    this.meta = meta;
}
项目:verify-matching-service-adapter    文件:UserAccountCreationAttributeExtractorTest.java   
@Test
public void shouldReturnRequiredCycle3AttributesWhenValuesExistInCycle3Assertion(){
    List<Attribute> accountCreationAttributes = Arrays.asList(CYCLE_3).stream()
            .map(attributeQueryAttributeFactory::createAttribute)
            .collect(toList());

    ImmutableMap<String, String> build = ImmutableMap.<String, String>builder().put("cycle3Key", "cycle3Value").build();
    Cycle3Dataset cycle3Dataset = Cycle3Dataset.createFromData(build);
    HubAssertion hubAssertion =new HubAssertion("1", "issuerId", DateTime.now(), new PersistentId("1"), null, Optional.of(cycle3Dataset));

    List<Attribute> userAttributesForAccountCreation = userAccountCreationAttributeExtractor.getUserAccountCreationAttributes(accountCreationAttributes, null, Optional.of(hubAssertion));

    List<Attribute> cycle_3 = userAttributesForAccountCreation.stream().filter(a -> a.getName().equals("cycle_3")).collect(toList());
    StringBasedMdsAttributeValue personName = (StringBasedMdsAttributeValue) cycle_3.get(0).getAttributeValues().get(0);

    assertThat(cycle_3.size()).isEqualTo(1);
    assertThat(personName.getValue().equals("cycle3Value"));
}
项目:dotwebstack-framework    文件:OpenApiRequestMapperTest.java   
@Test
public void map_ThrowsException_EndpointWithoutProduces() throws IOException {
  // Arrange
  mockDefinition().host(DBEERPEDIA.OPENAPI_HOST).path("/breweries",
      new Path().get(new Operation().vendorExtensions(
          ImmutableMap.of(OpenApiSpecificationExtensions.INFORMATION_PRODUCT,
              DBEERPEDIA.BREWERIES.stringValue())).response(Status.OK.getStatusCode(),
                  new Response().schema(mock(Property.class)))));

  // Assert
  thrown.expect(ConfigurationException.class);
  thrown.expectMessage(String.format("Path '%s' should produce at least one media type.",
      "/" + DBEERPEDIA.OPENAPI_HOST + "/breweries"));

  // Act
  requestMapper.map(httpConfigurationMock);
}
项目:BUILD_file_generator    文件:UserDefinedResolverTest.java   
/** Tests situation when only a subset of classes are to be mapped. */
@Test
public void filteredMapping() {
  ImmutableList<String> lines =
      ImmutableList.of(
          "com.test.stuff,//java/com/test/stuff:target",
          "com.test.hello,//java/com/test/other:target");

  ImmutableMap<String, BuildRule> actual =
      (new UserDefinedResolver(lines)).resolve(ImmutableSet.of("com.test.stuff"));

  assertThat(actual)
      .containsExactly(
          "com.test.stuff", ExternalBuildRule.create("//java/com/test/stuff:target"));
  assertThat(actual).doesNotContainKey("com.test.hello");
}
项目:firebase-admin-java    文件:UserRecordTest.java   
@Test
public void testUserIdOnly() throws IOException {
  String json = JSON_FACTORY.toString(ImmutableMap.of("localId", "user"));
  UserRecord userRecord = parseUser(json);
  assertEquals("user", userRecord.getUid());
  assertNull(userRecord.getEmail());
  assertNull(userRecord.getPhoneNumber());
  assertNull(userRecord.getPhotoUrl());
  assertNull(userRecord.getDisplayName());
  assertEquals(0L, userRecord.getUserMetadata().getCreationTimestamp());
  assertEquals(0L, userRecord.getUserMetadata().getLastSignInTimestamp());
  assertEquals(0, userRecord.getCustomClaims().size());
  assertFalse(userRecord.isDisabled());
  assertFalse(userRecord.isEmailVerified());
  assertEquals(0, userRecord.getProviderData().length);
}
项目:dotwebstack-framework    文件:RefSchemaMapperTest.java   
@Test
public void mapGraphValue_ReturnsResults_WhenRefCanBeResolved() {
  // Arrange
  property.set$ref(DUMMY_REF);
  Model refModel = new ModelImpl();
  refModel.setProperties(ImmutableMap.of(KEY_1, PROPERTY_1, KEY_2, PROPERTY_2));

  when(entityBuilderContext.getLdPathExecutor()).thenReturn(ldPathExecutor);
  when(entityBuilderContext.getSwaggerDefinitions()).thenReturn(
      ImmutableMap.of(property.getSimpleRef(), refModel));
  when(ldPathExecutor.ldPathQuery(context, LD_PATH_QUERY)).thenReturn(ImmutableList.of(VALUE_2));

  // Act
  Map<String, Object> result =
      (Map<String, Object>) schemaMapper.mapGraphValue(property, entityBuilderContext,
          ValueContext.builder().value(context).build(), schemaMapperAdapter);

  // Assert
  assertThat(result.keySet(), hasSize(2));
  assertEquals(((Optional) result.get(KEY_1)).orNull(), VALUE_1.stringValue());
  assertEquals(((Optional) result.get(KEY_2)).orNull(), VALUE_2.intValue());
}
项目:dremio-oss    文件:TestGeoPointType.java   
@Test
public void testSelectArrayOfGeoPointField() throws Exception {

  ColumnData[] data = new ColumnData[]{
          new ColumnData("location_field", GEO_POINT, new Object[][]{
                  {ImmutableMap.of("lat", 42.1, "lon", -31.66), ImmutableMap.of("lat", 35.6, "lon", -42.1)},
                  {ImmutableMap.of("lat", 23.1, "lon", -23.01), ImmutableMap.of("lat", -23.0, "lon", 9)}
          })
  };

  elastic.load(schema, table, data);


  logger.info("--> mapping:\n{}", elastic.mapping(schema, table));
  logger.info("--> search:\n{}", elastic.search(schema, table));

  testRunAndPrint(UserBitShared.QueryType.SQL, "select t.location_field from elasticsearch." + schema + "." + table + " t");

  testBuilder()
          .sqlQuery("select t.location_field[1].lat as lat_1 from elasticsearch." + schema + "." + table + " t")
          .unOrdered()
          .baselineColumns("lat_1")
          .baselineValues(35.6)
          .baselineValues(-23.0)
          .go();
}
项目:hashsdn-controller    文件:BindingTestContext.java   
public void startNewDomDataBroker() {
    checkState(this.executor != null, "Executor needs to be set");
    final InMemoryDOMDataStore operStore = new InMemoryDOMDataStore("OPER",
        MoreExecutors.newDirectExecutorService());
    final InMemoryDOMDataStore configStore = new InMemoryDOMDataStore("CFG",
        MoreExecutors.newDirectExecutorService());
    this.newDatastores = ImmutableMap.<LogicalDatastoreType, DOMStore>builder()
            .put(LogicalDatastoreType.OPERATIONAL, operStore)
            .put(LogicalDatastoreType.CONFIGURATION, configStore)
            .build();

    this.newDOMDataBroker = new SerializedDOMDataBroker(this.newDatastores, this.executor);

    this.mockSchemaService.registerSchemaContextListener(configStore);
    this.mockSchemaService.registerSchemaContextListener(operStore);
}
项目:dotwebstack-framework    文件:RedirectionResourceProviderTest.java   
@Test
public void loadResources_LoadRedirection_WithValidData() {
  // Arrange
  when(graphQuery.evaluate()).thenReturn(new IteratingGraphQueryResult(ImmutableMap.of(),
      ImmutableList.of(
          valueFactory.createStatement(DBEERPEDIA.ID2DOC_REDIRECTION, RDF.TYPE, ELMO.REDIRECTION),
          valueFactory.createStatement(DBEERPEDIA.ID2DOC_REDIRECTION, ELMO.URL_PATTERN,
              DBEERPEDIA.ID2DOC_URL_PATTERN),
          valueFactory.createStatement(DBEERPEDIA.ID2DOC_REDIRECTION, ELMO.STAGE_PROP,
              DBEERPEDIA.STAGE),
          valueFactory.createStatement(DBEERPEDIA.ID2DOC_REDIRECTION, ELMO.TARGET_URL,
              DBEERPEDIA.ID2DOC_TARGET_URL))));

  // Act
  redirectionResourceProvider.loadResources();

  // Assert
  assertThat(redirectionResourceProvider.getAll().entrySet(), hasSize(1));
  Redirection redirection = redirectionResourceProvider.get(DBEERPEDIA.ID2DOC_REDIRECTION);
  assertThat(redirection, is(not(nullValue())));
  assertThat(redirection.getUrlPattern(), equalTo(DBEERPEDIA.ID2DOC_URL_PATTERN.stringValue()));
  assertThat(redirection.getStage(), equalTo(stage));
  assertThat(redirection.getTargetUrl(), equalTo(DBEERPEDIA.ID2DOC_TARGET_URL.stringValue()));
}
项目:tac-kbp-eal    文件:LinkingStoreSource.java   
private Optional<ResponseLinking> read(Symbol docID, Set<Response> responses,
    Optional<ImmutableMap<String, String>> foreignResponseIDToLocal,
    Optional<ImmutableMap.Builder<String, String>> foreignLinkingIdToLocal)
    throws IOException {
  checkNotClosed();

  final File f;
  try {
    f = AssessmentSpecFormats.bareOrWithSuffix(directory, docID.toString(),
        ACCEPTABLE_SUFFIXES);
  } catch (FileNotFoundException ioe) {
    return Optional.absent();
  }

  return Optional.of(linkingLoader.read(docID, Files.asCharSource(f, UTF_8), responses,
      foreignResponseIDToLocal, foreignLinkingIdToLocal));
}
项目:Elasticsearch    文件:GetFieldMappingsResponse.java   
/**
 * Returns the mappings of a specific field.
 *
 * @param field field name as specified in the {@link GetFieldMappingsRequest}
 * @return FieldMappingMetaData for the requested field or null if not found.
 */
public FieldMappingMetaData fieldMappings(String index, String type, String field) {
    ImmutableMap<String, ImmutableMap<String, FieldMappingMetaData>> indexMapping = mappings.get(index);
    if (indexMapping == null) {
        return null;
    }
    ImmutableMap<String, FieldMappingMetaData> typeMapping = indexMapping.get(type);
    if (typeMapping == null) {
        return null;
    }
    return typeMapping.get(field);
}
项目:bromium    文件:URLUtilsTest.java   
@Test
public void canConstructQueryString() {
    Map<String, String> map = ImmutableMap.of("k1", "v1", "k2", "v2");
    String expected = "?k1=v1&k2=v2";
    String actual = URLUtils.toQueryString(map);
    assertEquals(expected, actual);
}
项目:jira-steps-plugin    文件:JiraService.java   
public ResponseData<Object> addComment(final String issueIdorKey, final String comment) {
  try {
    return parseResponse(jiraEndPoints
        .addComment(issueIdorKey, ImmutableMap.builder().put("body", comment).build()).execute());
  } catch (Exception e) {
    return buildErrorResponse(e);
  }
}
项目:apollo-custom    文件:ConfigIntegrationTest.java   
@Test
public void testGetConfigWithNoLocalFileAndRemoteConfigServiceRetry() throws Exception {
  String someKey = "someKey";
  String someValue = "someValue";
  ApolloConfig apolloConfig = assembleApolloConfig(ImmutableMap.of(someKey, someValue));
  boolean failedAtFirstTime = true;
  ContextHandler handler =
      mockConfigServerHandler(HttpServletResponse.SC_OK, apolloConfig, failedAtFirstTime);
  startServerWithHandlers(handler);

  Config config = ConfigService.getAppConfig();

  assertEquals(someValue, config.getProperty(someKey, null));
}
项目:dropwizard-influxdb-reporter    文件:DropwizardMeasurementTest.java   
@Test
public void testFromLine_DeserializesWithTags() {
  final DropwizardMeasurement expected = DropwizardMeasurement.create(
    "Measurement",
    ImmutableMap.of("action", "restore", "model", "cf-2-005"),
    Optional.empty()
  );
  assertEquals(expected, DropwizardMeasurement.fromLine("Measurement,action=restore,model=cf-2-005"));
}
项目:buckaroo    文件:ResolvedDependenciesTest.java   
@Test
public void isComplete1() throws Exception {

    final ResolvedDependencies a = ResolvedDependencies.of(ImmutableMap.of(
        RecipeIdentifier.of("org", "project"),
        Pair.with(
            SemanticVersion.of(1),
            RecipeVersion.of(
                Either.left(GitCommit.of("https://github.com/magicco/magiclib/commit", "b0215d5")),
                Optional.of("my-magic-lib"),
                DependencyGroup.of(),
                Optional.empty()))));

    assertTrue(a.isComplete());
}
项目:circus-train    文件:TableAndMetadataComparatorTest.java   
@Test
public void allShortCircuit() {
  left.getTable().getParameters().put("com.company.key", "value");
  left.getTable().setPartitionKeys(ImmutableList.of(new FieldSchema("p", "string", "p comment")));
  left.getTable().setOwner("left owner");
  List<PrivilegeGrantInfo> privilege = ImmutableList.of(new PrivilegeGrantInfo());
  left.getTable().setPrivileges(new PrincipalPrivilegeSet(ImmutableMap.of("write", privilege), null, null));
  left.getTable().setRetention(2);
  left.getTable().setTableType("internal");
  left.getTable().getSd().setLocation("left");
  left.getTable().getSd().setInputFormat("LeftInputFormat");
  left.getTable().getSd().setOutputFormat("LeftOutputFormat");
  left.getTable().getSd().getParameters().put("com.company.key", "value");
  left.getTable().getSd().getSerdeInfo().setName("left serde info");
  left.getTable().getSd().getSkewedInfo().setSkewedColNames(ImmutableList.of("left skewed col"));
  left.getTable().getSd().setCols(ImmutableList.of(new FieldSchema("left", "type", "comment")));
  left.getTable().getSd().setSortCols(ImmutableList.of(new Order()));
  left.getTable().getSd().setBucketCols(ImmutableList.of("bucket"));
  left.getTable().getSd().setNumBuckets(9000);

  List<Diff<Object, Object>> diffs = newTableAndMetadataComparator(SHORT_CIRCUIT).compare(left, right);

  assertThat(diffs, is(notNullValue()));
  assertThat(diffs.size(), is(1));
  assertThat(diffs.get(0), is(newPropertyDiff(TableAndMetadata.class, "table.parameters",
      left.getTable().getParameters(), right.getTable().getParameters())));
}
项目:secrets-proxy    文件:SecretDetailResponseV2.java   
public static Builder builder() {
    return new AutoValue_SecretDetailResponseV2.Builder()
            .checksum("")
            .description("")
            .type(null)
            .expiry(0)
            .metadata(ImmutableMap.of());
}
项目:centraldogma    文件:ContentServiceV1.java   
/**
 * GET /projects/{projectName}/repos/{repoName}/tree{path}?revision={revision}
 *
 * <p>Returns the list of files in the path.
 */
@Get("regex:/projects/(?<projectName>[^/]+)/repos/(?<repoName>[^/]+)/tree(?<path>(|/.*))$")
public CompletionStage<List<EntryDto<?>>> listFiles(@Param("path") String path,
                                                    @Param("revision") @Default("-1") String revision,
                                                    @RequestObject Repository repository) {
    final String path0 = rootDirIfEmpty(path);
    return listFiles(repository, path0, new Revision(revision),
                     ImmutableMap.of(FindOption.FETCH_CONTENT, false));
}
项目:dremio-oss    文件:ScanBuilder.java   
/**
 * Check the stack is valid for transformation. The following are
 *
 *   The stack must have a leaf that is an ElasticsearchScan
 *   The stack must not include a ElasitcsearchProject (this should have been removed in rel finalization prior to invoking ScanBuilder.
 *   The stack can only include the following rels (and only one each):
 *     ElasticsearchScanPrel, ElasticsearchFilter, ElasticsearchSample, ElasticsearchLimit
 *
 *   The order must be
 *   ElasticsearchSample (or ElasticsearchLimit) (optional)
 *       \
 *     ElasticsearchFilter (optional)
 *         \
 *       ElasticsearchScanPrel
 *
 * @param stack
 */
private  Map<Class<?>, ElasticsearchPrel> validate(List<ElasticsearchPrel> stack){
  final Map<Class<?>, ElasticsearchPrel> map = new HashMap<>();
  for(int i =0; i < stack.size(); i++){
    ElasticsearchPrel prel = stack.get(i);
    if(!CONSUMEABLE_RELS.contains(prel.getClass())){
      throw new IllegalStateException(String.format("ScanBuilder can't consume a %s.", prel.getClass().getName()));
    }
    if(map.containsKey(prel.getClass())){
      throw new IllegalStateException(String.format("ScanBuilder found more than one %s.", prel.getClass().getName()));
    }

    map.put(prel.getClass(), prel);
  }

  switch(stack.size()){
  case 0:
    throw new IllegalStateException("Stacks must include a scan.");
  case 1:
    Preconditions.checkArgument(stack.get(0) instanceof ElasticIntermediateScanPrel);
    break;
  case 2:
    Preconditions.checkArgument(stack.get(0) instanceof ElasticsearchSample || stack.get(0) instanceof ElasticsearchFilter || stack.get(0) instanceof ElasticsearchLimit);
    Preconditions.checkArgument(stack.get(1) instanceof ElasticIntermediateScanPrel);
    break;
  case 3:
    Preconditions.checkArgument(stack.get(0) instanceof ElasticsearchSample || stack.get(0) instanceof ElasticsearchLimit);
    Preconditions.checkArgument(stack.get(1) instanceof ElasticsearchFilter);
    Preconditions.checkArgument(stack.get(2) instanceof ElasticIntermediateScanPrel);
    break;
  default:
    throw new IllegalStateException(String.format("Stack should 1..3 in size, was %d in size.", stack.size()));
  }
  return ImmutableMap.copyOf(map);
}
项目:theskeleton    文件:ProfileRestControllerTest.java   
@Test
@WithMockUser("user123")
public void testFindProfileConnectedApps() throws Exception {
    final UserEntity user = new UserEntity().setUsername("user123");
    final OAuth2ClientEntity client = new OAuth2ClientEntity().setId("client123").setName("client123");
    final UserOAuth2ClientApprovalEntity approval1 = new UserOAuth2ClientApprovalEntity()
        .setUser(user)
        .setClient(client)
        .setScope("scope1")
        .setApprovalStatus(Approval.ApprovalStatus.APPROVED);
    final UserOAuth2ClientApprovalEntity approval2 = new UserOAuth2ClientApprovalEntity()
        .setUser(user)
        .setClient(client)
        .setScope("scope2")
        .setApprovalStatus(Approval.ApprovalStatus.DENIED);
    when(profileService.findOAuth2ClientApprovalByUsername("user123")).thenReturn(Arrays.asList(approval1, approval2));
    MockHttpServletRequestBuilder request = get("/api/profile/connected-apps")
        .contentType(MediaType.APPLICATION_JSON);
    MockHttpServletResponse response = mockMvc.perform(request)
        .andDo(document("user-profile-connected-apps-view"))
        .andReturn()
        .getResponse();
    assertThat(response.getStatus()).isEqualTo(200);
    CollectionType collectionType = objectMapper.getTypeFactory().constructCollectionType(List.class, UserOAuth2ClientApprovalRestData.class);
    List<UserOAuth2ClientApprovalRestData> returnedData = objectMapper
        .readValue(response.getContentAsByteArray(), collectionType);
    assertThat(returnedData).hasSize(1);
    UserOAuth2ClientApprovalRestData restData = returnedData.get(0);
    assertThat(restData.getClientId()).isEqualTo(client.getId());
    assertThat(restData.getClientName()).isEqualTo(client.getName());
    assertThat(restData.getUsername()).isEqualTo(user.getUsername());
    ImmutableMap<String, Approval.ApprovalStatus> scopeAndStatus = restData.getScopeAndStatus();
    assertThat(scopeAndStatus).hasSize(2);
    assertThat(scopeAndStatus).containsEntry(approval1.getScope(), approval1.getApprovalStatus());
    assertThat(scopeAndStatus).containsEntry(approval2.getScope(), approval2.getApprovalStatus());
    verify(profileService).findOAuth2ClientApprovalByUsername("user123");
}
项目:url-classifier    文件:QueryClassifierBuilder.java   
public QueryClassifierImpl(
    ImmutableSet<String> mayKeySet, Predicate<? super String> mayKeyClassifier,
    ImmutableSet<String> onceKeySet, Predicate<? super String> onceKeyClassifier,
    ImmutableSet<String> mustKeySet,
    ImmutableMap<String, Predicate<? super Optional<String>>> valueClassifierMap) {
  this.mayKeySet = mayKeySet;
  this.mayKeyClassifier = mayKeyClassifier;
  this.onceKeySet = onceKeySet;
  this.onceKeyClassifier = onceKeyClassifier;
  this.mustKeySet = mustKeySet;
  this.valueClassifierMap = valueClassifierMap;
}
项目:java-web-services-training    文件:GetGeonamesApplication.java   
public static void main(String[] args)
        throws IOException, URISyntaxException {
    RestTemplate restTemplate = new RestTemplate();
    GeonamesSearchResult searchResult = restTemplate.getForObject(
            "http://api.geonames.org/searchJSON?q={q}&username={username}",
        GeonamesSearchResult.class,
            ImmutableMap.of("q", "kabupaten garut", "username", "ceefour"));
    LOG.info("Body (GeonamesSearchResult): {}", searchResult);
    for (Geoname child : searchResult.getGeonames()) {
        LOG.info("Place: {} ({}, {})",
                child.getToponymName(), child.getLat(), child.getLng());
    }
}
项目:iron    文件:EntityStore.java   
public EntityStore(EntityDefinition<E> entityDefinition, Map<RelationDefinition, RelationStore> relationStores) {
    m_entityDefinition = entityDefinition;
    m_entityClass = entityDefinition.getEntityClass();
    m_entityName = entityDefinition.getEntityName();

    IdDefinition idDefinition = entityDefinition.getIdDefinition();
    m_idPropertyName = idDefinition != null ? idDefinition.getIdName() : null;

    m_attributes = ImmutableSet
            .copyOf(entityDefinition.getAttributes().values().stream().map(AttributeDefinition::getAttributeName).collect(Collectors.toList()));

    ImmutableMap.Builder<String, Map<Object, Long>> uniquesIndex = ImmutableMap.builder();
    entityDefinition.getUniqueConstraints().forEach(uniqueAttribute -> uniquesIndex.put(uniqueAttribute, new HashMap<>()));
    m_uniquesIndex = uniquesIndex.build();

    ImmutableSet.Builder<String> nonNullAttributes = ImmutableSet.builder();
    entityDefinition.getAttributes().values().stream() //
            .filter(attributeDefinition -> !attributeDefinition.isNullable()) //
            .forEach(attributeDefinition -> nonNullAttributes.add(attributeDefinition.getAttributeName()));
    m_nonNullAttributes = nonNullAttributes.build();

    ImmutableMap.Builder<String, RelationStore> relationStoresBuilder = ImmutableMap.builder();
    entityDefinition.getRelations().values().forEach(relationDefinition -> {
        RelationStore relationStore = relationStores.get(relationDefinition);
        relationStoresBuilder.put(relationDefinition.getRelationName(), relationStore);
    });
    m_relationStores = relationStoresBuilder.build();
}
项目:iextrading4j    文件:AbstractMarketDataRequestBuilder.java   
protected Map<String, String> getSymbols() {
    if (symbols != null) {
        return ImmutableMap.<String, String>builder()
                .put("symbols", symbols.stream().collect(joining(",")))
                .build();
    }
    return ImmutableMap.of();
}
项目:secrets-proxy    文件:PartialUpdateSecretRequestV2.java   
/**
 * Static factory method used by Jackson for deserialization
 */
@SuppressWarnings("unused")
@JsonCreator
public static PartialUpdateSecretRequestV2 fromParts(
        @JsonProperty("contentPresent") boolean contentPresent,
        @JsonProperty("content") @Nullable String content,
        @JsonProperty("descriptionPresent") boolean descriptionPresent,
        @JsonProperty("description") @Nullable String description,
        @JsonProperty("metadataPresent") boolean metadataPresent,
        @JsonProperty("metadata") @Nullable Map<String, String> metadata,
        @JsonProperty("expiryPresent") boolean expiryPresent,
        @JsonProperty("expiry") @Nullable Long expiry,
        @JsonProperty("typePresent") boolean typePresent,
        @JsonProperty("type") @Nullable String type) {
    return builder()
            .contentPresent(contentPresent)
            .content(Strings.nullToEmpty(content))
            .descriptionPresent(descriptionPresent)
            .description(Strings.nullToEmpty(description))
            .metadataPresent(metadataPresent)
            .metadata(metadata == null ? ImmutableMap.of() : ImmutableMap.copyOf(metadata))
            .expiryPresent(expiryPresent)
            .expiry(expiry == null ? Long.valueOf(0) : expiry)
            .typePresent(typePresent)
            .type(Strings.nullToEmpty(type))
            .build();
}
项目:firebase-admin-java    文件:UserRecordTest.java   
@Test
public void testEmptyCustomClaims() throws IOException {
  ImmutableMap<String, Object> resp = ImmutableMap.<String, Object>of(
      "localId", "user",
      "customAttributes", "{}"
  );
  String json = JSON_FACTORY.toString(resp);
  UserRecord userRecord = parseUser(json);
  assertEquals("user", userRecord.getUid());
  assertEquals(0, userRecord.getCustomClaims().size());
}
项目:cryptotrader    文件:CoincheckContextTest.java   
@Test(timeOut = 60 * 1000L)
public void testExecutePrivate() throws Exception {

    conf.addProperty(
            "com.after_sunrise.cryptocurrency.cryptotrader.service.coincheck.CoincheckContext.api.id",
            "my_id"
    );
    conf.addProperty(
            "com.after_sunrise.cryptocurrency.cryptotrader.service.coincheck.CoincheckContext.api.secret",
            "my_secret"
    );
    doReturn(Instant.ofEpochMilli(1234567890)).when(target).getNow();

    String path = "http://localhost:80/test";
    Map<String, String> params = ImmutableMap.of("foo", "bar");
    String data = "hoge";

    Map<String, String> headers = new LinkedHashMap<>();
    headers.put("Content-Type", "application/json");
    headers.put("ACCESS-KEY", "my_id");
    headers.put("ACCESS-NONCE", "1234567890");
    headers.put("ACCESS-SIGNATURE", "c1882128a3b8bcf13cec68d2dabf0ab867064f97afc90162624d32273a05b65a");
    doReturn("test").when(target).request(GET, path + "?foo=bar", headers, data);

    assertEquals(target.executePrivate(GET, path, params, data), "test");

}
项目:verify-service-provider    文件:AuthnRequestAcceptanceTest.java   
@Test
public void shouldGenerateValidAuthnRequestUsingDefaultEntityId() throws Exception {
    singleTenantApplication.before();
    Client client = new JerseyClientBuilder(singleTenantApplication.getEnvironment()).build("Test Client");

    setupComplianceToolWithDefaultEntityId(client);

    Response authnResponse = client
        .target(URI.create(String.format("http://localhost:%d/generate-request", singleTenantApplication.getLocalPort())))
        .request()
        .buildPost(Entity.json(new RequestGenerationBody(LevelOfAssurance.LEVEL_2, null)))
        .invoke();

    RequestResponseBody authnSaml = authnResponse.readEntity(RequestResponseBody.class);

    Response complianceToolResponse = client
        .target(authnSaml.getSsoLocation())
        .request()
        .buildPost(Entity.form(new MultivaluedHashMap<>(ImmutableMap.of("SAMLRequest", authnSaml.getSamlRequest()))))
        .invoke();

    JSONObject complianceToolResponseBody = new JSONObject(complianceToolResponse.readEntity(String.class));
    assertThat(complianceToolResponseBody.getJSONObject("status").get("message")).isEqualTo(null);
    assertThat(complianceToolResponseBody.getJSONObject("status").getString("status")).isEqualTo("PASSED");

    singleTenantApplication.after();
}
项目:CustomWorldGen    文件:B3DLoader.java   
public ModelWrapper(ResourceLocation modelLocation, B3DModel model, ImmutableSet<String> meshes, boolean smooth, boolean gui3d, int defaultKey, ImmutableMap<String, ResourceLocation> textures)
{
    this.modelLocation = modelLocation;
    this.model = model;
    this.meshes = meshes;
    this.textures = textures;
    this.smooth = smooth;
    this.gui3d = gui3d;
    this.defaultKey = defaultKey;
}
项目:Clef    文件:BakedModelInstrument.java   
@Override
public Pair<? extends IBakedModel, Matrix4f> handlePerspective(ItemCameraTransforms.TransformType type)
{
    if(instrument != null)
    {
        HashMap<ItemCameraTransforms.TransformType, TRSRTransformation> map = new HashMap<>();
        map.put(ItemCameraTransforms.TransformType.FIRST_PERSON_LEFT_HAND, new TRSRTransformation(new Vector3f(1F, 0F, 1F), TRSRTransformation.quatFromXYZDegrees(new Vector3f(0F, 180F, 0F)), new Vector3f(1F, 1F, 1F), new Quat4f()));
        map.put(ItemCameraTransforms.TransformType.THIRD_PERSON_LEFT_HAND, new TRSRTransformation(new Vector3f(0.1F, 0F + (instrument.handImg.getHeight() <= 16F ? 0F : MathHelper.clamp((float)instrument.info.activeHandPosition[1], -0.3F, 0.3F)), 0.025F - (instrument.handImg.getWidth() <= 16F ? 0F : MathHelper.clamp((float)instrument.info.activeHandPosition[0], -0.5F, 0.5F))), TRSRTransformation.quatFromXYZDegrees(new Vector3f(0F, 80F, 0F)), new Vector3f(-1F, 1F, 1F),  TRSRTransformation.quatFromXYZDegrees(new Vector3f(0F, 0F, 0F))));
        map.put(ItemCameraTransforms.TransformType.THIRD_PERSON_RIGHT_HAND, new TRSRTransformation(new Vector3f(-0.1F, 0F + (instrument.handImg.getHeight() <= 16F ? 0F : MathHelper.clamp((float)instrument.info.activeHandPosition[1], -0.3F, 0.3F)), 1F - (instrument.handImg.getWidth() <= 16F ? 0F : MathHelper.clamp((float)instrument.info.activeHandPosition[0], -0.5F, 0.5F))), TRSRTransformation.quatFromXYZDegrees(new Vector3f(0F, 80F, 0F)), new Vector3f(1F, 1F, 1F), TRSRTransformation.quatFromXYZDegrees(new Vector3f(0F, 0F, 0F))));
        ImmutableMap<ItemCameraTransforms.TransformType, TRSRTransformation> transforms = ImmutableMap.copyOf(map);
        return PerspectiveMapWrapper.handlePerspective(ModelBaseWrapper.isEntityRender(type) ? instrument.handModel : instrument.iconModel, transforms, type);
    }
    return PerspectiveMapWrapper.handlePerspective(this, transforms, type);
}