Java 类com.google.common.collect.ImmutableList 实例源码

项目:presto-ethereum    文件:EthereumRecordSetProvider.java   
@Override
public RecordSet getRecordSet(
        ConnectorTransactionHandle transaction,
        ConnectorSession session,
        ConnectorSplit split,
        List<? extends ColumnHandle> columns
) {
    EthereumSplit ethereumSplit = convertSplit(split);

    ImmutableList.Builder<EthereumColumnHandle> handleBuilder = ImmutableList.builder();

    for (ColumnHandle handle : columns) {
        EthereumColumnHandle columnHandle = convertColumnHandle(handle);
        handleBuilder.add(columnHandle);
    }

    return new EthereumRecordSet(web3j, handleBuilder.build(), ethereumSplit);
}
项目:QDrill    文件:ShowSchemasHandler.java   
/** Rewrite the parse tree as SELECT ... FROM INFORMATION_SCHEMA.SCHEMATA ... */
@Override
public SqlNode rewrite(SqlNode sqlNode) throws RelConversionException, ForemanSetupException {
  SqlShowSchemas node = unwrap(sqlNode, SqlShowSchemas.class);
  List<SqlNode> selectList =
      ImmutableList.of((SqlNode) new SqlIdentifier(SCHS_COL_SCHEMA_NAME, SqlParserPos.ZERO));

  SqlNode fromClause = new SqlIdentifier(
      ImmutableList.of(IS_SCHEMA_NAME, TAB_SCHEMATA), null, SqlParserPos.ZERO, null);

  SqlNode where = null;
  final SqlNode likePattern = node.getLikePattern();
  if (likePattern != null) {
    where = DrillParserUtil.createCondition(new SqlIdentifier(SCHS_COL_SCHEMA_NAME, SqlParserPos.ZERO),
                                            SqlStdOperatorTable.LIKE, likePattern);
  } else if (node.getWhereClause() != null) {
    where = node.getWhereClause();
  }

  return new SqlSelect(SqlParserPos.ZERO, null, new SqlNodeList(selectList, SqlParserPos.ZERO),
      fromClause, where, null, null, null, null, null, null);
}
项目:buckaroo    文件:RecipeSources.java   
public static Process<Event, RecipeIdentifier> selectDependency(final RecipeSource source, final PartialDependency dependency) {
    if (dependency.organization.isPresent()) {
        return Process.of(
            Single.just(RecipeIdentifier.of(dependency.source, dependency.organization.get(), dependency.project))
        );
    }
    final ImmutableList<RecipeIdentifier> candidates = Streams.stream(source
        .findCandidates(dependency))
        .limit(5)
        .collect(toImmutableList());

    if (candidates.size() == 0) {
        return Process.error(
            PartialDependencyResolutionException.of(candidates, dependency));
    }

    if (candidates.size() > 1) {
        return Process.error(PartialDependencyResolutionException.of(candidates, dependency));
    }

    return Process.of(
        Observable.just(
            Notification.of("Resolved partial dependency " + dependency.encode() + " to " + candidates.get(0).encode())),
        Single.just(candidates.get(0)));
}
项目:circus-train    文件:TestUtils.java   
private static String expandHql(
    String database,
    String table,
    List<FieldSchema> dataColumns,
    List<FieldSchema> partitionColumns) {
  List<String> dataColumnNames = toQualifiedColumnNames(table, dataColumns);
  List<String> partitionColumnNames = partitionColumns != null ? toQualifiedColumnNames(table, partitionColumns)
      : ImmutableList.<String> of();
  List<String> colNames = ImmutableList
      .<String> builder()
      .addAll(dataColumnNames)
      .addAll(partitionColumnNames)
      .build();

  String cols = COMMA_JOINER.join(colNames);
  return String.format("SELECT %s FROM `%s`.`%s`", cols, database, table);
}
项目:morf    文件:TestHumanReadableStatements.java   
/**
 * Tests that the upgrade comes out in the right order.
 */
@Test
public void testRemoveMultipleColumns() {
  List<Class<? extends UpgradeStep>> items = ImmutableList.<Class<? extends UpgradeStep>>of(
    UpgradeStep511.class
  );

  ListBackedHumanReadableStatementConsumer consumer = new ListBackedHumanReadableStatementConsumer();
  HumanReadableStatementProducer producer = new HumanReadableStatementProducer(items);
  producer.produceFor(consumer);

  List<String> actual = consumer.getList();

  List<String> expected = ImmutableList.of(
    "VERSIONSTART:[ALFA v1.0.0]",
    "STEPSTART:[SAMPLE-7]-[UpgradeStep511]-[5.1.1 Upgrade Step]",
    "CHANGE:[Remove column abc from SomeTable]",
    "CHANGE:[Remove column def from SomeTable]",
    "STEPEND:[UpgradeStep511]",
    "VERSIONEND:[ALFA v1.0.0]"
  );

  assertEquals(expected, actual);
}
项目:dremio-oss    文件:FlattenTemplate.java   
@Override
public final void setup(BufferAllocator allocator, FunctionContext context, VectorAccessible incoming, VectorAccessible outgoing,
                        List<TransferPair> transfers, ComplexWriterCreator complexWriterCollector,
                        long outputMemoryLimit, long outputBatchSize)  throws SchemaChangeException{

  this.svMode = incoming.getSchema().getSelectionVectorMode();
  switch (svMode) {
    case FOUR_BYTE:
      throw new UnsupportedOperationException("Flatten does not support selection vector inputs.");
    case TWO_BYTE:
      throw new UnsupportedOperationException("Flatten does not support selection vector inputs.");
  }
  this.transfers = ImmutableList.copyOf(transfers);
  outputAllocator = allocator;
  this.outputMemoryLimit = outputMemoryLimit;
  this.outputLimit = outputBatchSize;
  doSetup(context, incoming, outgoing, complexWriterCollector);
}
项目:android-auto-mapper    文件:AutoMappperProcessor.java   
private ImmutableMap<TypeMirror, FieldSpec> getTypeAdapters(ImmutableList<Property> properties) {
    Map<TypeMirror, FieldSpec> typeAdapters = new LinkedHashMap<>();
    NameAllocator nameAllocator = new NameAllocator();
    nameAllocator.newName("CREATOR");
    for (Property property : properties) {
        if (property.typeAdapter != null && !typeAdapters.containsKey(property.typeAdapter)) {
            ClassName typeName = (ClassName) TypeName.get(property.typeAdapter);
            String name = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, typeName.simpleName());
            name = nameAllocator.newName(name, typeName);

            typeAdapters.put(property.typeAdapter, FieldSpec.builder(
                    typeName, NameAllocator.toJavaIdentifier(name), PRIVATE, STATIC, FINAL)
                    .initializer("new $T()", typeName).build());
        }
    }
    return ImmutableMap.copyOf(typeAdapters);
}
项目:document-management-store-app    文件:StoredDocumentServiceTests.java   
@Test
public void testSaveItemsWithCommandAndToggleConfiguration() throws Exception {

    when(toggleConfiguration.isMetadatasearchendpoint()).thenReturn(true);
    when(toggleConfiguration.isTtl()).thenReturn(true);

    UploadDocumentsCommand uploadDocumentsCommand = new UploadDocumentsCommand();
    uploadDocumentsCommand.setFiles(singletonList(TestUtil.TEST_FILE));
    uploadDocumentsCommand.setRoles(ImmutableList.of("a", "b"));
    uploadDocumentsCommand.setClassification(Classifications.PRIVATE);
    uploadDocumentsCommand.setMetadata(ImmutableMap.of("prop1", "value1"));
    uploadDocumentsCommand.setTtl(new Date());

    List<StoredDocument> documents = storedDocumentService.saveItems(uploadDocumentsCommand);

    final StoredDocument storedDocument = documents.get(0);
    final DocumentContentVersion latestVersion = storedDocument.getDocumentContentVersions().get(0);

    Assert.assertEquals(1, documents.size());
    Assert.assertEquals(storedDocument.getRoles(), new HashSet(ImmutableList.of("a", "b")));
    Assert.assertEquals(storedDocument.getClassification(), Classifications.PRIVATE);
    Assert.assertEquals(storedDocument.getMetadata(), ImmutableMap.of("prop1", "value1"));
    Assert.assertNotNull(storedDocument.getTtl());
    Assert.assertEquals(TestUtil.TEST_FILE.getContentType(), latestVersion.getMimeType());
    Assert.assertEquals(TestUtil.TEST_FILE.getOriginalFilename(), latestVersion.getOriginalDocumentName());
}
项目:r8    文件:R8GMSCoreTreeShakeJarVerificationTest.java   
public AndroidApp buildAndTreeShakeFromDeployJar(
    CompilationMode mode, String base, boolean hasReference, int maxSize,
    Consumer<InternalOptions> optionsConsumer)
    throws ExecutionException, IOException, ProguardRuleParserException, CompilationException {
  AndroidApp app = runAndCheckVerification(
      CompilerUnderTest.R8,
      mode,
      hasReference ? base + REFERENCE_APK : null,
      null,
      base + PG_CONF,
      optionsConsumer,
      // Don't pass any inputs. The input will be read from the -injars in the Proguard
      // configuration file.
      ImmutableList.of());
  int bytes = applicationSize(app);
  assertTrue("Expected max size of " + maxSize + ", got " + bytes, bytes < maxSize);
  return app;
}
项目:morf    文件:TestDatabaseUpgradeIntegration.java   
/**
 * Test:
 *   1. Rename BasicTable to BasicTableRenamed
 *   2. Add BasicTable
 *
 * This tests that everything from BasicTable has been correctly renamed.
 */
@Test
public void testRenameFollowedByAdditionUsingOldName() {
  Table newTable = table("BasicTableRenamed").columns(
    column("stringCol", DataType.STRING, 20).primaryKey(),
    column("nullableStringCol", DataType.STRING, 10).nullable(),
    column("decimalTenZeroCol", DataType.DECIMAL, 10),
    column("decimalNineFiveCol", DataType.DECIMAL, 9, 5),
    column("bigIntegerCol", DataType.BIG_INTEGER, 19),
    column("nullableBigIntegerCol", DataType.BIG_INTEGER, 19).nullable()
  );

  List<Table> tables = Lists.newArrayList(schema.tables());
  tables.add(newTable);

  verifyUpgrade(schema(tables), ImmutableList.<Class<? extends UpgradeStep>>of(RenameTable.class, AddBasicTable.class));
}
项目:morf    文件:AbstractSqlDialectTest.java   
/**
 * Test that an Insert statement is generated with a null value
 */
@Test
public void testInsertWithNullDefaults() {
  InsertStatement stmt = new InsertStatement().into(new TableReference(TEST_TABLE))
      .from(new TableReference(OTHER_TABLE)).withDefaults(
        new NullFieldLiteral().as(DATE_FIELD),
        new NullFieldLiteral().as(BOOLEAN_FIELD),
        new NullFieldLiteral().as(CHAR_FIELD),
        new NullFieldLiteral().as(BLOB_FIELD)
          );

  String expectedSql = "INSERT INTO " + tableName(TEST_TABLE) + " (id, version, stringField, intField, floatField, dateField, booleanField, charField, blobField, bigIntegerField, clobField) SELECT id, version, stringField, intField, floatField, null AS dateField, null AS booleanField, null AS charField, null AS blobField, 12345 AS bigIntegerField, null AS clobField FROM " + tableName(OTHER_TABLE);

  List<String> sql = testDialect.convertStatementToSQL(stmt, metadata, SqlDialect.IdTable.withDeterministicName("idvalues"));
  assertEquals("Insert with null defaults", ImmutableList.of(expectedSql), sql);
}
项目:de.flapdoodle.solid    文件:TreeTest.java   
@Test
public void parseSampleTree() {
    PropertyTree src=FixedPropertyTree.builder()
            .put("one", FixedPropertyTree.builder()
                    .put("name", "A")
                    .put("children", "A-a")
                    .put("children", "A-b")
                    .put("children", "A-c")
                    .build())
            .put("two", FixedPropertyTree.builder()
                    .put("name", "B")
                    .build())
            .put("3", FixedPropertyTree.builder()
                    .put("name", "A-a")
                    .put("children", "A-a-0")
                    .build())
            .build();

    Tree tree = Tree.treeOf(src);
    assertEquals("Tree{relation={A=[A-a, A-b, A-c], B=[], A-a=[A-a-0]}}",tree.toString());

    ImmutableList<Tree.Node> mappedTree = tree.mapAsTree(ImmutableList.of("A-a-0","C","A-a","B","A"));
    assertEquals("[Node{name=C, children=[]}, Node{name=B, children=[]}, Node{name=A, children=[Node{name=A-a, children=[Node{name=A-a-0, children=[]}]}]}]", mappedTree.toString());
}
项目:guava-mock    文件:MoreExecutorsTest.java   
public void testListeningDecorator() throws Exception {
  ListeningExecutorService service =
      listeningDecorator(newDirectExecutorService());
  assertSame(service, listeningDecorator(service));
  List<Callable<String>> callables =
      ImmutableList.of(Callables.returning("x"));
  List<Future<String>> results;

  results = service.invokeAll(callables);
  assertThat(getOnlyElement(results)).isInstanceOf(TrustedListenableFutureTask.class);

  results = service.invokeAll(callables, 1, SECONDS);
  assertThat(getOnlyElement(results)).isInstanceOf(TrustedListenableFutureTask.class);

  /*
   * TODO(cpovirk): move ForwardingTestCase somewhere common, and use it to
   * test the forwarded methods
   */
}
项目:auto-value-step-builder    文件:SimpleTest.java   
@Test
public void step() throws Exception {

    Person person = Person.step()
            .id(PERSON_ID)
            .names(ImmutableList.of(PERSON_NAME, PERSON_SURNAME))
            .phones(ImmutableList.of(PERSON_PHONE))
            .homeAddress(
                    Address.step()
                            .title(ADDRESS_TITLE)
                            .street(ADDRESS_STREET)
                            .city(ADDRESS_CITY)
                            .postcode(ADDRESS_POSTCODE)
                            .countryCode(ADDRESS_COUNTRY_CODE)
                            .optional()
                            .streetParts(ADDRESS_STREET_PARTS)
                            .build()
            )
            .optional()
            .workAddress(PERSON_WORK_ADDRESS)
            .birthday(PERSON_BIRTHDAY)
            .build();

    assertPerson(person);
}
项目:Facegram    文件:NewStoriesControllerTest.java   
@Test
public void shouldGetNewStoriesOfLocation() throws Exception{
    Story story = generateStory();
    Geolocation geolocation = new Geolocation();
    geolocation.setLatitude(0);
    geolocation.setLongitude(0);
    MultiValueMap<String,String> params = new LinkedMultiValueMap<>();
    params.add("latitude",String.valueOf(geolocation.getLatitude()));
    params.add("longitude",String.valueOf(geolocation.getLongitude()));

    when(newStoriesService.getStoriesOfLocation(any(Geolocation.class))).thenReturn(ImmutableList.of(story));

    mockMvc.perform(get("/newStories/location").params(params))
            .andExpect(jsonPath("$[0].id").value(story.getId()))
            .andExpect(status().isOk());
}
项目:andbg    文件:DexBuilder.java   
@Nonnull public BuilderMethod internMethod(@Nonnull String definingClass,
                                           @Nonnull String name,
                                           @Nullable List<? extends MethodParameter> parameters,
                                           @Nonnull String returnType,
                                           int accessFlags,
                                           @Nonnull Set<? extends Annotation> annotations,
                                           @Nullable MethodImplementation methodImplementation) {
    if (parameters == null) {
        parameters = ImmutableList.of();
    }
    return new BuilderMethod(context.methodPool.internMethod(definingClass, name, parameters, returnType),
            internMethodParameters(parameters),
            accessFlags,
            context.annotationSetPool.internAnnotationSet(annotations),
            methodImplementation);
}
项目:LifecycleAware    文件:UtilsTest.java   
@Test
public void testDistinctByKey() throws Exception {
    List<TestPair> testPairList =
            ImmutableList.of(
                    new TestPair("a", "1"),
                    new TestPair("a", "2"),
                    new TestPair("a", "3"),
                    new TestPair("b", "1")
            );

    List<TestPair> distinctByFirst = testPairList.stream()
            .filter(Utils.distinctByKey(testPair -> testPair.first))
            .collect(Collectors.toList());

    Assert.assertNotEquals(testPairList, distinctByFirst);
    Assert.assertEquals(2, distinctByFirst.size());
}
项目:url-classifier    文件:AuthorityClassifierBuilderTest.java   
private static void runTests(
    AuthorityClassifier p,
    ImmutableMap<Classification, ImmutableList<String>> inputs) {

  Diagnostic.CollectingReceiver<UrlValue> cr = Diagnostic.CollectingReceiver.from(
      TestUtil.STDERR_RECEIVER);

  try {
    for (Map.Entry<Classification, ImmutableList<String>> e
        : inputs.entrySet()) {
      Classification want = e.getKey();
      ImmutableList<String> inputList = e.getValue();
      for (int i = 0; i < inputList.size(); ++i) {
        cr.clear();
        String url = inputList.get(i);
        UrlValue inp = UrlValue.from(TEST_URL_CONTEXT, url);
        Classification got = p.apply(inp, cr);
        assertEquals(i + ": " + url, want, got);
      }
      cr.clear();
    }
  } finally {
    cr.flush();
  }
}
项目:json2java4idea    文件:MoshiClassBuilder.java   
@Nonnull
@Override
protected List<MethodSpec> buildMethods() {
    final MethodSpec.Builder constructorBuilder = MethodSpec.constructorBuilder()
            .addModifiers(Modifier.PUBLIC);

    final ImmutableList.Builder<MethodSpec> builder = ImmutableList.builder();
    getProperties().entrySet().forEach(property -> {
        final String name = property.getKey();
        final TypeName type = property.getValue();
        final String fieldName = fieldNamePolicy.convert(name, type);
        final String methodName = methodNamePolicy.convert(name, type);
        builder.add(MethodSpec.methodBuilder(methodName)
                .addModifiers(Modifier.PUBLIC)
                .returns(type)
                .addStatement("return $L", fieldName)
                .build());

        final String propertyName = parameterNamePolicy.convert(name, type);
        constructorBuilder.addParameter(ParameterSpec.builder(type, propertyName)
                .build())
                .addStatement("this.$L = $L", fieldName, propertyName);
    });
    builder.add(constructorBuilder.build());
    return builder.build();
}
项目:guava-mock    文件:AbstractNonStreamingHashFunctionTest.java   
/**
 * Constructs two trivial HashFunctions (output := input), one streaming and one non-streaming,
 * and checks that their results are identical, no matter which newHasher version we used.
 */
public void testExhaustive() {
  List<Hasher> hashers = ImmutableList.of(
      new StreamingVersion().newHasher(),
      new StreamingVersion().newHasher(52),
      new NonStreamingVersion().newHasher(),
      new NonStreamingVersion().newHasher(123));
  Random random = new Random(0);
  for (int i = 0; i < 200; i++) {
    RandomHasherAction.pickAtRandom(random).performAction(random, hashers);
  }
  HashCode[] codes = new HashCode[hashers.size()];
  for (int i = 0; i < hashers.size(); i++) {
    codes[i] = hashers.get(i).hash();
  }
  for (int i = 1; i < codes.length; i++) {
    assertEquals(codes[i - 1], codes[i]);
  }
}
项目:GitHub    文件:TypeTest.java   
@Test
public void parseWildcards() {
  check(parser.parse("List<?>")).is(
      factory.parameterized(
          factory.reference("List"),
          ImmutableList.of(
              factory.extendsWildcard(Type.OBJECT))));

  check(parser.parse("Map<? extends List<? extends A>, ? super B>")).is(
      factory.parameterized(
          factory.reference("Map"),
          ImmutableList.of(
              factory.extendsWildcard(
                  factory.parameterized(
                      factory.reference("List"),
                      ImmutableList.of(
                          factory.extendsWildcard(
                              parameters.variable("A"))))),
              factory.superWildcard(
                  parameters.variable("B")))));
}
项目:atlas    文件:AndroidLibraryImpl.java   
AndroidLibraryImpl(
        @NonNull AndroidDependency clonedLibrary,
        boolean isProvided,
        boolean isSkipped,
        @NonNull List<AndroidLibrary> androidLibraries,
        @NonNull Collection<JavaLibrary> javaLibraries,
        @NonNull Collection<File> localJavaLibraries) {
    super(
            clonedLibrary.getProjectPath(),
            null,
            clonedLibrary.getCoordinates(),
            isSkipped,
            isProvided);
    this.androidLibraries = ImmutableList.copyOf(androidLibraries);
    this.javaLibraries = ImmutableList.copyOf(javaLibraries);
    //FIXME , add localJar later at prepareAllDependencies
    this.localJars = new ArrayList<>(localJavaLibraries);
    variant = clonedLibrary.getVariant();
    bundle = clonedLibrary.getArtifactFile();
    folder = clonedLibrary.getExtractedFolder();
    manifest = clonedLibrary.getManifest();
    jarFile = clonedLibrary.getJarFile();
    resFolder = clonedLibrary.getResFolder();
    assetsFolder = clonedLibrary.getAssetsFolder();
    jniFolder = clonedLibrary.getJniFolder();
    aidlFolder = clonedLibrary.getAidlFolder();
    renderscriptFolder = clonedLibrary.getRenderscriptFolder();
    proguardRules = clonedLibrary.getProguardRules();
    lintJar = clonedLibrary.getLintJar();
    annotations = clonedLibrary.getExternalAnnotations();
    publicResources = clonedLibrary.getPublicResources();
    symbolFile = clonedLibrary.getSymbolFile();
    hashcode = computeHashCode();
}
项目:verify-hub    文件:AssertionDecrypter.java   
private Assertion decrypt(EncryptedAssertion encryptedAssertion) {
    Decrypter decrypter = new DecrypterFactory().createDecrypter(ImmutableList.of(new BasicCredential(publicKey, privateKey)));
    decrypter.setRootInNewDocument(true);
    try {
        return decrypter.decrypt(encryptedAssertion);
    } catch (DecryptionException e) {
        throw new RuntimeException(e);
    }
}
项目:guava-mock    文件:TypeTokenTest.java   
public <T extends List<String>> void testMethod_parameterTypes()
    throws NoSuchMethodException {
  Method setMethod = List.class.getMethod("set", int.class, Object.class);
  Invokable<T, ?> invokable = new TypeToken<T>(getClass()) {}.method(setMethod);
  ImmutableList<Parameter> params = invokable.getParameters();
  assertEquals(2, params.size());
  assertEquals(TypeToken.of(int.class), params.get(0).getType());
  assertEquals(TypeToken.of(String.class), params.get(1).getType());
}
项目:dotwebstack-framework    文件:ParameterDefinitionResourceProviderTest.java   
@Test
public void loadResources_GetResources_WithValidData() {
  // Arrange
  when(graphQueryMock.evaluate()).thenReturn(new IteratingGraphQueryResult(ImmutableMap.of(),
      ImmutableList.of(
          VALUE_FACTORY.createStatement(DBEERPEDIA.NAME_PARAMETER_ID, RDF.TYPE, ELMO.TERM_FILTER),
          VALUE_FACTORY.createStatement(DBEERPEDIA.NAME_PARAMETER_ID, ELMO.NAME_PROP,
              DBEERPEDIA.NAME_PARAMETER_VALUE),
          VALUE_FACTORY.createStatement(DBEERPEDIA.PLACE_PARAMETER_ID, RDF.TYPE,
              ELMO.TERM_FILTER),
          VALUE_FACTORY.createStatement(DBEERPEDIA.PLACE_PARAMETER_ID, ELMO.NAME_PROP,
              DBEERPEDIA.PLACE_PARAMETER_VALUE))));

  when(parameterDefinitionFactoryMock.supports(ELMO.TERM_FILTER)).thenReturn(true);

  ParameterDefinition nameParameterDefinition = mock(ParameterDefinition.class);
  when(parameterDefinitionFactoryMock.create(Mockito.any(),
      Mockito.eq(DBEERPEDIA.NAME_PARAMETER_ID))).thenReturn(nameParameterDefinition);

  ParameterDefinition placeParameterDefinition = mock(ParameterDefinition.class);
  when(parameterDefinitionFactoryMock.create(Mockito.any(),
      Mockito.eq(DBEERPEDIA.PLACE_PARAMETER_ID))).thenReturn(placeParameterDefinition);

  // Act
  provider.loadResources();

  // Assert
  assertThat(provider.getAll().entrySet(), hasSize(2));
  assertThat(provider.get(DBEERPEDIA.NAME_PARAMETER_ID), sameInstance(nameParameterDefinition));
  assertThat(provider.get(DBEERPEDIA.PLACE_PARAMETER_ID), sameInstance(placeParameterDefinition));
}
项目:rkt-launcher    文件:RktCommandResourceTest.java   
@Test
public void shouldRunTrustWithoutPayloadMultiple() throws Exception {
  sinceVersion(Api.Version.V0);
  final Trust trust = Trust.builder()
      .args(ImmutableList.of("http://example.com/pubkey1", "http://example.com/pubkey2"))
      .build();
  final TrustOutput trustOutput = TrustOutput.builder()
      .addTrustedPubkey(TrustedPubkey.builder()
                            .prefix("")
                            .key("http://example.com/pubkey1")
                            .location("")
                            .build())
      .addTrustedPubkey(TrustedPubkey.builder()
                            .prefix("")
                            .key("http://example.com/pubkey2")
                            .location("")
                            .build())
      .build();
  when(rktLauncher.run(trust)).thenReturn(trustOutput);
  final Response<ByteString> response = awaitResponse(
      serviceHelper
          .request(DEFAULT_HTTP_METHOD, path("/trust?pubkey=http://example.com/pubkey1"
                                             + "&pubkey=http://example.com/pubkey2")));
  assertThat(response, hasStatus(belongsToFamily(StatusType.Family.SUCCESSFUL)));
  assertTrue(response.payload().isPresent());
  assertEquals(trustOutput,
               Json.deserialize(response.payload().get().toByteArray(), TrustOutput.class));
}
项目:athena    文件:TransactionalContinuousResourceSubStore.java   
private boolean appendValue(ContinuousResource original, ResourceAllocation value) {
    ContinuousResourceAllocation oldValue = consumers.putIfAbsent(original.id(),
            new ContinuousResourceAllocation(original, ImmutableList.of(value)));
    if (oldValue == null) {
        return true;
    }

    ContinuousResourceAllocation newValue = oldValue.allocate(value);
    return consumers.replace(original.id(), oldValue, newValue);
}
项目:dremio-oss    文件:TestSchedule.java   
private static Object[] newTestCase(String name, Schedule schedule, String[] events) {
  ImmutableList.Builder<Instant> builder = ImmutableList.builder();
  for(String event: events) {
    builder.add(Instant.parse(event));
  }

  return new Object[] { name, schedule, builder.build() };
}
项目:guava-mock    文件:HashingTest.java   
public void testAllHashFunctionsHaveKnownHashes() throws Exception {
  // The following legacy hashing function methods have been covered by unit testing already.
  List<String> legacyHashingMethodNames = ImmutableList.of("murmur2_64", "fprint96");
  for (Method method : Hashing.class.getDeclaredMethods()) {
    if (method.getReturnType().equals(HashFunction.class) // must return HashFunction
        && Modifier.isPublic(method.getModifiers()) // only the public methods
        && method.getParameterTypes().length == 0 // only the seed-less grapes^W hash functions
        && !legacyHashingMethodNames.contains(method.getName())) {
      HashFunction hashFunction = (HashFunction) method.invoke(Hashing.class);
      assertTrue("There should be at least 3 entries in KNOWN_HASHES for " + hashFunction,
          KNOWN_HASHES.row(hashFunction).size() >= 3);
    }
  }
}
项目:GitHub    文件:BindViewTest.java   
@Test public void bindingGeneratedView() {
  JavaFileObject source = JavaFileObjects.forSourceString("test.Test", ""
      + "package test;\n"
      + "import butterknife.BindView;\n"
      + "@PerformGeneration\n"
      + "public class Test {\n"
      + "    @BindView(1) GeneratedView thing;\n"
      + "}"
  );

  // w/o the GeneratingProcessor it can't find `class GeneratedView`
  assertAbout(javaSources()).that(ImmutableList.of(source, TestGeneratingProcessor.ANNOTATION))
      .processedWith(new ButterKnifeProcessor())
      .failsToCompile()
      .withErrorContaining("cannot find symbol");

  // now the GeneratingProcessor should let it compile
  assertAbout(javaSources()).that(ImmutableList.of(source, TestGeneratingProcessor.ANNOTATION))
      .processedWith(new ButterKnifeProcessor(), new TestGeneratingProcessor("GeneratedView",
          "package test;",
          "import android.content.Context;",
          "import android.view.View;",
          "public class GeneratedView extends View {",
          "  public GeneratedView(Context context) {",
          "    super(context);",
          "  }",
          "}"
      ))
      .compilesWithoutError()
      .withNoteContaining("@BindView field with unresolved type (GeneratedView)").and()
      .withNoteContaining("must elsewhere be generated as a View or interface").and()
      .and()
      .generatesFileNamed(StandardLocation.CLASS_OUTPUT, "test", "Test_ViewBinding.class");
}
项目:CustomWorldGen    文件:ItemLayerModel.java   
public IBakedModel bake(IModelState state, final VertexFormat format, Function<ResourceLocation, TextureAtlasSprite> bakedTextureGetter)
{
    ImmutableList.Builder<BakedQuad> builder = ImmutableList.builder();
    Optional<TRSRTransformation> transform = state.apply(Optional.<IModelPart>absent());
    for(int i = 0; i < textures.size(); i++)
    {
        TextureAtlasSprite sprite = bakedTextureGetter.apply(textures.get(i));
        builder.addAll(getQuadsForSprite(i, sprite, format, transform));
    }
    TextureAtlasSprite particle = bakedTextureGetter.apply(textures.isEmpty() ? new ResourceLocation("missingno") : textures.get(0));
    ImmutableMap<TransformType, TRSRTransformation> map = IPerspectiveAwareModel.MapWrapper.getTransforms(state);
    return new BakedItemModel(builder.build(), particle, map, overrides, null);
}
项目:tikv-client-lib-java    文件:CatalogTransaction.java   
public List<TiDBInfo> getDatabases() {
  List<Pair<ByteString, ByteString>> fields = hashGetFields(KEY_DB);
  ImmutableList.Builder<TiDBInfo> builder = ImmutableList.builder();
  for (Pair<ByteString, ByteString> pair : fields) {
    builder.add(parseFromJson(pair.second, TiDBInfo.class));
  }
  return builder.build();
}
项目:dropwizard-influxdb-reporter    文件:SenderTest.java   
@Test
public void testSend_SendsMeasures() throws Exception {
  final InfluxDbWriter writer = mock(InfluxDbWriter.class);
  final Sender sender = new Sender(writer);
  sender.send(ImmutableList.of(
    InfluxDbMeasurement.create("hello", ImmutableMap.of("x", "y"), ImmutableMap.of("a", "b"), 90210L),
    InfluxDbMeasurement.create("hello", ImmutableMap.of("x", "y"), ImmutableMap.of("e", "d"), 90210L)
  ));

  verify(writer, only()).writeBytes("hello,x=y a=b 90210000000\nhello,x=y e=d 90210000000\n".getBytes());
  assertEquals("should clear measure queue", 0, sender.queuedMeasures());
}
项目:auto-value-step-builder    文件:MoshiTest.java   
@Test
public void marshalUnmarshal() throws Exception {
    Person person = Person.step()
            .id(PERSON_ID)
            .names(ImmutableList.of(PERSON_NAME, PERSON_SURNAME))
            .phones(ImmutableList.of(PERSON_PHONE))
            .homeAddress(
                    Address.step()
                            .title(ADDRESS_TITLE)
                            .street(ADDRESS_STREET)
                            .city(ADDRESS_CITY)
                            .postcode(ADDRESS_POSTCODE)
                            .countryCode(ADDRESS_COUNTRY_CODE)
                            .optional()
                            .streetParts(ADDRESS_STREET_PARTS)
                            .build()
            )
            .optional()
            .workAddress(PERSON_WORK_ADDRESS)
            .birthday(PERSON_BIRTHDAY)
            .build();

    assertPerson(person);

    Moshi moshi = new Moshi.Builder()
            .add(MoshiFactory.create())
            .add(ImmutableListJsonAdapter.FACTORY)
            .add(Date.class, new Rfc3339DateJsonAdapter())
            .build();

    String moshiString = moshi.adapter(Person.class).toJson(person);

    assertEquals(moshiString, MOSHI_STRING);

    Person personFromJson = moshi.adapter(Person.class).fromJson(moshiString);

    assertEquals(person, personFromJson);

    assertPerson(personFromJson);
}
项目:tikv-client-lib-java    文件:KeyRangeUtils.java   
public static List<DataType> getIndexColumnTypes(TiTableInfo table, TiIndexInfo index) {
  ImmutableList.Builder<DataType> types = ImmutableList.builder();
  for (TiIndexColumn indexColumn : index.getIndexColumns()) {
    TiColumnInfo tableColumn = table.getColumns().get(indexColumn.getOffset());
    types.add(tableColumn.getType());
  }
  return types.build();
}
项目:tac-kbp-eal    文件:AnswerAlignment.java   
public List<AlignedAnswers<Answerable, LeftAnswer, RightAnswer>> alignmentsForAnswerables() {
  return ImmutableList.copyOf(Iterables.transform(answerables,
      new Function<Answerable, AlignedAnswers<Answerable, LeftAnswer, RightAnswer>>() {
        @Override
        public AlignedAnswers<Answerable, LeftAnswer, RightAnswer> apply(
            final Answerable answerable) {
          return AlignedAnswers.create(answerable,
              ecToLeft.get(answerable), ecToRight.get(answerable));
        }
      }));
}
项目:rkt-launcher    文件:RmOptionsTest.java   
@Test
public void shouldBuildCorrectList() {
  final RmOptions rmOptions = RmOptions.builder()
      .uuidFile("file")
      .build();
  final ImmutableList<String> expected = ImmutableList.of(
      "--uuid-file=file");
  assertEquals(expected, rmOptions.asList());
}
项目:servicebuilder    文件:ServiceConfigInitializer.java   
public static ServiceConfig finalize(ServiceConfig serviceConfig) {
    List<Addon> unFinalizedAddons = sortAddonList(serviceConfig.addons);
    ServiceConfig withFinalizedAddons = serviceConfig.withAddons(ImmutableList.of());
    for (Addon addon : unFinalizedAddons) {
        withFinalizedAddons = withFinalizedAddons.addon(addon.initialize(withFinalizedAddons));
    }
    return withFinalizedAddons;
}
项目:r8    文件:JumpSubroutineTests.java   
@Test
public void testJsrWithStraightlineCodeMultiple() throws Exception {
  JasminBuilder builder = new JasminBuilder();
  JasminBuilder.ClassBuilder clazz = builder.addClass("Test");

  clazz.addStaticMethod("foo", ImmutableList.of(), "I",
      ".limit stack 3",
      ".limit locals 3",
      "  ldc 0",
      "  ldc 1",
      "  jsr LabelSub1",
      "  ldc 2",
      "  jsr LabelSub2",
      "  ldc 3",
      "  jsr LabelSub3",
      "  ireturn",
      "LabelSub1:",
      "  astore 1",
      "  iadd",
      "  ret 1",
      "LabelSub2:",
      "  astore 1",
      "  iadd",
      "  ret 1",
      "LabelSub3:",
      "  astore 1",
      "  iadd",
      "  ret 1");

  clazz.addMainMethod(
      ".limit stack 2",
      ".limit locals 1",
      "  getstatic java/lang/System/out Ljava/io/PrintStream;",
      "  invokestatic Test/foo()I",
      "  invokevirtual java/io/PrintStream/print(I)V",
      "  return");

  runTest(builder, clazz.name, Integer.toString(3 * 4 / 2));
}
项目:tools    文件:DownloadFactory.java   
private ImmutableList<String> readSiaPathsFromInfo(ZipInputStream zis) {
    ImmutableList<String> ret;
    JSONArray fileInfo = new JSONArray(convertStreamToString(zis));
    final ImmutableList.Builder<String> filenamesBuilder = ImmutableList.builder();
    for (Object o : fileInfo) {
        JSONObject o2 = (JSONObject) o;
        final String siapath = o2.getString("siapath");
        filenamesBuilder.add(siapath);
    }
    ret = filenamesBuilder.build();
    return ret;
}