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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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;
}
 
Example 41
Project: rkt-launcher   File: SystemTest.java   Source Code and License 5 votes vote down vote up
@Test
public void shouldRunConfig() throws Exception {
  //language=JSON
  final String json = "{\n"
                      + "  \"stage0\": [\n"
                      + "    {\n"
                      + "      \"rktVersion\": \"v1\",\n"
                      + "      \"rktKind\": \"paths\",\n"
                      + "      \"data\": \"/var/lib/rkt\",\n"
                      + "      \"stage1-images\": \"/usr/lib/rkt\"\n"
                      + "    },\n"
                      + "    {\n"
                      + "      \"rktVersion\": \"v1\",\n"
                      + "      \"rktKind\": \"stage1\",\n"
                      + "      \"name\": \"coreos.com/rkt/stage1-coreos\",\n"
                      + "      \"version\": \"0.15.0+git\",\n"
                      + "      \"location\": \"/usr/libexec/rkt/stage1-coreos.aci\"\n"
                      + "    }\n"
                      + "  ]\n"
                      + "}";
  final ProcessResult processResult = new ProcessResult(0, new ProcessOutput(json.getBytes()));
  when(processExecutor.command(
      ImmutableList.of("rkt", "--insecure-options=image", "config")))
      .thenReturn(processExecutor);
  when(processExecutor.executeNoTimeout()).thenReturn(processResult);
  final Config config = Config.COMMAND;
  final ConfigOutput configOutput = rktLauncher.run(config);
  assertEquals("paths", configOutput.config().stage0().get(0).rktKind());
}
 
Example 42
Project: rkt-launcher   File: CatManifestTest.java   Source Code and License 5 votes vote down vote up
@Test
public void shouldBuildCorrectList() {
  final ImmutableList<String> expected = ImmutableList.of(
      "cat-manifest",
      "arg1");
  assertEquals(expected, catManifest.asList());
}
 
Example 43
Project: tac-kbp-eal   File: CorpusQueryExecutor2016.java   Source Code and License 5 votes vote down vote up
/**
 * Only tries lower ranked alignment strategies if no matches have been found yet, hence the array
 * of matchingResponses.
 */
private void gatherResponsesMatchingEntryPoints(final CorpusQueryEntryPoint queryEntryPoint,
    final DocumentSystemOutput2015 docSystemOutput, final List<Response> matchingResponses,
    final StringBuilder msg) {
  final EREEvent ereEventForEntryPoint =
      ereEventForEntryPoint(queryEntryPoint);
  final ImmutableSet<Symbol> entryPointEventTypes = gatherTypes(ereEventForEntryPoint);

  final Symbol mappedRole = ontologyMapper.eventRole(queryEntryPoint.role()).get();
  final ImmutableList<Response> argumentsMatchingInTypeAndEventType =
      FluentIterable.from(docSystemOutput.arguments().responses())
          .filter(compose(in(entryPointEventTypes), type()))
          .filter(compose(equalTo(mappedRole), role())).toList();
  msg.append(argumentsMatchingInTypeAndEventType.size())
      .append(" arguments matched in type and role\n");

  final ImmutableSet<QueryCAS> validCASOffsets = gatherValidCASOffsets(queryEntryPoint);
  checkState(!validCASOffsets.isEmpty());
  final ImmutableSet<OffsetRange<CharOffset>> eventPJs =
      gatherEventPJs(ereEventForEntryPoint);
  checkState(!eventPJs.isEmpty());

  msg.append("Query valid CASes are ").append(validCASOffsets).append("\n");
  // apply a series of more aggressive alignment rules until we find something that matches
  for (AlignmentConfiguration alignConfig : alignmentConfigurations) {
    if (matchingResponses.isEmpty()) {
      addMatchingResponses(validCASOffsets, eventPJs, matchingResponses, alignConfig,
          argumentsMatchingInTypeAndEventType, msg);
      if(!matchingResponses.isEmpty()) {
        break;
      }
    }
  }
}
 
Example 44
Project: athena   File: JsonCodecTest.java   Source Code and License 5 votes vote down vote up
@Test
public void encode() {
    Foo f1 = new Foo("foo");
    Foo f2 = new Foo("bar");
    FooCodec codec = new FooCodec();
    ImmutableList<Foo> entities = ImmutableList.of(f1, f2);
    ArrayNode json = codec.encode(entities, new TestContext());
    List<Foo> foos = codec.decode(json, new TestContext());
    assertEquals("incorrect encode/decode", entities, foos);
}
 
Example 45
Project: athena   File: ContinuousResourceId.java   Source Code and License 5 votes vote down vote up
@Override
public String toString() {
    // due to performance consideration, the value might need to be stored in a field
    return ImmutableList.builder()
            .addAll(components.subList(0, components.size() - 1))
            .add(name)
            .build().toString();
}
 
Example 46
Project: creacoinj   File: BasicKeyChain.java   Source Code and License 5 votes vote down vote up
@Override
public List<ECKey> getKeys(@Nullable KeyPurpose purpose, int numberOfKeys) {
    checkArgument(numberOfKeys > 0);
    lock.lock();
    try {
        if (hashToKeys.size() < numberOfKeys) {
            checkState(keyCrypter == null);

            List<ECKey> keys = new ArrayList<>();
            for (int i = 0; i < numberOfKeys - hashToKeys.size(); i++) {
                keys.add(new ECKey());
            }

            ImmutableList<ECKey> immutableKeys = ImmutableList.copyOf(keys);
            importKeysLocked(immutableKeys);
            queueOnKeysAdded(immutableKeys);
        }

        List<ECKey> keysToReturn = new ArrayList<>();
        int count = 0;
        while (hashToKeys.values().iterator().hasNext() && numberOfKeys != count) {
            keysToReturn.add(hashToKeys.values().iterator().next());
            count++;
        }
        return keysToReturn;
    } finally {
        lock.unlock();
    }
}
 
Example 47
Project: de.flapdoodle.solid   File: DefaultBlobParser.java   Source Code and License 5 votes vote down vote up
private Maybe<Blob> interalParse(Path path, String content) {
		String filename = Filenames.filenameOf(path);
		String extension = Filenames.extensionOf(filename);
		Maybe<ContentType> contentType = ContentType.ofExtension(extension);
		if (contentType.isPresent()) {
			Maybe<ParsedMetaAndContent> optMetaAndContent = findToml(parserFactory, content);
			if (!optMetaAndContent.isPresent()) {
				optMetaAndContent = findYaml(parserFactory, content);
			}
			
			if (optMetaAndContent.isPresent()) {
				ParsedMetaAndContent metaAndContent = optMetaAndContent.get();
				PropertyTree meta = metaAndContent.meta();
				
				ImmutableList<String> blobPath = Filenames.pathAsList(path.getParent());
				
				PropertyTree blobMetaData = FixedPropertyTree.builder()
					.put("path", Joiner.on('/').join(blobPath)+"/")
					.put("filename", filename)
					.build()
					.overriding(meta);
				
				return Maybe.of(Blob.builder()
//					.addAllPath(blobPath)
//					.filename(filename)
					.meta(blobMetaData)
					.contentType(contentType.get())
					.content(metaAndContent.content())
					.build());
			}
		}
		
		return Maybe.empty();
	}
 
Example 48
Project: okwallet   File: MarriedKeyChain.java   Source Code and License 5 votes vote down vote up
/** Create a new married key and return the matching output script */
@Override
public Script freshOutputScript(KeyPurpose purpose) {
    DeterministicKey followedKey = getKey(purpose);
    ImmutableList.Builder<ECKey> keys = ImmutableList.<ECKey>builder().add(followedKey);
    for (DeterministicKeyChain keyChain : followingKeyChains) {
        DeterministicKey followingKey = keyChain.getKey(purpose);
        checkState(followedKey.getChildNumber().equals(followingKey.getChildNumber()), "Following keychains should be in sync");
        keys.add(followingKey);
    }
    List<ECKey> marriedKeys = keys.build();
    Script redeemScript = ScriptBuilder.createRedeemScript(sigsRequiredToSpend, marriedKeys);
    return ScriptBuilder.createP2SHOutputScript(redeemScript);
}
 
Example 49
Project: r8   File: TreeShakingTest.java   Source Code and License 5 votes vote down vote up
private static void shaking14EnsureRightStaticMethodsLive(DexInspector inspector) {
  ClassSubject superclass = inspector.clazz("shaking14.Superclass");
  Assert.assertFalse(superclass.method("int", "aMethod", ImmutableList.of("int")).isPresent());
  Assert.assertFalse(
      superclass.method("double", "anotherMethod", ImmutableList.of("double")).isPresent());
  ClassSubject subclass = inspector.clazz("shaking14.Subclass");
  Assert.assertTrue(subclass.method("int", "aMethod", ImmutableList.of("int")).isPresent());
  Assert.assertTrue(
      subclass.method("double", "anotherMethod", ImmutableList.of("double")).isPresent());
}
 
Example 50
Project: embulk-filter-google_translate_api   File: GoogleTranslateApiFilterPlugin.java   Source Code and License 5 votes vote down vote up
/**
 * @param task
 * @param inputSchema
 * @return
 */
private Schema buildOutputSchema(PluginTask task, Schema inputSchema) {
    ImmutableList.Builder<Column> builder = ImmutableList.builder();
    int i = 0;
    for (Column inputColumn: inputSchema.getColumns()) {
        Column outputColumn = new Column(i++, inputColumn.getName(), inputColumn.getType());
        builder.add(outputColumn);
    }
    for (String keyName : task.getKeyNames()) {
        builder.add(new Column(i++, keyName + task.getOutKeyNameSuffix(), Types.STRING));
    }
    Schema outputSchema = new Schema(builder.build());
    return outputSchema;
}
 
Example 51
Project: guava-mock   File: DoubleMathTest.java   Source Code and License 5 votes vote down vote up
@GwtIncompatible // DoubleMath.mean
public void testMean_intIterable() {
  assertEquals(-13.75, DoubleMath.mean(ImmutableList.of(11, -22, 44, -88)), 1.0e-10);
  assertEquals(11, DoubleMath.mean(ImmutableList.of(11)), 1.0e-10);
  try {
    DoubleMath.mean(ImmutableList.<Integer>of());
    fail("Expected IllegalArgumentException");
  } catch (IllegalArgumentException expected) {
  }
}
 
Example 52
Project: googles-monorepo-demo   File: FuturesTest.java   Source Code and License 5 votes vote down vote up
public void testAllAsList_singleFailure() throws Exception {
  Throwable exception = new Throwable("failed");
  ListenableFuture<String> future = immediateFailedFuture(exception);
  ListenableFuture<List<String>> compound = allAsList(ImmutableList.of(future));

  try {
    getDone(compound);
    fail();
  } catch (ExecutionException expected) {
    assertSame(exception, expected.getCause());
  }
}
 
Example 53
Project: rainbow   File: Delete.java   Source Code and License 5 votes vote down vote up
@Override
public List<Node> getChildren()
{
    ImmutableList.Builder<Node> nodes = ImmutableList.builder();
    nodes.add(table);
    where.ifPresent(nodes::add);
    return nodes.build();
}
 
Example 54
Project: drift   File: TestDriftClient.java   Source Code and License 5 votes vote down vote up
private static void verifyMethodInvocation(Collection<Supplier<InvokeRequest>> targets, String methodName, int id, String name, Map<String, String> headers)
{
    for (Supplier<InvokeRequest> target : targets) {
        InvokeRequest invokeRequest = target.get();
        assertEquals(invokeRequest.getMethod().getName(), methodName);
        assertEquals(invokeRequest.getParameters(), ImmutableList.of(id, name));
        assertEquals(invokeRequest.getHeaders(), headers);
    }
}
 
Example 55
Project: n4js   File: N4JSEclipseModel.java   Source Code and License 5 votes vote down vote up
public Optional<? extends IN4JSSourceContainer> getN4JSSourceContainer(IResource resource) {
	N4JSEclipseProject project = getN4JSProject(resource.getProject());
	ImmutableList<? extends IN4JSEclipseSourceContainer> containers = project.getSourceContainers();
	IPath fullPath = resource.getFullPath();
	for (IN4JSEclipseSourceContainer container : containers) {
		if (matchPaths(fullPath, container)) {
			return Optional.of(container);
		}
	}
	return Optional.absent();
}
 
Example 56
Project: lttng-scope   File: TestModelProvider.java   Source Code and License 5 votes vote down vote up
protected TestModelProvider() {
    super("Test",
            /* Sorting modes */
            null,
            /* Filter modes */
            null,
            /* State provider */
            new TestModelStateProvider(),
            /* Arrow providers */
            ImmutableList.of(new TestModelArrowProvider1(), new TestModelArrowProvider2()));
}
 
Example 57
Project: ProjectAres   File: TutorialPlayerFacet.java   Source Code and License 5 votes vote down vote up
private ItemStack createItem(CommandSender viewer) {
    final ItemStack item = new ItemStack(TUTORIAL_ITEM);
    final ItemMeta meta = item.getItemMeta();
    meta.addItemFlags(ItemFlag.values());
    meta.setDisplayName(renderer.renderLegacy(new Component(new TranslatableComponent("tutorial.displayName"), ChatColor.GOLD, ChatColor.BOLD), viewer));
    meta.setLore(ImmutableList.of(renderer.renderLegacy(new Component(new TranslatableComponent("tutorial.tooltip", mapInfo.getColoredName()), ChatColor.WHITE), viewer)));
    item.setItemMeta(meta);
    return item;
}
 
Example 58
Project: morf   File: TestXmlDataSetProducer.java   Source Code and License 5 votes vote down vote up
@Test
public void testFutureFormatFails() throws IOException {
  String input = SourceXML.readResource("testFutureFormatFails.xml");
  XmlDataSetProducer producer = new XmlDataSetProducer(new TestXmlInputStreamProvider(input, "TestTable"));
  producer.open();

  try {
    ImmutableList.copyOf(producer.records("TestTable"));
    fail();
  } catch(IllegalStateException ise) {
    // ok
  } finally {
    producer.close();
  }
}
 
Example 59
Project: googles-monorepo-demo   File: Parameter.java   Source Code and License 5 votes vote down vote up
Parameter(
    Invokable<?, ?> declaration, int position, TypeToken<?> type, Annotation[] annotations) {
  this.declaration = declaration;
  this.position = position;
  this.type = type;
  this.annotations = ImmutableList.copyOf(annotations);
}
 
Example 60
Project: QDrill   File: InfoSchemaPushFilterIntoRecordGenerator.java   Source Code and License 5 votes vote down vote up
protected void doMatch(RelOptRuleCall call, ScanPrel scan, ProjectPrel project, FilterPrel filter) {
  final RexNode condition = filter.getCondition();

  InfoSchemaGroupScan groupScan = (InfoSchemaGroupScan)scan.getGroupScan();
  if (groupScan.isFilterPushedDown()) {
    return;
  }

  LogicalExpression conditionExp =
      DrillOptiq.toDrill(new DrillParseContext(PrelUtil.getPlannerSettings(call.getPlanner())), project != null ? project : scan, condition);
  InfoSchemaFilterBuilder filterBuilder = new InfoSchemaFilterBuilder(conditionExp);
  InfoSchemaFilter infoSchemaFilter = filterBuilder.build();
  if (infoSchemaFilter == null) {
    return; //no filter pushdown ==> No transformation.
  }

  final InfoSchemaGroupScan newGroupsScan = new InfoSchemaGroupScan(groupScan.getTable(), infoSchemaFilter);
  newGroupsScan.setFilterPushedDown(true);

  RelNode input = ScanPrel.create(scan, filter.getTraitSet(), newGroupsScan, scan.getRowType());
  if (project != null) {
    input = project.copy(project.getTraitSet(), input, project.getProjects(), filter.getRowType());
  }

  if (filterBuilder.isAllExpressionsConverted()) {
    // Filter can be removed as all expressions in the filter are converted and pushed to scan
    call.transformTo(input);
  } else {
    call.transformTo(filter.copy(filter.getTraitSet(), ImmutableList.of(input)));
  }
}