Java Code Examples for com.google.common.collect.ImmutableMap

The following are top voted examples for showing how to use com.google.common.collect.ImmutableMap. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: CustomWorldGen   File: PersistentRegistryManager.java   View source code 7 votes vote down vote up
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.");
}
 
Example 2
Project: buckaroo   File: MoreObservablesTest.java   View source code 6 votes vote down vote up
@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);
}
 
Example 3
Project: generator-thundr-gae-react   File: MagicLinkService.java   View source code 6 votes vote down vote up
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();
}
 
Example 4
Project: buckaroo   File: MoreObservablesTest.java   View source code 6 votes vote down vote up
@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);
}
 
Example 5
Project: hashsdn-controller   File: ShardDataTreeSnapshotTest.java   View source code 6 votes vote down vote up
@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());
}
 
Example 6
Project: de.flapdoodle.solid   File: Multimaps.java   View source code 6 votes vote down vote up
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();
}
 
Example 7
Project: Spring-cloud-gather   File: ExchangeRatesServiceImplTest.java   View source code 6 votes vote down vote up
@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);
}
 
Example 8
Project: dotwebstack-framework   File: RefSchemaMapper.java   View source code 6 votes vote down vote up
@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();
}
 
Example 9
Project: radosgw-admin4j   File: RgwAdminImpl.java   View source code 6 votes vote down vote up
@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);
}
 
Example 10
Project: Elasticsearch   File: Mapping.java   View source code 6 votes vote down vote up
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;
}
 
Example 11
Project: verify-matching-service-adapter   File: UserAccountCreationAttributeExtractorTest.java   View source code 6 votes vote down vote up
@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"));
}
 
Example 12
Project: dotwebstack-framework   File: OpenApiRequestMapperTest.java   View source code 6 votes vote down vote up
@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);
}
 
Example 13
Project: BUILD_file_generator   File: UserDefinedResolverTest.java   View source code 6 votes vote down vote up
/** 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");
}
 
Example 14
Project: firebase-admin-java   File: UserRecordTest.java   View source code 6 votes vote down vote up
@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);
}
 
Example 15
Project: dotwebstack-framework   File: RefSchemaMapperTest.java   View source code 6 votes vote down vote up
@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());
}
 
Example 16
Project: dremio-oss   File: TestGeoPointType.java   View source code 6 votes vote down vote up
@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();
}
 
Example 17
Project: hashsdn-controller   File: BindingTestContext.java   View source code 6 votes vote down vote up
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);
}
 
Example 18
Project: dotwebstack-framework   File: RedirectionResourceProviderTest.java   View source code 6 votes vote down vote up
@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()));
}
 
Example 19
Project: tac-kbp-eal   File: LinkingStoreSource.java   View source code 6 votes vote down vote up
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));
}
 
Example 20
Project: Elasticsearch   File: GetFieldMappingsResponse.java   View source code 5 votes vote down vote up
/**
 * 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);
}
 
Example 21
Project: bromium   File: URLUtilsTest.java   View source code 5 votes vote down vote up
@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);
}
 
Example 22
Project: jira-steps-plugin   File: JiraService.java   View source code 5 votes vote down vote up
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);
  }
}
 
Example 23
Project: apollo-custom   File: ConfigIntegrationTest.java   View source code 5 votes vote down vote up
@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));
}
 
Example 24
Project: dropwizard-influxdb-reporter   File: DropwizardMeasurementTest.java   View source code 5 votes vote down vote up
@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"));
}
 
Example 25
Project: buckaroo   File: ResolvedDependenciesTest.java   View source code 5 votes vote down vote up
@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());
}
 
Example 26
Project: circus-train   File: TableAndMetadataComparatorTest.java   View source code 5 votes vote down vote up
@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())));
}
 
Example 27
Project: secrets-proxy   File: SecretDetailResponseV2.java   View source code 5 votes vote down vote up
public static Builder builder() {
    return new AutoValue_SecretDetailResponseV2.Builder()
            .checksum("")
            .description("")
            .type(null)
            .expiry(0)
            .metadata(ImmutableMap.of());
}
 
Example 28
Project: centraldogma   File: ContentServiceV1.java   View source code 5 votes vote down vote up
/**
 * 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));
}
 
Example 29
Project: dremio-oss   File: ScanBuilder.java   View source code 5 votes vote down vote up
/**
 * 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);
}
 
Example 30
Project: theskeleton   File: ProfileRestControllerTest.java   View source code 5 votes vote down vote up
@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");
}
 
Example 31
Project: url-classifier   File: QueryClassifierBuilder.java   View source code 5 votes vote down vote up
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;
}
 
Example 32
Project: java-web-services-training   File: GetGeonamesApplication.java   View source code 5 votes vote down vote up
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());
	}
}
 
Example 33
Project: iron   File: EntityStore.java   View source code 5 votes vote down vote up
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();
}
 
Example 34
Project: iextrading4j   File: AbstractMarketDataRequestBuilder.java   View source code 5 votes vote down vote up
protected Map<String, String> getSymbols() {
    if (symbols != null) {
        return ImmutableMap.<String, String>builder()
                .put("symbols", symbols.stream().collect(joining(",")))
                .build();
    }
    return ImmutableMap.of();
}
 
Example 35
Project: secrets-proxy   File: PartialUpdateSecretRequestV2.java   View source code 5 votes vote down vote up
/**
 * 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();
}
 
Example 36
Project: firebase-admin-java   File: UserRecordTest.java   View source code 5 votes vote down vote up
@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());
}
 
Example 37
Project: cryptotrader   File: CoincheckContextTest.java   View source code 5 votes vote down vote up
@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");

}
 
Example 38
Project: verify-service-provider   File: AuthnRequestAcceptanceTest.java   View source code 5 votes vote down vote up
@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();
}
 
Example 39
Project: CustomWorldGen   File: B3DLoader.java   View source code 5 votes vote down vote up
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;
}
 
Example 40
Project: Clef   File: BakedModelInstrument.java   View source code 5 votes vote down vote up
@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);
}