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

The following are top voted examples for showing how to use com.google.common.collect.ImmutableList. 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: presto-ethereum   File: EthereumRecordSetProvider.java   View source code 7 votes vote down vote up
@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);
}
 
Example 2
Project: QDrill   File: ShowSchemasHandler.java   View source code 6 votes vote down vote up
/** 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);
}
 
Example 3
Project: buckaroo   File: RecipeSources.java   View source code 6 votes vote down vote up
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)));
}
 
Example 4
Project: circus-train   File: TestUtils.java   View source code 6 votes vote down vote up
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);
}
 
Example 5
Project: morf   File: TestHumanReadableStatements.java   View source code 6 votes vote down vote up
/**
 * 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);
}
 
Example 6
Project: dremio-oss   File: FlattenTemplate.java   View source code 6 votes vote down vote up
@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);
}
 
Example 7
Project: android-auto-mapper   File: AutoMappperProcessor.java   View source code 6 votes vote down vote up
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);
}
 
Example 8
Project: document-management-store-app   File: StoredDocumentServiceTests.java   View source code 6 votes vote down vote up
@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());
}
 
Example 9
Project: r8   File: R8GMSCoreTreeShakeJarVerificationTest.java   View source code 6 votes vote down vote up
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;
}
 
Example 10
Project: morf   File: TestDatabaseUpgradeIntegration.java   View source code 6 votes vote down vote up
/**
 * 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));
}
 
Example 11
Project: morf   File: AbstractSqlDialectTest.java   View source code 6 votes vote down vote up
/**
 * 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);
}
 
Example 12
Project: de.flapdoodle.solid   File: TreeTest.java   View source code 6 votes vote down vote up
@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());
}
 
Example 13
Project: guava-mock   File: MoreExecutorsTest.java   View source code 6 votes vote down vote up
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
   */
}
 
Example 14
Project: auto-value-step-builder   File: SimpleTest.java   View source code 6 votes vote down vote up
@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);
}
 
Example 15
Project: Facegram   File: NewStoriesControllerTest.java   View source code 6 votes vote down vote up
@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());
}
 
Example 16
Project: andbg   File: DexBuilder.java   View source code 6 votes vote down vote up
@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);
}
 
Example 17
Project: LifecycleAware   File: UtilsTest.java   View source code 6 votes vote down vote up
@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());
}
 
Example 18
Project: url-classifier   File: AuthorityClassifierBuilderTest.java   View source code 6 votes vote down vote up
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();
  }
}
 
Example 19
Project: json2java4idea   File: MoshiClassBuilder.java   View source code 6 votes vote down vote up
@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();
}
 
Example 20
Project: guava-mock   File: AbstractNonStreamingHashFunctionTest.java   View source code 6 votes vote down vote up
/**
 * 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]);
  }
}
 
Example 21
Project: GitHub   File: TypeTest.java   View source code 6 votes vote down vote up
@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")))));
}
 
Example 22
Project: atlas   File: AndroidLibraryImpl.java   View source code 5 votes vote down vote up
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();
}
 
Example 23
Project: verify-hub   File: AssertionDecrypter.java   View source code 5 votes vote down vote up
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);
    }
}
 
Example 24
Project: guava-mock   File: TypeTokenTest.java   View source code 5 votes vote down vote up
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());
}
 
Example 25
Project: dotwebstack-framework   File: ParameterDefinitionResourceProviderTest.java   View source code 5 votes vote down vote up
@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));
}
 
Example 26
Project: rkt-launcher   File: RktCommandResourceTest.java   View source code 5 votes vote down vote up
@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));
}
 
Example 27
Project: athena   File: TransactionalContinuousResourceSubStore.java   View source code 5 votes vote down vote up
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);
}
 
Example 28
Project: dremio-oss   File: TestSchedule.java   View source code 5 votes vote down vote up
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() };
}
 
Example 29
Project: guava-mock   File: HashingTest.java   View source code 5 votes vote down vote up
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);
    }
  }
}
 
Example 30
Project: GitHub   File: BindViewTest.java   View source code 5 votes vote down vote up
@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");
}
 
Example 31
Project: CustomWorldGen   File: ItemLayerModel.java   View source code 5 votes vote down vote up
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);
}
 
Example 32
Project: tikv-client-lib-java   File: CatalogTransaction.java   View source code 5 votes vote down vote up
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();
}
 
Example 33
Project: dropwizard-influxdb-reporter   File: SenderTest.java   View source code 5 votes vote down vote up
@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());
}
 
Example 34
Project: auto-value-step-builder   File: MoshiTest.java   View source code 5 votes vote down vote up
@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);
}
 
Example 35
Project: tikv-client-lib-java   File: KeyRangeUtils.java   View source code 5 votes vote down vote up
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();
}
 
Example 36
Project: tac-kbp-eal   File: AnswerAlignment.java   View source code 5 votes vote down vote up
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));
        }
      }));
}
 
Example 37
Project: rkt-launcher   File: RmOptionsTest.java   View source code 5 votes vote down vote up
@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());
}
 
Example 38
Project: servicebuilder   File: ServiceConfigInitializer.java   View source code 5 votes vote down vote up
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;
}
 
Example 39
Project: r8   File: JumpSubroutineTests.java   View source code 5 votes vote down vote up
@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));
}
 
Example 40
Project: tools   File: DownloadFactory.java   View source code 5 votes vote down vote up
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;
}