com.google.common.collect.ImmutableList.Builder#add ( )源码实例Demo

下面列出了com.google.common.collect.ImmutableList.Builder#add ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: arcusplatform   文件: IrisRtspSdp.java
private static void parseFormatParameters(String value, List<Media> media) {
   int idx = value.indexOf(" ");
   String format = value.substring(0, idx);
   String paramString = value.substring(idx + 1);

   String[] params = paramString.split(";");

   Builder<String> fvalue = ImmutableList.builder();
   for(int i = 1; i < params.length; i++) {
      fvalue.add(params[i].trim());
   }

   for (Media md : media) {
      if (md.format.equals(format)) {
         md.setFormatParameters(fvalue.build());
      }
   }
}
 
源代码2 项目: n4js   文件: NodeYarnProcessBuilder.java
/**
 * Prepares process builder for "cache clean" command, either using npm or yarn (depending on
 * {@link #isYarnUsed(Path)}).
 *
 * @param invocationPath
 *            location where the command should be invoked.
 * @return configured, operating system aware process builder for "npm/yarn cache clean" command.
 */
public ProcessBuilder getNpmCacheCleanProcessBuilder(File invocationPath) {
	Builder<String> builder = ImmutableList.<String> builder();

	Binary binary = isYarnUsed(invocationPath.toPath()) ? yarnBinaryProvider.get()
			: npmBinaryProvider.get();

	Optional<String[]> cacheCleanCommand = binary.getCacheCleanCommand();
	if (!cacheCleanCommand.isPresent()) {
		throw new IllegalStateException("cache clean not supported by binary: " + binary.getId());
	}

	if (isWindows()) {
		builder.add(WIN_SHELL_COMAMNDS);
		builder.add(concat(escapeBinaryPath(binary.getBinaryAbsolutePath()),
				cacheCleanCommand.get()));
	} else {
		builder.add(NIX_SHELL_COMAMNDS);
		builder.add(escapeBinaryPath(binary.getBinaryAbsolutePath())
				+ " " + Joiner.on(" ").join(cacheCleanCommand.get()));
	}

	return create(builder.build(), binary, invocationPath, false);
}
 
源代码3 项目: yangtools   文件: AbstractLithiumDataInput.java
private NodeIdentifierWithPredicates readNormalizedNodeWithPredicates() throws IOException {
    final QName qname = readQName();
    final int count = input.readInt();
    switch (count) {
        case 0:
            return NodeIdentifierWithPredicates.of(qname);
        case 1:
            return NodeIdentifierWithPredicates.of(qname, readQName(), readObject());
        default:
            // ImmutableList is used by ImmutableOffsetMapTemplate for lookups, hence we use that.
            final Builder<QName> keys = ImmutableList.builderWithExpectedSize(count);
            final Object[] values = new Object[count];
            for (int i = 0; i < count; i++) {
                keys.add(readQName());
                values[i] = readObject();
            }

            return NodeIdentifierWithPredicates.of(qname, ImmutableOffsetMapTemplate.ordered(keys.build())
                .instantiateWithValues(values));
    }
}
 
源代码4 项目: buck   文件: SuperConsoleEventBusListenerTest.java
private void validateBuildIdConsoleWithLogLines(
    SuperConsoleEventBusListener listener,
    TestRenderingConsole renderingConsole,
    long timeMs,
    ImmutableList<String> lines,
    ImmutableList<String> logLines) {

  Builder<String> builder =
      ImmutableList.builderWithExpectedSize(lines.size() + (printBuildId ? 1 : 0));
  if (printBuildId) {
    builder.add("Build UUID: 1234-5678");
  }
  builder.addAll(lines);

  validateConsoleWithStdOutAndErr(
      listener,
      renderingConsole,
      timeMs,
      builder.build(),
      logLines,
      Optional.of(""),
      Optional.of(""));
}
 
源代码5 项目: Mixin   文件: TypeHandle.java
@SuppressWarnings("unchecked")
protected static <T extends Element> List<T> getEnclosedElements(TypeElement targetElement, ElementKind... kind) {
    if (kind == null || kind.length < 1) {
        return (List<T>)TypeHandle.getEnclosedElements(targetElement);
    }
    
    if (targetElement == null) {
        return Collections.<T>emptyList();
    }
    
    Builder<T> list = ImmutableList.<T>builder();
    for (Element elem : targetElement.getEnclosedElements()) {
        for (ElementKind ek : kind) {
            if (elem.getKind() == ek) {
                list.add((T)elem);
                break;
            }
        }
    }

    return list.build();
}
 
源代码6 项目: buck   文件: PrebuiltPythonLibrary.java
@Override
public ImmutableList<? extends Step> getBuildSteps(
    BuildContext context, BuildableContext buildableContext) {
  Builder<Step> builder = ImmutableList.builder();
  buildableContext.recordArtifact(extractedOutput);

  builder.addAll(
      MakeCleanDirectoryStep.of(
          BuildCellRelativePath.fromCellRelativePath(
              context.getBuildCellRootPath(), getProjectFilesystem(), extractedOutput)));
  builder.add(
      new UnzipStep(
          getProjectFilesystem(),
          context.getSourcePathResolver().getAbsolutePath(binarySrc),
          extractedOutput,
          Optional.empty()));
  builder.add(new MovePythonWhlDataStep(getProjectFilesystem(), extractedOutput));
  return builder.build();
}
 
源代码7 项目: buck   文件: DotnetFramework.java
@VisibleForTesting
static DotnetFramework resolveFramework(FileSystem osFilesystem, FrameworkVersion version) {

  Builder<Path> builder = ImmutableList.builder();
  for (String dir : version.getDirectories()) {
    Path frameworkDir = osFilesystem.getPath(dir);
    if (!Files.exists(frameworkDir)) {
      throw new HumanReadableException(
          String.format("Required dir %s for %s was not found", dir, version));
    } else if (!Files.isDirectory(frameworkDir)) {
      throw new HumanReadableException(
          "Resolved framework directory is not a directory: %s", frameworkDir);
    } else {
      builder.add(frameworkDir);
    }
  }

  return new DotnetFramework(version, builder.build());
}
 
源代码8 项目: binnavi   文件: TypeListModel.java
/**
 * Creates a new types list model with the given filter. Takes ownership of the given list.
 *
 * @param types The set of types to be potentially included in this model.
 * @param filter A filter predicate to narrow the set of types that is included in this model.
 */
public TypeListModel(final List<BaseType> types, final Predicate<BaseType> filter) {
  final Builder<BaseType> builder = ImmutableList.builder();
  for (BaseType baseType : types) {
    if (filter.apply(baseType)) {
      builder.add(baseType);
    }
  }
  filteredTypes = builder.build();
}
 
源代码9 项目: pravega   文件: OrdererTest.java
private List<StubEventSegmentReader> createInputStreams(int num) {
    Builder<StubEventSegmentReader> builder = ImmutableList.builder();
    for (int i = 0; i < num; i++) {
        builder.add(new StubEventSegmentReader(i));
    }
    return builder.build();
}
 
源代码10 项目: ldp4j   文件: TripleResolver.java
private List<TripleResolution> createResolutions() throws ContentTransformationException {
	List<Triple> endpointTriples=triples(this.result.endpoint());
	List<Triple> alternativeTriples=triples(this.result.alternative());
	Builder<TripleResolution> builder = ImmutableList.builder();
	for(int i=0;i<endpointTriples.size();i++) {
		builder.add(resolveTriple(endpointTriples.get(i), alternativeTriples.get(i)));
	}
	return builder.build();
}
 
源代码11 项目: Strata   文件: CapletStrippingSetup.java
protected static Pair<List<ResolvedIborCapFloorLeg>, List<Double>> getCapsNormalVols(int strikeIndex) {
  ResolvedIborCapFloorLeg[] caps = CAPS_NORMAL[strikeIndex];
  double[] vols = CAP_NORMAL_VOLS[strikeIndex];
  Builder<ResolvedIborCapFloorLeg> capBuilder = ImmutableList.builder();
  Builder<Double> volBuilder = ImmutableList.builder();
  int nVols = vols.length;
  for (int i = 0; i < nVols; ++i) {
    if (Double.isFinite(vols[i])) {
      capBuilder.add(caps[i]);
      volBuilder.add(vols[i]);
    }
  }
  return Pair.of(capBuilder.build(), volBuilder.build());
}
 
源代码12 项目: ldp4j   文件: Constraints.java
private <T extends AbstractPropertyConstraint<?>> void filter(Builder<T> builder, Class<? extends T> clazz) {
	for(AbstractPropertyConstraint<?> c:this.constraints.values()) {
		if(clazz.isInstance(c)) {
			builder.add(clazz.cast(c));
		}
	}
}
 
源代码13 项目: android-arscblamer   文件: ArscDumper.java
private static List<String> getConfigurationHeaders() {
  Builder<String> builder = ImmutableList.builder();
  for (ResourceConfiguration.Type type : ResourceConfiguration.Type.values()) {
    builder.add(type.toString());
  }
  return builder.build();
}
 
源代码14 项目: android-arscblamer   文件: ArscDumper.java
private static List<String> getConfigurationParts(ResourceConfiguration configuration) {
  Map<ResourceConfiguration.Type, String> parts = configuration.toStringParts();
  Builder<String> builder = ImmutableList.builder();
  for (ResourceConfiguration.Type key : ResourceConfiguration.Type.values()) {
    builder.add(parts.containsKey(key) ? parts.get(key) : "");
  }
  return builder.build();
}
 
源代码15 项目: buck   文件: CacheCommandTest.java
private void testRunCommandAndFetchArtifactsSuccessfullyImpl(boolean fetchPrefix)
    throws Exception {
  final String ruleKeyHash = "b64009ae3762a42a1651c139ec452f0d18f48e21";

  ArtifactCache cache =
      new FakeArtifactCache(
          null, new RuleKey(ruleKeyHash), CacheResult.hit("http", ArtifactCacheMode.http));

  TestConsole console = new TestConsole();

  CommandRunnerParams commandRunnerParams =
      CommandRunnerParamsForTesting.builder().setConsole(console).setArtifactCache(cache).build();

  Builder<String> arguments = ImmutableList.builder();
  if (fetchPrefix) {
    arguments.add("fetch");
  }
  arguments.add(ruleKeyHash);

  CacheCommand cacheCommand = new CacheCommand();
  cacheCommand.setArguments(arguments.build());
  ExitCode exitCode = cacheCommand.run(commandRunnerParams);
  assertEquals(ExitCode.SUCCESS, exitCode);
  assertThat(
      console.getTextWrittenToStdErr(),
      containsString("Successfully downloaded artifact with id " + ruleKeyHash + " at "));

  if (!CacheCommand.MUTE_FETCH_SUBCOMMAND_WARNING) {
    assertThat(
        console.getTextWrittenToStdErr(),
        fetchPrefix ? not(containsString("deprecated")) : containsString("deprecated"));
  }
}
 
源代码16 项目: copybara   文件: SimpleGlob.java
@Override
public PathMatcher relativeTo(Path path) {
  Builder<PathMatcher> includeList = ImmutableList.builder();
  for (String path1 : include) {
    includeList.add(ReadablePathMatcher.relativeGlob(path, path1));
  }
  PathMatcher excludeMatcher = (exclude == null)
      ? FileUtil.anyPathMatcher(ImmutableList.of())
      : exclude.relativeTo(path);
  return new GlobPathMatcher(
      FileUtil.anyPathMatcher(includeList.build()),
      excludeMatcher);
}
 
源代码17 项目: buck   文件: ScalacToJarStepFactory.java
@Override
public void createCompileStep(
    BuildContext context,
    ProjectFilesystem projectFilesystem,
    BuildTarget invokingRule,
    CompilerParameters parameters,
    /* output params */
    Builder<Step> steps,
    BuildableContext buildableContext) {

  ImmutableSortedSet<Path> classpathEntries = parameters.getClasspathEntries();
  ImmutableSortedSet<Path> sourceFilePaths = parameters.getSourceFilePaths();
  Path outputDirectory = parameters.getOutputPaths().getClassesDir();

  if (sourceFilePaths.stream().anyMatch(SCALA_PATH_MATCHER::matches)) {
    steps.add(
        new ScalacStep(
            scalac,
            ImmutableList.<String>builder()
                .addAll(configCompilerFlags)
                .addAll(extraArguments)
                .addAll(
                    Iterables.transform(
                        compilerPlugins,
                        input ->
                            "-Xplugin:" + context.getSourcePathResolver().getRelativePath(input)))
                .build(),
            context.getSourcePathResolver(),
            outputDirectory,
            sourceFilePaths,
            ImmutableSortedSet.<Path>naturalOrder()
                .addAll(
                    Optional.ofNullable(extraClassPath.getExtraClasspath())
                        .orElse(ImmutableList.of()))
                .addAll(classpathEntries)
                .build(),
            projectFilesystem));
  }

  ImmutableSortedSet<Path> javaSourceFiles =
      ImmutableSortedSet.copyOf(
          sourceFilePaths.stream()
              .filter(JAVA_PATH_MATCHER::matches)
              .collect(Collectors.toSet()));

  // Don't invoke javac if we don't have any java files.
  if (!javaSourceFiles.isEmpty()) {
    CompilerParameters javacParameters =
        CompilerParameters.builder()
            .from(parameters)
            .setClasspathEntries(
                ImmutableSortedSet.<Path>naturalOrder()
                    .add(outputDirectory)
                    .addAll(
                        Optional.ofNullable(extraClassPath.getExtraClasspath())
                            .orElse(ImmutableList.of()))
                    .addAll(classpathEntries)
                    .build())
            .setSourceFilePaths(javaSourceFiles)
            .build();
    new JavacToJarStepFactory(javac, javacOptions, extraClassPath)
        .createCompileStep(
            context, projectFilesystem, invokingRule, javacParameters, steps, buildableContext);
  }
}
 
源代码18 项目: buck   文件: BuckGlobalStateLifecycleManagerTest.java
@Test
public void testAndroidSdkChangesParserInvalidated() throws IOException {
  // Disable the test on Windows for now since it's failing to find python.
  assumeThat(Platform.detect(), not(Platform.WINDOWS));

  BuckConfig buckConfig = FakeBuckConfig.builder().build();
  Builder<Entry<ProcessExecutorParams, FakeProcess>> fakeProcessesBuilder =
      ImmutableList.builder();
  ProcessExecutorParams processExecutorParams =
      ProcessExecutorParams.builder()
          .setCommand(ImmutableList.of("xcode-select", "--print-path"))
          .build();
  // First KnownBuildRuleTypes resolution.
  fakeProcessesBuilder.add(
      new SimpleImmutableEntry<>(processExecutorParams, new FakeProcess(0, "/dev/null", "")));
  // Check SDK.
  fakeProcessesBuilder.add(
      new SimpleImmutableEntry<>(processExecutorParams, new FakeProcess(0, "/dev/null", "")));
  // Check SDK.
  fakeProcessesBuilder.add(
      new SimpleImmutableEntry<>(processExecutorParams, new FakeProcess(0, "/dev/null", "")));
  // KnownBuildRuleTypes resolution.
  fakeProcessesBuilder.add(
      new SimpleImmutableEntry<>(processExecutorParams, new FakeProcess(0, "/dev/null", "")));
  // Check SDK.
  fakeProcessesBuilder.add(
      new SimpleImmutableEntry<>(processExecutorParams, new FakeProcess(0, "/dev/null", "")));

  Object buckGlobalState1 =
      buckGlobalStateLifecycleManager
          .getBuckGlobalState(
              new TestCellBuilder().setBuckConfig(buckConfig).setFilesystem(filesystem).build(),
              knownRuleTypesProvider,
              watchman,
              Console.createNullConsole(),
              clock,
              unconfiguredBuildTargetFactory,
              targetConfigurationSerializer)
          .getFirst();
  Object buckGlobalState2 =
      buckGlobalStateLifecycleManager
          .getBuckGlobalState(
              new TestCellBuilder().setBuckConfig(buckConfig).setFilesystem(filesystem).build(),
              knownRuleTypesProvider,
              watchman,
              Console.createNullConsole(),
              clock,
              unconfiguredBuildTargetFactory,
              targetConfigurationSerializer)
          .getFirst();
  assertEquals(
      "Android SDK should be the same initial location", buckGlobalState1, buckGlobalState2);

  Path androidSdkPath = tmp.newFolder("android-sdk").toAbsolutePath();

  Cells cell = createCellWithAndroidSdk(androidSdkPath);

  Object buckGlobalState3 =
      buckGlobalStateLifecycleManager
          .getBuckGlobalState(
              cell,
              knownRuleTypesProvider,
              watchman,
              Console.createNullConsole(),
              clock,
              unconfiguredBuildTargetFactory,
              targetConfigurationSerializer)
          .getFirst();

  assertEquals("Daemon should not be re-created", buckGlobalState2, buckGlobalState3);
  Object buckGlobalState4 =
      buckGlobalStateLifecycleManager
          .getBuckGlobalState(
              cell,
              knownRuleTypesProvider,
              watchman,
              Console.createNullConsole(),
              clock,
              unconfiguredBuildTargetFactory,
              targetConfigurationSerializer)
          .getFirst();

  assertEquals(
      "Android SDK should be the same other location", buckGlobalState3, buckGlobalState4);
}
 
源代码19 项目: gss.gwt   文件: ImageSpriteCreator.java
private void createSprite(CssDeclarationNode declaration) {
  List<CssValueNode> valuesNodes = declaration.getPropertyValue().getChildren();

  if (valuesNodes.size() != 1) {
    errorManager.report(new GssError(SPRITE_PROPERTY_NAME + " must have exactly one value",
        declaration.getSourceCodeLocation()));
  }

  String imageResource = valuesNodes.get(0).getValue();

  JMethod imageMethod;
  try {
    imageMethod = ResourceGeneratorUtil.getMethodByPath(context.getClientBundleType(),
        getPathElement(imageResource), imageResourceType);
  } catch (NotFoundException e) {
    errorManager.report(new GssError("Unable to find ImageResource method "
        + imageResource + " in " + context.getClientBundleType().getQualifiedSourceName() + " : "
        + e.getMessage(), declaration.getSourceCodeLocation()));
    return;
  }

  ImageOptions options = imageMethod.getAnnotation(ImageOptions.class);
  RepeatStyle repeatStyle = options != null ? options.repeatStyle() : RepeatStyle.None;

  Builder<CssDeclarationNode> listBuilder = ImmutableList.builder();
  SourceCodeLocation sourceCodeLocation = declaration.getSourceCodeLocation();

  String repeatText;
  switch (repeatStyle) {
    case None:
      repeatText = " no-repeat";
      listBuilder.add(buildHeightDeclaration(imageResource, sourceCodeLocation));
      listBuilder.add(buildWidthDeclaration(imageResource, sourceCodeLocation));
      break;
    case Horizontal:
      repeatText = " repeat-x";
      listBuilder.add(buildHeightDeclaration(imageResource, sourceCodeLocation));
      break;
    case Vertical:
      repeatText = " repeat-y";
      listBuilder.add(buildWidthDeclaration(imageResource, sourceCodeLocation));
      break;
    case Both:
      repeatText = " repeat";
      break;
    default:
      errorManager.report(new GssError("Unknown repeatStyle " + repeatStyle,
          sourceCodeLocation));
      return;
  }

  listBuilder.add(buildOverflowDeclaration(sourceCodeLocation));
  listBuilder.add(buildBackgroundDeclaration(imageResource, repeatText, sourceCodeLocation));

  visitController.replaceCurrentBlockChildWith(listBuilder.build(), false);
}
 
源代码20 项目: buck   文件: CxxThinLTOIndex.java
@Override
public ImmutableList<Step> getBuildSteps(
    BuildContext context,
    ProjectFilesystem filesystem,
    OutputPathResolver outputPathResolver,
    BuildCellRelativePathFactory buildCellPathFactory) {
  Path scratchDir = filesystem.resolve(outputPathResolver.getTempPath());
  Path argFilePath = scratchDir.resolve("linker.argsfile");
  Path fileListPath = scratchDir.resolve("filelist.txt");

  Path outputPath = outputPathResolver.resolvePath(output);
  Path linkOutput = outputPath.getParent().resolve("thinlto.objects");

  Builder<Step> stepsBuilder =
      new Builder<Step>()
          .add(MkdirStep.of(buildCellPathFactory.from(outputPath.getParent())))
          .add(MkdirStep.of(buildCellPathFactory.from(outputPath)))
          .addAll(
              CxxPrepareForLinkStep.create(
                  argFilePath,
                  fileListPath,
                  linker.fileList(fileListPath),
                  linkOutput,
                  args,
                  linker,
                  targetName.getCell(),
                  filesystem.getRootPath().getPath(),
                  context.getSourcePathResolver()))
          .add(
              new CxxLinkStep(
                  filesystem.getRootPath(),
                  linker.getEnvironment(context.getSourcePathResolver()),
                  linker.getCommandPrefix(context.getSourcePathResolver()),
                  argFilePath,
                  scratchDir));

  if (linkerMapPath.isPresent()) {
    // In some case (when there are no `dll_export`s eg) an import library is not produced by
    // link.exe. An empty file is produced in this case (since an import library was already
    // promised to `buildableContext`).
    stepsBuilder.add(
        new TouchStep(filesystem, outputPathResolver.resolvePath(linkerMapPath.get())));
  }
  return stepsBuilder.build();
}