java类com.google.common.collect.ImmutableMap的实例源码

PersistentRegistryManager.java 文件源码 项目:CustomWorldGen 阅读 40 收藏 0 点赞 0 评论 0
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.");
}
MoreObservablesTest.java 文件源码 项目:buckaroo 阅读 39 收藏 0 点赞 0 评论 0
@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);
}
MagicLinkService.java 文件源码 项目:generator-thundr-gae-react 阅读 38 收藏 0 点赞 0 评论 0
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();
}
MoreObservablesTest.java 文件源码 项目:buckaroo 阅读 39 收藏 0 点赞 0 评论 0
@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);
}
ShardDataTreeSnapshotTest.java 文件源码 项目:hashsdn-controller 阅读 25 收藏 0 点赞 0 评论 0
@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());
}
Multimaps.java 文件源码 项目:de.flapdoodle.solid 阅读 39 收藏 0 点赞 0 评论 0
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();
}
ExchangeRatesServiceImplTest.java 文件源码 项目:Spring-cloud-gather 阅读 46 收藏 0 点赞 0 评论 0
@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);
}
RefSchemaMapper.java 文件源码 项目:dotwebstack-framework 阅读 33 收藏 0 点赞 0 评论 0
@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();
}
RgwAdminImpl.java 文件源码 项目:radosgw-admin4j 阅读 43 收藏 0 点赞 0 评论 0
@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);
}
Mapping.java 文件源码 项目:Elasticsearch 阅读 43 收藏 0 点赞 0 评论 0
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;
}
UserAccountCreationAttributeExtractorTest.java 文件源码 项目:verify-matching-service-adapter 阅读 32 收藏 0 点赞 0 评论 0
@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"));
}
OpenApiRequestMapperTest.java 文件源码 项目:dotwebstack-framework 阅读 64 收藏 0 点赞 0 评论 0
@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);
}
UserDefinedResolverTest.java 文件源码 项目:BUILD_file_generator 阅读 47 收藏 0 点赞 0 评论 0
/** 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");
}
UserRecordTest.java 文件源码 项目:firebase-admin-java 阅读 41 收藏 0 点赞 0 评论 0
@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);
}
RefSchemaMapperTest.java 文件源码 项目:dotwebstack-framework 阅读 33 收藏 0 点赞 0 评论 0
@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());
}
TestGeoPointType.java 文件源码 项目:dremio-oss 阅读 31 收藏 0 点赞 0 评论 0
@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();
}
BindingTestContext.java 文件源码 项目:hashsdn-controller 阅读 38 收藏 0 点赞 0 评论 0
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);
}
RedirectionResourceProviderTest.java 文件源码 项目:dotwebstack-framework 阅读 45 收藏 0 点赞 0 评论 0
@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()));
}
LinkingStoreSource.java 文件源码 项目:tac-kbp-eal 阅读 33 收藏 0 点赞 0 评论 0
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));
}
GetFieldMappingsResponse.java 文件源码 项目:Elasticsearch 阅读 29 收藏 0 点赞 0 评论 0
/**
 * 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);
}
URLUtilsTest.java 文件源码 项目:bromium 阅读 33 收藏 0 点赞 0 评论 0
@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);
}
JiraService.java 文件源码 项目:jira-steps-plugin 阅读 33 收藏 0 点赞 0 评论 0
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);
  }
}
ConfigIntegrationTest.java 文件源码 项目:apollo-custom 阅读 45 收藏 0 点赞 0 评论 0
@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));
}
DropwizardMeasurementTest.java 文件源码 项目:dropwizard-influxdb-reporter 阅读 30 收藏 0 点赞 0 评论 0
@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"));
}
ResolvedDependenciesTest.java 文件源码 项目:buckaroo 阅读 35 收藏 0 点赞 0 评论 0
@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());
}
TableAndMetadataComparatorTest.java 文件源码 项目:circus-train 阅读 37 收藏 0 点赞 0 评论 0
@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())));
}
SecretDetailResponseV2.java 文件源码 项目:secrets-proxy 阅读 43 收藏 0 点赞 0 评论 0
public static Builder builder() {
    return new AutoValue_SecretDetailResponseV2.Builder()
            .checksum("")
            .description("")
            .type(null)
            .expiry(0)
            .metadata(ImmutableMap.of());
}
ContentServiceV1.java 文件源码 项目:centraldogma 阅读 23 收藏 0 点赞 0 评论 0
/**
 * 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));
}
ScanBuilder.java 文件源码 项目:dremio-oss 阅读 26 收藏 0 点赞 0 评论 0
/**
 * 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);
}
ProfileRestControllerTest.java 文件源码 项目:theskeleton 阅读 32 收藏 0 点赞 0 评论 0
@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");
}


问题


面经


文章

微信
公众号

扫码关注公众号