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

项目:n4js    文件:DelegatingQuickfixProvider.java   
private static Builder<DefaultQuickfixProvider> collectRegisteredProviders() {
    final Builder<DefaultQuickfixProvider> builder = ImmutableList.<DefaultQuickfixProvider> builder();
    if (Platform.isRunning()) {
        final IConfigurationElement[] elements = getQuickfixSupplierElements();
        for (final IConfigurationElement element : elements) {
            try {
                final Object extension = element.createExecutableExtension(CLAZZ_PROPERTY_NAME);
                if (extension instanceof QuickfixProviderSupplier) {
                    builder.add(((QuickfixProviderSupplier) extension).get());
                }
            } catch (final CoreException e) {
                LOGGER.error("Error while instantiating quickfix provider supplier instance.", e);
            }
        }
    }
    return builder;
}
项目:n4js    文件:N4JSModel.java   
public ImmutableList<? extends IN4JSSourceContainer> getN4JSSourceContainers(N4JSProject project) {
    ImmutableList.Builder<IN4JSSourceContainer> result = ImmutableList.builder();
    URI location = project.getLocation();
    ProjectDescription description = getProjectDescription(location);
    if (description != null) {
        List<SourceFragment> sourceFragments = newArrayList(from(description.getSourceFragment()));
        sourceFragments.sort((f1, fDIRECT_RESOURCE_IN_PROJECT_SEGMENTCOUNT) -> f1
                .compareByFragmentType(fDIRECT_RESOURCE_IN_PROJECT_SEGMENTCOUNT));
        for (SourceFragment sourceFragment : sourceFragments) {
            List<String> paths = sourceFragment.getPaths();
            for (String path : paths) {
                // XXX poor man's canonical path conversion. Consider headless compiler with npm projects.
                final String relativeLocation = ".".equals(path) ? "" : path;
                IN4JSSourceContainer sourceContainer = this.createProjectN4JSSourceContainer(project,
                        sourceFragment.getSourceFragmentType(), relativeLocation);
                result.add(sourceContainer);
            }
        }
    }
    return result.build();
}
项目:n4js    文件:N4JSModel.java   
public ImmutableList<IN4JSSourceContainer> getSourceContainers(N4JSArchive archive) {
    ImmutableList.Builder<IN4JSSourceContainer> result = ImmutableList.builder();
    URI location = archive.getLocation();
    ProjectDescription description = getProjectDescription(location);
    if (description != null) {
        List<SourceFragment> sourceFragments = newArrayList(from(description.getSourceFragment()));
        sourceFragments.sort((f1, fDIRECT_RESOURCE_IN_PROJECT_SEGMENTCOUNT) -> f1
                .compareByFragmentType(fDIRECT_RESOURCE_IN_PROJECT_SEGMENTCOUNT));
        for (SourceFragment sourceFragment : sourceFragments) {
            List<String> paths = sourceFragment.getPaths();
            for (String path : paths) {
                result.add(createArchiveN4JSSourceContainer(archive, sourceFragment.getSourceFragmentType(), path));
            }
        }
    }
    return result.build();
}
项目:n4js    文件:NodeProcessBuilder.java   
/**
 * Prepares process builder configured to invoke Node.js for main module resolution.
 *
 * @param packageRoot
 *            package name to resolve.
 * @return configured process builder
 */
public ProcessBuilder prepareMainModuleResolveProcessBuilder(File packageRoot) {
    final Builder<String> builder = ImmutableList.<String> builder();
    NodeJsBinary nodeBinary = nodeBinaryProvider.get();
    if (isWindows()) {
        builder.add(WIN_SHELL_COMAMNDS);
        builder.add(escapeBinaryPath(nodeBinary.getBinaryAbsolutePath()));
        builder.add("-e");
        builder.add("console.log(require.resolve('" + packageRoot.getName() + "'));");
    } else {
        builder.add(NIX_SHELL_COMAMNDS);
        builder.add(escapeBinaryPath(nodeBinary.getBinaryAbsolutePath())
                + " -e \"console.log(require.resolve('" + packageRoot.getName() + "'));\"");
    }

    return create(builder.build(), nodeBinary, packageRoot, false);
}
项目:n4js    文件:NodeProcessBuilder.java   
/**
 * Prepares process builder for "npm cache clean" command.
 *
 * @param invokationPath
 *            location on which npm command should be invoked
 * @return configured, operating system aware process builder for "npm cache clean" command
 */
public ProcessBuilder getNpmCacheCleanProcessBuilder(File invokationPath) {
    Builder<String> builder = ImmutableList.<String> builder();
    NpmBinary npmBinary = npmBinaryProvider.get();

    if (isWindows()) {
        builder.add(WIN_SHELL_COMAMNDS);
        builder.add(escapeBinaryPath(npmBinary.getBinaryAbsolutePath()), "cache", "clean", "--force");
    } else {
        builder.add(NIX_SHELL_COMAMNDS);
        builder.add(
                escapeBinaryPath(npmBinary.getBinaryAbsolutePath()) + " cache clean --force");
    }

    return create(builder.build(), npmBinary, invokationPath, false);
}
项目:n4js    文件:NodeProcessBuilder.java   
/**
 * Prepares process builder for simple npm commands, e.g. "npm install" or "npm uninstall". Specific command should
 * be passed without surrounding spaces or or quotes.
 *
 * @param invokationPath
 *            location on which npm command should be invoked
 * @param packageName
 *            package passed as parameter to the command (might be space separated list of names)
 * @param save
 *            instructs npm to save command result to packages in package.json (if available)
 * @param simpleCommand
 *            command to execute
 * @return configured, operating system aware process builder for given command
 */
private ProcessBuilder simpleCall(File invokationPath, String packageName, boolean save, String simpleCommand) {
    Builder<String> builder = ImmutableList.<String> builder();
    NpmBinary npmBinary = npmBinaryProvider.get();
    String saveCommand = save ? NPM_OPTION_SAVE : "";

    if (isWindows()) {
        builder.add(WIN_SHELL_COMAMNDS);
        builder.add(escapeBinaryPath(npmBinary.getBinaryAbsolutePath()), simpleCommand, packageName, saveCommand);
    } else {
        builder.add(NIX_SHELL_COMAMNDS);
        builder.add(
                escapeBinaryPath(npmBinary.getBinaryAbsolutePath()) + " " + simpleCommand + " " + packageName + " "
                        + saveCommand);
    }

    return create(builder.build(), npmBinary, invokationPath, false);
}
项目:r8    文件:DictionaryReader.java   
public static ImmutableList<String> readAllNames(Path path) {
  if (path != null) {
    Builder<String> namesBuilder = new ImmutableList.Builder<String>();
    try (DictionaryReader reader = new DictionaryReader(path);) {
      String name = reader.readName();
      while (!name.isEmpty()) {
        namesBuilder.add(name);
        name = reader.readName();
      }
    } catch (IOException e) {
      System.err.println("Unable to create dictionary from file " + path.toString());
    }
    return namesBuilder.build();
  } else {
    return ImmutableList.of();
  }
}
项目:centraldogma    文件:MetadataService.java   
/**
 * Returns {@link ProjectRole}s of the specified secret of a {@link TokenInfo}.
 */
public CompletionStage<Map<String, ProjectRole>> findRole(String secret) {
    requireNonNull(secret, "secret");
    final String q = "$[?(@.tokens[?(@.secret == \"" + secret +
                     "\")] empty false && @.removed != true)]";
    return query(q)
            .thenApply(MetadataService::toProjectInfoList)
            .thenApply(list -> {
                final ImmutableMap.Builder<String, ProjectRole> builder = new ImmutableMap.Builder<>();
                list.forEach(p -> p.tokens().stream()
                                   .filter(t -> t.secret().equals(secret))
                                   .findFirst()
                                   .ifPresent(m -> builder.put(p.name(), m.role())));
                return builder.build();
            });
}
项目:centraldogma    文件:ChangesRequestConverter.java   
@Override
public Object convertRequest(ServiceRequestContext ctx, AggregatedHttpMessage request,
                             Class<?> expectedResultType) throws Exception {
    final JsonNode node = (JsonNode) super.convertRequest(ctx, request, JsonNode.class);
    if (node.get("changes") != null) {
        // have one entry or more than one entry
        final JsonNode changeNode = node.get("changes");

        final Builder<Change<?>> builder = ImmutableList.builder();
        for (JsonNode change : changeNode) {
            builder.add(readChange(change));
        }
        final ImmutableList<Change<?>> changes = builder.build();
        checkArgument(!changes.isEmpty(), "should have at least one change.");
        return changes;
    }

    // have only one entry
    return ImmutableList.of(readChange(node));
}
项目:Equella    文件:NotificationPortalExtension.java   
@SuppressWarnings("nls")
@Override
public List<TaskListSubsearch> getTaskFilters()
{
    Builder<TaskListSubsearch> notificationFilters = ImmutableList.builder();
    notificationFilters.add(factory.create(NotifcationPortalConstants.ID_ALL, "", false));
    notificationFilters.add(factory.create("notewentlive", Notification.REASON_WENTLIVE, true));
    notificationFilters.add(factory.create("notewentlive2", Notification.REASON_WENTLIVE2, true));
    notificationFilters.add(factory.create("notemylive", Notification.REASON_MYLIVE, true));
    notificationFilters.add(factory.create("noterejected", Notification.REASON_REJECTED, true));
    notificationFilters.add(factory.create("notebadurl", Notification.REASON_BADURL, true));
    notificationFilters.add(factory.create("noteoverdue", Notification.REASON_OVERDUE, true));
    notificationFilters.add(factory.create("noteerror", Notification.REASON_SCRIPT_ERROR, true));
    notificationFilters.add(factory.create("noteexecuted", Notification.REASON_SCRIPT_EXECUTED, true));
    return notificationFilters.build();
}
项目:quilt    文件:ValidVectorTest.java   
/**
 * Loads a list of tests based on the json-encoded test vector files.
 */
@Parameters(name = "Test Vector {index}: {0}")
public static Collection<TestVector> testVectorData() throws Exception {
  final URI baseUri =
      ValidVectorTest.class.getResource(ValidVectorTest.class.getSimpleName() + ".class").toURI();
  final File baseDirectoryFile = new File(baseUri).getParentFile();
  final File validTestVectorDir = new File(baseDirectoryFile, "/vectors/valid");

  final Builder<TestVector> vectors = ImmutableList.builder();
  final ObjectMapper mapper = new ObjectMapper();

  Arrays.stream(validTestVectorDir.listFiles()).forEach(file -> {
    try {
      if (file.getName().endsWith(".json")) {
        TestVector vector = mapper.readValue(file, TestVector.class);
        vector.setName(file.getName().substring(0, file.getName().length() - 5));
        vectors.add(vector);
      }
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  });

  return vectors.build();
}
项目:quilt    文件:AbstractCryptoConditionTest.java   
/**
 * Concurrently runs one or more instances of {@link Runnable} in a multithreaded fashion,
 * relying upon {@code numThreads} for concurrency.
 */
protected void runConcurrent(final int numThreads, final Runnable... runnableTest)
    throws InterruptedException {
  final Builder<Runnable> builder = ImmutableList.builder();

  // For each runnableTest, add it numThreads times to the bulider.
  for (final Runnable runnable : runnableTest) {
    for (int i = 0; i < numThreads; i++) {
      builder.add(runnable);
    }
  }

  logger.info(String.format("About to run %s threads...", numThreads));
  // Actually runs the Runnables above using multiple threads.
  assertConcurrent("Test did not complete before the harness timed-out. Please consider "
      + "increasing the timeout value for this test.", builder.build(), 15);
  logger.info(String.format("Ran %s threads!", numThreads));
}
项目:linkifier    文件:Tokenizers.java   
private static List<Tokenizer> flatten(List<Tokenizer> simplifiers) {
    Builder<Tokenizer> flattend = ImmutableList.builder();

    for (Tokenizer s : simplifiers) {
        if (s instanceof Recursive) {
            // Tokenizers controls the creation of recursive tokenizers
            // all recursive tokenizers are flat so we don't have
            // to flatten recursively
            final Recursive c = (Recursive) s;
            flattend.addAll(c.getTokenizers());
        } else {
            flattend.add(s);
        }
    }

    return flattend.build();
}
项目:CustomWorldGen    文件:FMLCommonHandler.java   
public void computeBranding()
{
    if (brandings == null)
    {
        Builder<String> brd = ImmutableList.builder();
        brd.add(Loader.instance().getMCVersionString());
        brd.add(Loader.instance().getMCPVersionString());
        brd.add("Powered by Forge " + ForgeVersion.getVersion());
        if (sidedDelegate!=null)
        {
            brd.addAll(sidedDelegate.getAdditionalBrandingInformation());
        }
        if (Loader.instance().getFMLBrandingProperties().containsKey("fmlbranding"))
        {
            brd.add(Loader.instance().getFMLBrandingProperties().get("fmlbranding"));
        }
        int tModCount = Loader.instance().getModList().size();
        int aModCount = Loader.instance().getActiveModList().size();
        brd.add(String.format("%d mod%s loaded, %d mod%s active", tModCount, tModCount!=1 ? "s" :"", aModCount, aModCount!=1 ? "s" :"" ));
        brandings = brd.build();
        brandingsNoMC = brandings.subList(1, brandings.size());
    }
}
项目:morf    文件:OracleDialect.java   
/**
 * @see org.alfasoftware.morf.jdbc.SqlDialect#addTableFromStatements(org.alfasoftware.morf.metadata.Table, org.alfasoftware.morf.sql.SelectStatement)
 */
@Override
public Collection<String> addTableFromStatements(Table table, SelectStatement selectStatement) {
  Builder<String> result = ImmutableList.<String>builder();
  result.add(new StringBuilder()
      .append(createTableStatement(table, true))
      .append(" AS ")
      .append(convertStatementToSQL(selectStatement))
      .toString()
    );
  result.add("ALTER TABLE " + qualifiedTableName(table) + " NOPARALLEL LOGGING");

  if (!primaryKeysForTable(table).isEmpty()) {
    result.add("ALTER INDEX " + schemaNamePrefix() + primaryKeyConstraintName(table.getName()) + " NOPARALLEL LOGGING");
  }

  result.addAll(buildRemainingStatementsAndComments(table));

  return result.build();
}
项目:morf    文件:SqlServerDialect.java   
@Override
public Collection<String> renameTableStatements(Table fromTable, Table toTable) {
  String from = fromTable.getName();
  String to = toTable.getName();
  Builder<String> builder = ImmutableList.<String>builder();

  builder.add("IF EXISTS (SELECT 1 FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'" + from + "_version_DF') AND type = (N'D')) exec sp_rename N'" + from + "_version_DF', N'" + to + "_version_DF'");

  if (!primaryKeysForTable(fromTable).isEmpty()) {
    builder.add("sp_rename N'" + from + "." + from + "_PK', N'" + to + "_PK', N'INDEX'");
  }

  builder.add("sp_rename N'" + from + "', N'" + to + "'");

  return builder.build();
}
项目:morf    文件:TestSqlStatements.java   
/**
 * Checks if parametrised query execution is working correctly.
 */
@Test
public void shouldExecuteParametrisedQuery()  {
  SqlScriptExecutor executor = sqlScriptExecutorProvider.get(new LoggingSqlScriptVisitor());

  SelectStatement testSelect = select(field("alfaDate1"), field("alfaDate2"), literal(123))
                               .from(tableRef("DateTable")).where(eq(field("alfaDate1"), parameter("firstDateParam").type(DataType.BIG_INTEGER)));;
  Iterable<SqlParameter> parameterMetadata = ImmutableList.of(parameter(column("firstDateParam", DataType.STRING)));
  RecordBuilder parameterData = DataSetUtils.record().setString("firstDateParam", "20040609");
  ResultSetProcessor<List<List<String>>> resultSetProcessor = new ResultSetProcessor<List<List<String>>>() {
    /**
     * Takes all rows and puts into two-dimension String array.
     */
    @Override
    public List<List<String>> process(ResultSet resultSet) throws SQLException {
      Builder<List<String>> builder = ImmutableList.<List<String>>builder();
      ResultSetMetaData metaData = resultSet.getMetaData();
      int columnCount = metaData.getColumnCount();

      while (resultSet.next()) {
        List<String> rowBuilder = new LinkedList<>();
        for (int columnNumber = 1; columnNumber < columnCount + 1; columnNumber++) {
          String stringifiezedCell = resultSet.getString(columnNumber);
          rowBuilder.add(stringifiezedCell);
        }
        builder.add(rowBuilder);
      }
      return builder.build();
    }
  };
  List<List<String>> result = executor.executeQuery(testSelect, parameterMetadata, parameterData, connection, resultSetProcessor);

  assertEquals(ImmutableList.of(ImmutableList.of("20040609","20040813", "123"), ImmutableList.of("20040609","20040609", "123") , ImmutableList.of("20040609","20040610", "123")), result);
}
项目:morf    文件:H2Dialect.java   
/**
 * @see org.alfasoftware.morf.jdbc.SqlDialect#renameTableStatements(java.lang.String, java.lang.String)
 */
@Override
public Collection<String> renameTableStatements(Table from, Table to) {

  Builder<String> builder = ImmutableList.<String>builder();

  if (!primaryKeysForTable(from).isEmpty()) {
    builder.add(dropPrimaryKeyConstraintStatement(from));
  }

  builder.add("ALTER TABLE " + from.getName() + " RENAME TO " + to.getName());

  if (!primaryKeysForTable(to).isEmpty()) {
    builder.add(addPrimaryKeyConstraintStatement(to, namesOfColumns(primaryKeysForTable(to))));
  }

  return builder.build();
}
项目:morf    文件:NuoDBDialect.java   
/**
 * @see org.alfasoftware.morf.jdbc.SqlDialect#alterTableAddColumnStatements(org.alfasoftware.morf.metadata.Table, org.alfasoftware.morf.metadata.Column)
 */
@Override
public Collection<String> alterTableAddColumnStatements(Table table, Column column) {
  ImmutableList.Builder<String> statements = ImmutableList.builder();

  statements.add(
    new StringBuilder().append("ALTER TABLE ").append(qualifiedTableName(table)).append(" ADD COLUMN ")
      .append(column.getName()).append(' ').append(sqlRepresentationOfColumnType(column, true))
      .toString()
  );

  if (StringUtils.isNotBlank(column.getDefaultValue()) && column.isNullable()) {
    statements.add("UPDATE " + table.getName() + " SET " + column.getName() + " = " + getSqlFrom(new FieldLiteral(column.getDefaultValue(), column.getType())));
  }

  return statements.build();
}
项目:morf    文件:NuoDBDialect.java   
/**
 * @see org.alfasoftware.morf.jdbc.SqlDialect#renameTableStatements(java.lang.String, java.lang.String)
 */
@Override
public Collection<String> renameTableStatements(Table from, Table to) {

  Builder<String> builder = ImmutableList.<String>builder();

  if (!primaryKeysForTable(from).isEmpty()) {
    builder.add(dropPrimaryKeyConstraintStatement(from));
  }

  builder.add("ALTER TABLE " + qualifiedTableName(from) + " RENAME TO " + qualifiedTableName(to));

  if (!primaryKeysForTable(to).isEmpty()) {
    builder.add(addPrimaryKeyConstraintStatement(to, namesOfColumns(primaryKeysForTable(to))));
  }

  return builder.build();
}
项目:morf    文件:MockDialect.java   
/**
 * @see org.alfasoftware.morf.jdbc.SqlDialect#renameTableStatements(java.lang.String, java.lang.String)
 */
@Override
public Collection<String> renameTableStatements(Table from, Table to) {

  Builder<String> builder = ImmutableList.<String>builder();

  if (!primaryKeysForTable(from).isEmpty()) {
    builder.add(dropPrimaryKeyConstraintStatement(from));
  }

  builder.add("ALTER TABLE " + from.getName() + " RENAME TO " + to.getName());

  if (!primaryKeysForTable(to).isEmpty()) {
    builder.add(addPrimaryKeyConstraintStatement(to, namesOfColumns(primaryKeysForTable(to))));
  }

  return builder.build();
}
项目:rx-composer    文件:Page.java   
/**
 * Concurrently fetches the fragments of the page and returns the {@link Content#isAvailable() available} {@link Contents}.
 *
 * @param params Parameters used to fetch the content
 * @param tracer the Tracer used to process {@link TraceEvent trace events}.
 * @return available Contents
 */
public Contents fetchWith(final Parameters params, final Tracer tracer) {

    // use a latch to await execution of all fragments:
    final CountDownLatch latch = new CountDownLatch(1);
    final Contents.Builder contents = contentsBuilder();
    from(fragments)
            .flatMap((fragment) -> fragment.fetchWith(tracer, params))
            .subscribe(
                    contents::add,
                    (t) -> LOG.error(t.getMessage(), t),
                    latch::countDown
            );
    try {
        // wait for completion of the plan execution:
        latch.await();
    } catch (final InterruptedException e) {
        LOG.error("Interrupted waiting for Contents: {}", e.getMessage());
    }
    final Statistics statistics = tracer.getStatistics();
    LOG.info(statistics.toString());
    return contents
            .setStats(statistics)
            .build();
}
项目:elastic-crud    文件:ElasticSearchRepository.java   
@Override
public List<String> deleteAllIds(final Collection<String> ids) {
  if (ids.isEmpty()) {
    return ImmutableList.of();
  }

  final BulkRequestBuilder bulk = client
    .prepareBulk()
    .setRefreshPolicy(policy.get());

  for (final String id : ids) {
    bulk.add(client.prepareDelete(index, type, id));
  }

  final BulkResponse response = bulk.execute().actionGet();

  final ImmutableList.Builder<String> builder = ImmutableList.builder();
  for (final BulkItemResponse item : response.getItems()) {
    builder.add(item.getId());
  }
  return builder.build();
}
项目:android-arscblamer    文件:ArscDumper.java   
public static void main(String[] args) throws IOException {
  InjectedApplication application = new InjectedApplication.Builder(args)
      .withParameter(Params.class, CommonParams.class)
      .withModule(new ArscModule())
      .build();
  ArscDumper dumper = application.get(ArscDumper.class);
  Params params = application.get(Params.class);
  CommonParams commonParams = application.get(CommonParams.class);

  try (BufferedWriter writer = new BufferedWriter(getWriter(commonParams.getOutput()))) {
    switch (params.type) {
      case CONFIGS:
        dumper.dumpResourceConfigs(writer, params.keys);
        break;
      case ENTRIES:
        dumper.dumpEntries(writer);
        break;
      case BASELESS_KEYS:
        dumper.dumpBaselessKeys(writer);
        break;
      default:
        throw new UnsupportedOperationException(
            String.format("Missing implementation for type: %s.", params.type));
    }
  }
}
项目:turbine    文件:Lower.java   
/** Lower type annotations in a class declaration's signature. */
private ImmutableList<TypeAnnotationInfo> classTypeAnnotations(SourceTypeBoundClass info) {
  ImmutableList.Builder<TypeAnnotationInfo> result = ImmutableList.builder();
  {
    if (info.superClassType() != null) {
      lowerTypeAnnotations(
          result,
          info.superClassType(),
          TargetType.SUPERTYPE,
          new TypeAnnotationInfo.SuperTypeTarget(-1));
    }
    int idx = 0;
    for (Type i : info.interfaceTypes()) {
      lowerTypeAnnotations(
          result, i, TargetType.SUPERTYPE, new TypeAnnotationInfo.SuperTypeTarget(idx++));
    }
  }
  typeParameterAnnotations(
      result,
      info.typeParameterTypes().values(),
      TargetType.CLASS_TYPE_PARAMETER,
      TargetType.CLASS_TYPE_PARAMETER_BOUND);
  return result.build();
}
项目:turbine    文件:DisambiguateTypeAnnotations.java   
private static MethodInfo bindMethod(Env<ClassSymbol, TypeBoundClass> env, MethodInfo base) {
  ImmutableList.Builder<AnnoInfo> declarationAnnotations = ImmutableList.builder();
  Type returnType =
      disambiguate(
          env,
          base.name().equals("<init>") ? ElementType.CONSTRUCTOR : ElementType.METHOD,
          base.returnType(),
          base.annotations(),
          declarationAnnotations);
  return new MethodInfo(
      base.sym(),
      base.tyParams(),
      returnType,
      bindParameters(env, base.parameters()),
      base.exceptions(),
      base.access(),
      base.defaultValue(),
      base.decl(),
      declarationAnnotations.build(),
      base.receiver() != null ? bindParam(env, base.receiver()) : null);
}
项目:turbine    文件:DisambiguateTypeAnnotations.java   
/**
 * Moves type annotations in {@code annotations} to {@code type}, and adds any declaration
 * annotations on {@code type} to {@code declarationAnnotations}.
 */
private static Type disambiguate(
    Env<ClassSymbol, TypeBoundClass> env,
    ElementType declarationTarget,
    Type type,
    ImmutableList<AnnoInfo> annotations,
    Builder<AnnoInfo> declarationAnnotations) {
  // desugar @Repeatable annotations before disambiguating: annotation containers may target
  // a subset of the types targeted by their element annotation
  annotations = groupRepeated(env, annotations);
  ImmutableList.Builder<AnnoInfo> typeAnnotations = ImmutableList.builder();
  for (AnnoInfo anno : annotations) {
    Set<ElementType> target = env.get(anno.sym()).annotationMetadata().target();
    if (target.contains(ElementType.TYPE_USE)) {
      typeAnnotations.add(anno);
    }
    if (target.contains(declarationTarget)) {
      declarationAnnotations.add(anno);
    }
  }
  return addAnnotationsToType(type, typeAnnotations.build());
}
项目:turbine    文件:Transitive.java   
public static ImmutableMap<String, byte[]> collectDeps(
    ClassPath bootClassPath, BindingResult bound) {
  ImmutableMap.Builder<String, byte[]> transitive = ImmutableMap.builder();
  for (ClassSymbol sym : superClosure(bound)) {
    BytecodeBoundClass info = bound.classPathEnv().get(sym);
    if (info == null) {
      // the symbol wasn't loaded from the classpath
      continue;
    }
    if (bootClassPath.env().get(sym) != null) {
      // don't export symbols loaded from the bootclasspath
      continue;
    }
    transitive.put(sym.binaryName(), ClassWriter.writeClass(trimClass(info.classFile())));
  }
  return transitive.build();
}
项目:api-compiler    文件:HttpAttribute.java   
private ImmutableList<FieldSelector> buildVisibleSelectors(
    List<FieldSelector> selectors) {
  ImmutableList.Builder<FieldSelector> listBuilder = ImmutableList.builder();
  for (FieldSelector selector : selectors) {
    boolean hasInvisibleField = false;
    for (Field field : selector.getFields()) {
      if (!field.isReachable()) {
        hasInvisibleField = true;
        break;
      }
    }
    // Only include FieldSelector that has no invisible field.
    if (!hasInvisibleField) {
      listBuilder.add(selector);
    }
  }
  return listBuilder.build();
}
项目:java-crypto-conditions    文件:ValidVectorTest.java   
/**
 * Loads a list of tests based on the json-encoded test vector files.
 */
@Parameters(name = "Test Vector {index}: {0}")
public static Collection<TestVector> testVectorData() throws Exception {
  final URI baseUri =
      ValidVectorTest.class.getResource(ValidVectorTest.class.getSimpleName() + ".class").toURI();
  final File baseDirectoryFile = new File(baseUri).getParentFile();
  final File validTestVectorDir = new File(baseDirectoryFile, "/vectors/valid");

  final Builder<TestVector> vectors = ImmutableList.builder();
  final ObjectMapper mapper = new ObjectMapper();

  Arrays.stream(validTestVectorDir.listFiles()).forEach(file -> {
    try {
      if (file.getName().endsWith(".json")) {
        TestVector vector = mapper.readValue(file, TestVector.class);
        vector.setName(file.getName().substring(0, file.getName().length() - 5));
        vectors.add(vector);
      }
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  });

  return vectors.build();
}
项目:java-crypto-conditions    文件:AbstractCryptoConditionTest.java   
/**
 * Concurrently runs one or more instances of {@link Runnable} in a multithreaded fashion,
 * relying upon {@code numThreads} for concurrency.
 */
protected void runConcurrent(final int numThreads, final Runnable... runnableTest)
    throws InterruptedException {
  final Builder<Runnable> builder = ImmutableList.builder();

  // For each runnableTest, add it numThreads times to the bulider.
  for (final Runnable runnable : runnableTest) {
    for (int i = 0; i < numThreads; i++) {
      builder.add(runnable);
    }
  }

  logger.info(String.format("About to run %s threads...", numThreads));
  // Actually runs the Runnables above using multiple threads.
  assertConcurrent("Test did not complete before the harness timed-out. Please consider "
      + "increasing the timeout value for this test.", builder.build(), 15);
  logger.info(String.format("Ran %s threads!", numThreads));
}
项目:xtext-core    文件:AbstractSemanticRegionsFinder.java   
@Override
public List<Pair<ISemanticRegion, ISemanticRegion>> keywordPairs(Keyword kw1, Keyword kw2) {
    Preconditions.checkNotNull(kw1);
    Preconditions.checkNotNull(kw2);
    Preconditions.checkArgument(kw1 != kw2);
    Predicate<ISemanticRegion> p1 = createPredicate(kw1);
    Predicate<ISemanticRegion> p2 = createPredicate(kw2);
    List<ISemanticRegion> all = findAll(Predicates.or(p1, p2));
    Builder<Pair<ISemanticRegion, ISemanticRegion>> result = ImmutableList.builder();
    LinkedList<ISemanticRegion> stack = new LinkedList<ISemanticRegion>();
    for (ISemanticRegion region : all) {
        if (p1.apply(region))
            stack.push(region);
        else if (!stack.isEmpty())
            result.add(Pair.of(stack.pop(), region));
    }
    return result.build();
}
项目:nexus-public    文件:SearchMappingsServiceImpl.java   
private static Collection<SearchMapping> collectMappings(final Map<String, SearchMappings> searchMappings) {
  final Builder<SearchMapping> builder = ImmutableList.builder();

  // put the default mappings in first
  final SearchMappings defaultMappings = searchMappings.get(DEFAULT);
  if (defaultMappings != null) {
    builder.addAll(defaultMappings.get());
  }

  // add the rest of the mappings
  searchMappings.keySet().stream()
      .filter(key -> !DEFAULT.equals(key))
      .sorted()
      .forEach(key -> builder.addAll(searchMappings.get(key).get()));

  return builder.build();
}
项目:FinanceAnalytics    文件:ComponentManager.java   
/**
 * Intelligently sets the property.
 * <p>
 * This uses the repository to link properties declared with classifiers to the instance.
 * 
 * @param bean  the bean, not null
 * @param mp  the property, not null
 * @param value  the configured value, not null
 * @throws ComponentConfigException if the property cannot be initialized
 */
protected void setPropertyInferType(Bean bean, MetaProperty<?> mp, String value) {
  Class<?> propertyType = mp.propertyType();
  if (isConvertibleFromString(mp.propertyType())) {
    // set property by value type conversion from String
    mp.set(bean, convert(propertyType, value));

  } else if (Collection.class.isAssignableFrom(propertyType)) {
    // set property by value type conversion from comma separated String
    Class<?> collType = JodaBeanUtils.collectionType(mp, bean.getClass());
    if (isConvertibleFromString(collType)) {
      Iterable<String> split = Splitter.on(',').trimResults().split(value);
      Builder<Object> builder = ImmutableList.builder();
      for (String singleValue : split) {
        builder.add(convert(collType, singleValue));
      }
      mp.set(bean, builder.build());
    } else {
      throw new ComponentConfigException(String.format("No mechanism found to set collection property %s from value: %s", mp, value));
    }

  } else {
    throw new ComponentConfigException(String.format("No mechanism found to set property %s from value: %s", mp, value));
  }
}
项目:theta    文件:XtaAction.java   
private BasicXtaAction(final XtaSystem system, final List<Loc> sourceLocs, final Edge edge) {
    super(system, sourceLocs);
    this.edge = checkNotNull(edge);

    final ImmutableList.Builder<Loc> builder = ImmutableList.builder();
    final Loc source = edge.getSource();
    final Loc target = edge.getTarget();
    boolean matched = false;
    for (final Loc loc : sourceLocs) {
        if (loc.equals(source)) {
            checkArgument(!matched);
            builder.add(target);
            matched = true;
        } else {
            builder.add(loc);
        }
    }
    checkArgument(matched);
    targetLocs = builder.build();
}
项目:theta    文件:XtaAction.java   
@Override
public List<Stmt> getStmts() {
    List<Stmt> result = stmts;
    if (stmts == null) {
        final ImmutableList.Builder<Stmt> builder = ImmutableList.builder();
        addInvariants(builder, getSourceLocs());
        addGuards(builder, edge);
        addUpdates(builder, edge);
        addInvariants(builder, targetLocs);
        if (shouldApplyDelay(getTargetLocs())) {
            addDelay(builder, getClockVars());
        }
        result = builder.build();
        stmts = result;
    }
    return result;
}
项目:theta    文件:XtaAction.java   
@Override
public List<Stmt> getStmts() {
    List<Stmt> result = stmts;
    if (stmts == null) {
        final ImmutableList.Builder<Stmt> builder = ImmutableList.builder();
        addInvariants(builder, getSourceLocs());
        addSync(builder, emitEdge, recvEdge);
        addGuards(builder, emitEdge);
        addGuards(builder, recvEdge);
        addUpdates(builder, emitEdge);
        addUpdates(builder, recvEdge);
        addInvariants(builder, targetLocs);
        if (shouldApplyDelay(getTargetLocs())) {
            addDelay(builder, getClockVars());
        }
        result = builder.build();
        stmts = result;
    }
    return result;
}
项目:broker-store    文件:DirHelper.java   
public static List<String> dirList(String path){
    Builder<String> builder = ImmutableList.builder();
    File folder = new File(path);
    File[] files = folder.listFiles();
    if(files == null) {
        throw new NullPointerException();
    }
    for (File entry : files) {
        if (entry.isFile()) {
            builder.add("File : " + entry.getName());
        } else if (entry.isDirectory()) {
            builder.add("Directory : " + entry.getName());
        }
    }
    return builder.build();
}
项目:java-smt    文件:Z3Model.java   
@Override
protected ImmutableList<ValueAssignment> modelToList() {
  Builder<ValueAssignment> out = ImmutableList.builder();

  // Iterate through constants.
  for (int constIdx = 0; constIdx < Native.modelGetNumConsts(z3context, model); constIdx++) {
    long keyDecl = Native.modelGetConstDecl(z3context, model, constIdx);
    Native.incRef(z3context, keyDecl);
    out.addAll(getConstAssignments(keyDecl));
    Native.decRef(z3context, keyDecl);
  }

  // Iterate through function applications.
  for (int funcIdx = 0; funcIdx < Native.modelGetNumFuncs(z3context, model); funcIdx++) {
    long funcDecl = Native.modelGetFuncDecl(z3context, model, funcIdx);
    Native.incRef(z3context, funcDecl);
    if (!isInternalSymbol(funcDecl)) {
      String functionName = z3creator.symbolToString(Native.getDeclName(z3context, funcDecl));
      out.addAll(getFunctionAssignments(funcDecl, funcDecl, functionName));
    }
    Native.decRef(z3context, funcDecl);
  }

  return out.build();
}
项目:java-smt    文件:Mathsat5Model.java   
@Override
protected ImmutableList<ValueAssignment> modelToList() {
  Builder<ValueAssignment> assignments = ImmutableList.builder();

  long modelIterator = msat_model_create_iterator(model);
  while (msat_model_iterator_has_next(modelIterator)) {
    long[] key = new long[1];
    long[] value = new long[1];
    if (msat_model_iterator_next(modelIterator, key, value)) {
      throw new NoSuchElementException();
    }

    if (msat_is_array_type(creator.getEnv(), msat_term_get_type(value[0]))) {
      assignments.addAll(getArrayAssignments(key[0], key[0], value[0], Collections.emptyList()));
    } else {
      assignments.add(getAssignment(key[0], value[0]));
    }
  }
  msat_destroy_model_iterator(modelIterator);
  return assignments.build();
}