Java Code Examples for com.google.common.collect.ImmutableList#builder()

The following examples show how to use com.google.common.collect.ImmutableList#builder() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: UnusedDependenciesFinder.java    From buck with Apache License 2.0 6 votes vote down vote up
static ImmutableList<DependencyAndExportedDeps> getDependencies(
    BuildRuleResolver buildRuleResolver, SortedSet<BuildRule> targets) {
  ImmutableList.Builder<DependencyAndExportedDeps> builder = ImmutableList.builder();
  for (BuildRule rule : targets) {
    BuildTargetAndSourcePaths targetAndSourcePaths =
        getBuildTargetAndSourcePaths(rule, buildRuleResolver);
    if (targetAndSourcePaths == null) {
      continue;
    }

    ImmutableList<DependencyAndExportedDeps> exportedDeps =
        rule instanceof ExportDependencies
            ? getDependencies(buildRuleResolver, ((ExportDependencies) rule).getExportedDeps())
            : ImmutableList.of();
    builder.add(new DependencyAndExportedDeps(targetAndSourcePaths, exportedDeps));
  }

  return builder.build();
}
 
Example 2
Source File: ClientQueueMemoryLocalPersistenceTest.java    From hivemq-community-edition with Apache License 2.0 6 votes vote down vote up
@Test
public void test_batched_add() {
    final ImmutableList.Builder<PUBLISH> publishes = ImmutableList.builder();
    for (int i = 0; i < 10; i++) {
        publishes.add(createPublish(1, QoS.AT_LEAST_ONCE, "topic" + i));
    }
    persistence.add("client", false, publishes.build(), 100, DISCARD, false, 0);

    assertEquals(10, persistence.size("client", false, 0));

    final ImmutableList<PUBLISH> all =
            persistence.readNew("client", false, ImmutableIntArray.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), 10000L, 0);

    assertEquals(10, all.size());
    assertEquals("topic0", all.get(0).getTopic());
    assertEquals("topic1", all.get(1).getTopic());
}
 
Example 3
Source File: TargetCompleteEvent.java    From bazel with Apache License 2.0 6 votes vote down vote up
@Override
public Collection<BuildEventId> getChildrenEvents() {
  ImmutableList.Builder<BuildEventId> childrenBuilder = ImmutableList.builder();
  for (Cause cause : getRootCauses().toList()) {
    childrenBuilder.add(cause.getIdProto());
  }
  if (isTest) {
    // For tests, announce all the test actions that will minimally happen (except for
    // interruption). If after the result of a test action another attempt is necessary,
    // it will be announced with the action that made the new attempt necessary.
    Label label = getLabel();
    for (int run = 0; run < Math.max(testParams.getRuns(), 1); run++) {
      for (int shard = 0; shard < Math.max(testParams.getShards(), 1); shard++) {
        childrenBuilder.add(BuildEventIdUtil.testResult(label, run, shard, configEventId));
      }
    }
    childrenBuilder.add(BuildEventIdUtil.testSummary(label, configEventId));
  }
  return childrenBuilder.build();
}
 
Example 4
Source File: CxxWriteArgsToFileStep.java    From buck with Apache License 2.0 6 votes vote down vote up
static ImmutableList<String> stringify(
    ImmutableCollection<Arg> args,
    CanonicalCellName currentCellName,
    SourcePathResolverAdapter pathResolver,
    boolean useUnixPathSeparator) {
  ImmutableList.Builder<String> builder = ImmutableList.builder();
  for (Arg arg : args) {
    if (arg instanceof FileListableLinkerInputArg) {
      ((FileListableLinkerInputArg) arg)
          .appendToCommandLineRel(
              builder::add, currentCellName, pathResolver, useUnixPathSeparator);
    } else if (arg instanceof SourcePathArg) {
      ((SourcePathArg) arg)
          .appendToCommandLineRel(
              builder::add, currentCellName, pathResolver, useUnixPathSeparator);
    } else if (arg instanceof CompositeArg) {
      ((CompositeArg) arg)
          .appendToCommandLineRel(
              builder::add, currentCellName, pathResolver, useUnixPathSeparator);
    } else {
      arg.appendToCommandLine(builder::add, pathResolver);
    }
  }
  return builder.build();
}
 
Example 5
Source File: AppleSimulatorDiscoveryTest.java    From buck with Apache License 2.0 6 votes vote down vote up
@Test
public void appleSimulatorsDiscoveredFromRetrySimctlList()
    throws IOException, InterruptedException {
  ProcessExecutorParams processExecutorParams =
      ProcessExecutorParams.builder()
          .setCommand(ImmutableList.of("path/to/simctl", "list"))
          .build();

  ImmutableList.Builder<Map.Entry<ProcessExecutorParams, FakeProcess>> fakeProcessesBuilder =
      ImmutableList.builder();
  fakeProcessesBuilder.add(
      new SimpleImmutableEntry<>(processExecutorParams, new FakeProcess(42, "", "")));
  fakeProcessesBuilder.add(
      new SimpleImmutableEntry<>(processExecutorParams, new FakeProcess(42, "", "")));
  fakeProcessesBuilder.add(
      new SimpleImmutableEntry<>(processExecutorParams, new FakeProcess(0, "", "")));

  FakeProcessExecutor fakeProcessExecutor = new FakeProcessExecutor(fakeProcessesBuilder.build());

  AppleSimulatorDiscovery.discoverAppleSimulators(
      fakeProcessExecutor, Paths.get("path/to/simctl"));
}
 
Example 6
Source File: CommandExecutor.java    From redis-mock with MIT License 5 votes vote down vote up
public Slice mget(List<Slice> params) throws WrongNumberOfArgumentsException {
    checkArgumentsNumberGreater(params, 0);

    ImmutableList.Builder<Slice> builder = new ImmutableList.Builder<Slice>();
    for (Slice key : params) {
        builder.add(Response.bulkString(base.rawGet(key)));

    }
    return Response.array(builder.build());
}
 
Example 7
Source File: TypeConverter.java    From tajo with Apache License 2.0 5 votes vote down vote up
public static Type convert(TypeDesc type) {
  if (type.getDataType().getType() == TajoDataTypes.Type.RECORD) {
    ImmutableList.Builder<Field> fields = ImmutableList.builder();
    for (Column c : type.getNestedSchema().getRootColumns()) {
      fields.add(FieldConverter.convert(c));
    }
    return Record(fields.build());
  } else {
    return convert(type.dataType);
  }
}
 
Example 8
Source File: RelBuilder.java    From Bats with Apache License 2.0 5 votes vote down vote up
/** Returns references to fields for a given list of input ordinals. */
public ImmutableList<RexNode> fields(List<? extends Number> ordinals) {
    final ImmutableList.Builder<RexNode> nodes = ImmutableList.builder();
    for (Number ordinal : ordinals) {
        RexNode node = field(1, 0, ordinal.intValue(), false);
        nodes.add(node);
    }
    return nodes.build();
}
 
Example 9
Source File: OcamlMLCompileStep.java    From buck with Apache License 2.0 5 votes vote down vote up
@Override
protected ImmutableList<String> getShellCommandInternal(ExecutionContext context) {
  ImmutableList.Builder<String> cmd =
      ImmutableList.<String>builder()
          .addAll(args.ocamlCompiler.getCommandPrefix(resolver))
          .addAll(OcamlCompilables.DEFAULT_OCAML_FLAGS);

  if (args.stdlib.isPresent()) {
    cmd.add("-nostdlib", OcamlCompilables.OCAML_INCLUDE_FLAG, args.stdlib.get());
  }

  String ext = Files.getFileExtension(args.input.toString());
  String dotExt = "." + ext;
  boolean isImplementation =
      dotExt.equals(OcamlCompilables.OCAML_ML) || dotExt.equals(OcamlCompilables.OCAML_RE);
  boolean isReason =
      dotExt.equals(OcamlCompilables.OCAML_RE) || dotExt.equals(OcamlCompilables.OCAML_REI);

  cmd.add("-cc", args.cCompiler.get(0))
      .addAll(
          MoreIterables.zipAndConcat(
              Iterables.cycle("-ccopt"), args.cCompiler.subList(1, args.cCompiler.size())))
      .add("-c")
      .add("-annot")
      .add("-bin-annot")
      .add("-o", args.output.toString())
      .addAll(Arg.stringify(args.flags, resolver));

  if (isReason && isImplementation) {
    cmd.add("-pp").add("refmt").add("-intf-suffix").add("rei").add("-impl");
  }
  if (isReason && !isImplementation) {
    cmd.add("-pp").add("refmt").add("-intf");
  }

  cmd.add(args.input.toString());
  return cmd.build();
}
 
Example 10
Source File: TestSpatialPartitioningInternalAggregation.java    From presto with Apache License 2.0 5 votes vote down vote up
private List<OGCGeometry> makeGeometries()
{
    ImmutableList.Builder<OGCGeometry> geometries = ImmutableList.builder();
    for (int i = 0; i < 10; i++) {
        for (int j = 0; j < 10; j++) {
            geometries.add(new OGCPoint(new Point(-10 + i, -10 + j), null));
        }
    }

    for (int i = 0; i < 5; i++) {
        for (int j = 0; j < 5; j++) {
            geometries.add(new OGCPoint(new Point(-10 + 2 * i, 2 * j), null));
        }
    }

    for (int i = 0; i < 4; i++) {
        for (int j = 0; j < 4; j++) {
            geometries.add(new OGCPoint(new Point(2.5 * i, -10 + 2.5 * j), null));
        }
    }

    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            geometries.add(new OGCPoint(new Point(5 * i, 5 * j), null));
        }
    }

    return geometries.build();
}
 
Example 11
Source File: GitRepository.java    From copybara with Apache License 2.0 5 votes vote down vote up
/**
 * Find submodules information for the current repository.
 *
 * @param currentRemoteUrl remote url associated with the repository. It will be used to
 * resolve relative URLs (for example: url = ../foo).
 */
Iterable<Submodule> listSubmodules(String currentRemoteUrl) throws RepoException {
  ImmutableList.Builder<Submodule> result = ImmutableList.builder();
  for (String submoduleName : getSubmoduleNames()) {
    String path = getSubmoduleField(submoduleName, "path");

    if (path == null) {
      throw new RepoException("Path is required for submodule " + submoduleName);
    }
    String url = getSubmoduleField(submoduleName, "url");
    if (url == null) {
      throw new RepoException("Url is required for submodule " + submoduleName);
    }
    String branch = getSubmoduleField(submoduleName, "branch");
    if (branch != null && branch.equals(".")) {
      branch = "HEAD";
    }
    FileUtil.checkNormalizedRelative(path);
    // If the url is relative, construct a url using the parent module remote url.
    if (url.startsWith("../")) {
      url = siblingUrl(currentRemoteUrl, submoduleName, url.substring(3));
    } else if (url.startsWith("./")) {
      url = siblingUrl(currentRemoteUrl, submoduleName, url.substring(2));
    }
    try {
      result.add(new Submodule(validateUrl(url), submoduleName, branch, path));
    } catch (ValidationException e) {
      throw new RepoException("Invalid url: " + url, e);
    }
  }
  return result.build();
}
 
Example 12
Source File: FieldScopeLogic.java    From curiostack with MIT License 5 votes vote down vote up
@Override
final FieldScopeLogic subScopeImpl(
    Descriptor rootDescriptor, FieldDescriptorOrUnknown fieldDescriptorOrUnknown) {
  ImmutableList.Builder<FieldScopeLogic> builder =
      ImmutableList.builderWithExpectedSize(elements.size());
  for (FieldScopeLogic elem : elements) {
    builder.add(elem.subScope(rootDescriptor, fieldDescriptorOrUnknown));
  }
  return newLogicOfSameType(builder.build());
}
 
Example 13
Source File: Grib2Tables.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static ImmutableList<Grib2Tables> getAllRegisteredTables() {
  ImmutableList.Builder<Grib2Tables> builder = ImmutableList.builder();
  for (Grib2TableConfig config : Grib2TableConfig.getTables()) {
    builder.add(build(config));
  }
  return builder.build();
}
 
Example 14
Source File: QuantileDigest.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the values at the specified quantiles +/- maxError. The list of quantiles must be sorted
 * in increasing order, and each value must be in the range [0, 1]
 */
public List<Long> getQuantiles(List<Double> quantiles) {
  checkArgument(Ordering.natural().isOrdered(quantiles), "quantiles must be sorted in increasing order");
  for (double quantile : quantiles) {
    checkArgument(quantile >= 0 && quantile <= 1, "quantile must be between [0,1]");
  }

  final ImmutableList.Builder<Long> builder = ImmutableList.builder();
  final PeekingIterator<Double> iterator = Iterators.peekingIterator(quantiles.iterator());

  postOrderTraversal(root, new Callback() {
    private double sum = 0;

    @Override
    public boolean process(Node node) {
      sum += node.weightedCount;

      while (iterator.hasNext() && sum > iterator.peek() * weightedCount) {
        iterator.next();

        // we know the max value ever seen, so cap the percentile to provide better error
        // bounds in this case
        long value = Math.min(node.getUpperBound(), max);

        builder.add(value);
      }

      return iterator.hasNext();
    }
  });

  // we finished the traversal without consuming all quantiles. This means the remaining quantiles
  // correspond to the max known value
  while (iterator.hasNext()) {
    builder.add(max);
    iterator.next();
  }

  return builder.build();
}
 
Example 15
Source File: PlaceholderIdFieldInitializerBuilder.java    From bazel with Apache License 2.0 5 votes vote down vote up
private static ImmutableList<FieldInitializer> getAttrInitializers(
    Map<String, Integer> attrAssignments, SortedMap<String, ResourceLinkageInfo> sortedFields) {
  ImmutableList.Builder<FieldInitializer> initList = ImmutableList.builder();
  for (Map.Entry<String, ResourceLinkageInfo> entry : sortedFields.entrySet()) {
    String field = entry.getKey();
    ResourceLinkageInfo linkageInfo = entry.getValue();
    int attrId = attrAssignments.get(field);
    initList.add(
        IntFieldInitializer.of(
            linkageInfo.dependencyInfo(), linkageInfo.visibility(), field, attrId));
  }
  return initList.build();
}
 
Example 16
Source File: GNSS_MeasurementForOneGNSS.java    From supl-client with Apache License 2.0 4 votes vote down vote up
@Override public Iterable<? extends SequenceComponent>
                                                getExtensionComponents() {
ImmutableList.Builder<SequenceComponent> builder = ImmutableList.builder();
  
  return builder.build();
}
 
Example 17
Source File: GNSS_AlmanacSupport.java    From supl-client with Apache License 2.0 4 votes vote down vote up
@Override public Iterable<? extends SequenceComponent> getComponents() {
  ImmutableList.Builder<SequenceComponent> builder = ImmutableList.builder();
  
  builder.add(new SequenceComponent() {
        Asn1Tag tag = Asn1Tag.fromClassAndNumber(2, 0);

        @Override public boolean isExplicitlySet() {
          return getAlmanacModel() != null;
        }

        @Override public boolean hasDefaultValue() {
          return false;
        }

        @Override public boolean isOptional() {
          return true;
        }

        @Override public Asn1Object getComponentValue() {
          return getAlmanacModel();
        }

        @Override public void setToNewInstance() {
          setAlmanacModelToNewInstance();
        }

        @Override public Collection<Asn1Tag> getPossibleFirstTags() {
          return tag == null ? GNSS_AlmanacSupport.almanacModelType.getPossibleFirstTags() : ImmutableList.of(tag);
        }

        @Override
        public Asn1Tag getTag() {
          return tag;
        }

        @Override
        public boolean isImplicitTagging() {
          return true;
        }

        @Override public String toIndentedString(String indent) {
              return "almanacModel : "
                  + getAlmanacModel().toIndentedString(indent);
            }
      });
  
  return builder.build();
}
 
Example 18
Source File: ConfigGeneratorToolTest.java    From api-compiler with Apache License 2.0 4 votes vote down vote up
private void test(String baseName, @Nullable String extensionName, boolean outputWarnings,
    List<String> experiments) throws Exception {
  TestDataLocator locator = TestDataLocator.create(getClass());

  ImmutableList.Builder<String> protoFilesBuilder = ImmutableList.builder();
  protoFilesBuilder.add(baseName + ".proto");
  TestConfig testConfig = new TestConfig(locator, tempDir.getRoot().getPath(),
      protoFilesBuilder.build());

  TestConfig extensionTestConfig = null;
  if (extensionName != null) {
    extensionTestConfig = new TestConfig(locator, extensionTempDir.getRoot().getPath(),
        ImmutableList.of(extensionName + ".proto"));
  }

  List<String> configFiles = new ArrayList<>();
  configFiles.add(baseName + ".yaml");
  final TestConfig testConfigCopy = testConfig;
  configFiles = FluentIterable.from(configFiles).transform(
      new Function<String, String>() {
        @Override
        public String apply(String file) {
          return testConfigCopy.copyTestDataAndGetPath(file).toString();
        }
      }).toList();

  ToolOptions options = ToolOptions.create();
  options.set(
      ConfigGeneratorDriver.TXT_OUT,
      (new File(tempDir.getRoot().getPath(), "textout")).getAbsolutePath());
  options.set(
      ConfigGeneratorDriver.BIN_OUT,
      (new File(tempDir.getRoot().getPath(), "binout")).getAbsolutePath());
  options.set(
      ConfigGeneratorDriver.JSON_OUT,
      (new File(tempDir.getRoot().getPath(), "jsonout")).getAbsolutePath());
  options.set(ToolOptions.DESCRIPTOR_SET, testConfig.getDescriptorFile().toString());
  options.set(ToolOptions.CONFIG_FILES, configFiles);
  options.set(
      ConfigGeneratorFromProtoDescriptor.SUPPRESS_WARNINGS, isSuppressWarningsTest(baseName));
  options.set(ToolOptions.EXPERIMENTS, experiments);
  if (extensionTestConfig != null) {
    options.set(
        ToolOptions.EXTENSION_DESCRIPTOR_SET, extensionTestConfig.getDescriptorFile().toString());
  }

  if (isLibraryWithError(baseName)) {
    options.set(ConfigGeneratorFromProtoDescriptor.NAME, "foobar");
  }
  if (isDnsNameTest(baseName)){
    options.set(ConfigGeneratorFromProtoDescriptor.NAME, "foobar");
  }
  if (isSuppressWarningsTest(baseName)){
    options.set(ConfigGeneratorFromProtoDescriptor.NAME, "test");
  }
  ConfigGeneratorDriverForTest tool = new ConfigGeneratorDriverForTest(options);
  tool.runTest();
  if (!tool.hasErrors()) {
    // Output diag into baseline file, if needed.
    if (outputWarnings) {
      printDiags(tool.getDiags(), true);
    }
    Service.Builder serviceBuilder =
        ServiceConfigTestingUtil.clearIrrelevantData(tool.getServiceConfig().toBuilder());
    testOutput().println(
        "============== file: normalized config without derived data ==============");
    testOutput().println(TextFormatForTest.INSTANCE.printToString(serviceBuilder.build()));

    // Regenerate the model from service config and ensure it builds without errors.
    Service generatedServiceConfig = tool.getServiceConfig();
    Model model = Model.create(generatedServiceConfig);
    StandardSetup.registerStandardConfigAspects(model);
    StandardSetup.registerStandardProcessors(model);
    model.establishStage(Normalized.KEY);
    if (model.getDiagReporter().getDiagCollector().hasErrors()) {
      printDiags(model.getDiagReporter().getDiagCollector().getDiags(), false);
    } else {
      testOutput().println(
          "============== Successfully regenerated service config ==============");
    }
  } else {
    printDiags(tool.getDiags(), true);
  }
}
 
Example 19
Source File: GoTest.java    From buck with Apache License 2.0 4 votes vote down vote up
private ImmutableList<TestResultSummary> parseTestResults() throws IOException {
  ImmutableList.Builder<TestResultSummary> summariesBuilder = ImmutableList.builder();
  CharsetDecoder decoder = Charsets.UTF_8.newDecoder();
  decoder.onMalformedInput(CodingErrorAction.REPLACE);
  decoder.replaceWith(NON_PRINTABLE_REPLACEMENT);
  try (BufferedReader reader =
      new BufferedReader(
          new InputStreamReader(
              Files.newInputStream(getProjectFilesystem().resolve(getPathToTestResults())),
              decoder))) {
    Set<String> currentTests = new HashSet<>();
    List<String> stdout = new ArrayList<>();
    List<String> stackTrace = new ArrayList<>();
    String line = reader.readLine();
    while (line != null) {
      Matcher matcher;
      if ((matcher = TEST_START_PATTERN.matcher(line)).matches()) {
        currentTests.add(matcher.group("name"));
        line = reader.readLine();
      } else if ((matcher = TEST_FINISHED_PATTERN.matcher(line)).matches()) {
        if (!currentTests.contains(matcher.group("name"))) {
          throw new RuntimeException(
              String.format(
                  "Error parsing test output: test case end '%s' does not match any start in [%s]",
                  matcher.group("name"), Joiner.on(", ").join(currentTests)));
        }

        ResultType result = ResultType.FAILURE;
        if ("PASS".equals(matcher.group("status"))) {
          result = ResultType.SUCCESS;
        } else if ("SKIP".equals(matcher.group("status"))) {
          result = ResultType.ASSUMPTION_VIOLATION;
        }

        double timeTaken = 0.0;
        try {
          timeTaken = Float.parseFloat(matcher.group("duration"));
        } catch (NumberFormatException ex) {
          Throwables.throwIfUnchecked(ex);
        }
        line = reader.readLine();
        // Looking ahead to capture error messages
        while (line != null
            && !TEST_START_PATTERN.matcher(line).matches()
            && !TEST_FINISHED_PATTERN.matcher(line).matches()
            && !line.equals("PASS")
            && !line.equals("FAIL")) {
          stackTrace.add(line);
          line = reader.readLine();
        }
        summariesBuilder.add(
            new TestResultSummary(
                "go_test",
                matcher.group("name"),
                result,
                (long) (timeTaken * 1000),
                "",
                Joiner.on(System.lineSeparator()).join(stackTrace),
                Joiner.on(System.lineSeparator()).join(stdout),
                ""));

        currentTests.remove(matcher.group("name"));
        stdout.clear();
        stackTrace.clear();
      } else {
        stdout.add(line);
        line = reader.readLine();
      }
    }

    for (String testName : currentTests) {
      // This can happen in case of e.g. a panic.
      summariesBuilder.add(
          new TestResultSummary(
              "go_test",
              testName,
              ResultType.FAILURE,
              0,
              "incomplete",
              "",
              Joiner.on(System.lineSeparator()).join(stdout),
              ""));
    }
  }
  return summariesBuilder.build();
}
 
Example 20
Source File: SystemInfoAssistData.java    From supl-client with Apache License 2.0 4 votes vote down vote up
@Override public Iterable<? extends SequenceComponent>
                                                getExtensionComponents() {
ImmutableList.Builder<SequenceComponent> builder = ImmutableList.builder();
  
  return builder.build();
}