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

The following examples show how to use com.google.common.collect.ImmutableList.Builder#add() . 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: IrisRtspSdp.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
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());
      }
   }
}
 
Example 2
Source File: DotnetFramework.java    From buck with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example 3
Source File: NodeYarnProcessBuilder.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * 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);
}
 
Example 4
Source File: PrebuiltPythonLibrary.java    From buck with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example 5
Source File: TypeHandle.java    From Mixin with MIT License 6 votes vote down vote up
@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();
}
 
Example 6
Source File: AbstractLithiumDataInput.java    From yangtools with Eclipse Public License 1.0 6 votes vote down vote up
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));
    }
}
 
Example 7
Source File: SuperConsoleEventBusListenerTest.java    From buck with Apache License 2.0 6 votes vote down vote up
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(""));
}
 
Example 8
Source File: ArscDumper.java    From android-arscblamer with Apache License 2.0 5 votes vote down vote up
private static List<String> getConfigurationHeaders() {
  Builder<String> builder = ImmutableList.builder();
  for (ResourceConfiguration.Type type : ResourceConfiguration.Type.values()) {
    builder.add(type.toString());
  }
  return builder.build();
}
 
Example 9
Source File: SimpleGlob.java    From copybara with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 10
Source File: CacheCommandTest.java    From buck with Apache License 2.0 5 votes vote down vote up
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"));
  }
}
 
Example 11
Source File: ArscDumper.java    From android-arscblamer with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example 12
Source File: TypeListModel.java    From binnavi with Apache License 2.0 5 votes vote down vote up
/**
 * 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();
}
 
Example 13
Source File: Constraints.java    From ldp4j with Apache License 2.0 5 votes vote down vote up
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));
		}
	}
}
 
Example 14
Source File: CapletStrippingSetup.java    From Strata with Apache License 2.0 5 votes vote down vote up
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());
}
 
Example 15
Source File: TripleResolver.java    From ldp4j with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example 16
Source File: OrdererTest.java    From pravega with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example 17
Source File: ImageSpriteCreator.java    From gss.gwt with Apache License 2.0 4 votes vote down vote up
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);
}
 
Example 18
Source File: CxxThinLTOIndex.java    From buck with Apache License 2.0 4 votes vote down vote up
@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();
}
 
Example 19
Source File: BuckGlobalStateLifecycleManagerTest.java    From buck with Apache License 2.0 4 votes vote down vote up
@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);
}
 
Example 20
Source File: ScalacToJarStepFactory.java    From buck with Apache License 2.0 4 votes vote down vote up
@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);
  }
}