private ImmutableSet<String> prepareDirectory(
        String dirname, Pattern filePattern, ImmutableSet<String> requiredHashes) throws Exception {
      try (TraceEventLogger ignored = TraceEventLogger.start(eventBus, "prepare_" + dirname)) {
        String dirPath = dataRoot.resolve(dirname).toString();
        mkDirP(dirPath);

        String output = AdbHelper.executeCommandWithErrorChecking(device, "ls " + dirPath);

        ImmutableSet.Builder<String> foundHashes = ImmutableSet.builder();
        ImmutableSet.Builder<String> filesToDelete = ImmutableSet.builder();

        processLsOutput(output, filePattern, requiredHashes, foundHashes, filesToDelete);

        String commandPrefix = "cd " + dirPath + " && rm ";
        // Add a fudge factor for separators and error checking.
        final int overhead = commandPrefix.length() + 100;
        for (List<String> rmArgs :
            chunkArgs(filesToDelete.build(), MAX_ADB_COMMAND_SIZE - overhead)) {
          String command = commandPrefix + Joiner.on(' ').join(rmArgs);
          LOG.debug("Executing %s", command);
          AdbHelper.executeCommandWithErrorChecking(device, command);
        }

        return foundHashes.build();
      }
    }
Esempio n. 2
0
  /**
   * Creates a new environment.
   *
   * @param configuration the service's {@link Configuration}
   * @param service the service
   */
  public Environment(Configuration configuration, AbstractService<?> service) {
    this.service = service;
    this.config =
        new DropwizardResourceConfig() {
          @Override
          public void validate() {
            super.validate();
            logResources();
            logProviders();
            logHealthChecks();
            logManagedObjects();
            logEndpoints();
          }
        };
    this.healthChecks = ImmutableSet.builder();
    this.servlets = ImmutableMap.builder();
    this.filters = ImmutableMultimap.builder();
    this.servletListeners = ImmutableSet.builder();
    this.tasks = ImmutableSet.builder();
    this.lifeCycle = new AggregateLifeCycle();

    final HttpServlet jerseyContainer = service.getJerseyContainer(config);
    if (jerseyContainer != null) {
      addServlet(jerseyContainer, configuration.getHttpConfiguration().getRootPath())
          .setInitOrder(Integer.MAX_VALUE);
    }
    addTask(new GarbageCollectionTask());
  }
  @Test
  public void upperBoundGenericTypesCauseValuesToBeSetToTheUpperBound()
      throws ConstructorArgMarshalException, NoSuchBuildTargetException {

    class Dto {
      public List<? extends SourcePath> yup;
    }

    ProjectFilesystem projectFilesystem = new FakeProjectFilesystem();
    SourcePathResolver pathResolver = new SourcePathResolver(new BuildRuleResolver());
    BuildRule rule =
        new FakeBuildRule(BuildTargetFactory.newInstance("//will:happen"), pathResolver);
    ruleResolver.addToIndex(rule);
    Dto dto = new Dto();
    marshaller.populate(
        createCellRoots(filesystem),
        filesystem,
        buildRuleFactoryParams(),
        dto,
        ImmutableSet.<BuildTarget>builder(),
        ImmutableSet.<BuildTargetPattern>builder(),
        ImmutableMap.<String, Object>of(
            "yup", ImmutableList.of(rule.getBuildTarget().getFullyQualifiedName())));

    BuildTargetSourcePath path = new BuildTargetSourcePath(rule.getBuildTarget());
    assertEquals(ImmutableList.of(path), dto.yup);
  }
Esempio n. 4
0
  /**
   * Returns the ShellCommand object that is supposed to generate a code coverage report from data
   * obtained during the test run. This method will also generate a set of source paths to the class
   * files tested during the test run.
   */
  private static Step getReportCommand(
      ImmutableSet<JavaLibrary> rulesUnderTest,
      Optional<DefaultJavaPackageFinder> defaultJavaPackageFinderOptional,
      ProjectFilesystem filesystem,
      Path outputDirectory,
      CoverageReportFormat format) {
    ImmutableSet.Builder<String> srcDirectories = ImmutableSet.builder();
    ImmutableSet.Builder<Path> pathsToClasses = ImmutableSet.builder();

    // Add all source directories of java libraries that we are testing to -sourcepath.
    for (JavaLibrary rule : rulesUnderTest) {
      ImmutableSet<String> sourceFolderPath =
          getPathToSourceFolders(rule, defaultJavaPackageFinderOptional, filesystem);
      if (!sourceFolderPath.isEmpty()) {
        srcDirectories.addAll(sourceFolderPath);
      }
      Path pathToOutput = rule.getPathToOutput();
      if (pathToOutput == null) {
        continue;
      }
      pathsToClasses.add(pathToOutput);
    }

    return new GenerateCodeCoverageReportStep(
        srcDirectories.build(), pathsToClasses.build(), outputDirectory, format);
  }
  @Test
  public void fieldsWithIsDepEqualsFalseHintAreNotTreatedAsDeps()
      throws ConstructorArgMarshalException, NoSuchBuildTargetException {

    class Dto {
      @Hint(isDep = false)
      public Optional<Set<BuildTarget>> deps;
    }

    final String dep = "//should/be:ignored";

    Dto dto = new Dto();
    Map<String, Object> args = Maps.newHashMap();
    args.put("deps", ImmutableList.of(dep));

    ImmutableSet.Builder<BuildTarget> declaredDeps = ImmutableSet.builder();

    marshaller.populate(
        createCellRoots(filesystem),
        filesystem,
        buildRuleFactoryParams(),
        dto,
        declaredDeps,
        ImmutableSet.<BuildTargetPattern>builder(),
        args);

    assertEquals(ImmutableSet.of(), declaredDeps.build());
  }
  public void shouldSetBuildTargetParameters()
      throws ConstructorArgMarshalException, NoSuchBuildTargetException {
    class Dto {
      public BuildTarget single;
      public BuildTarget sameBuildFileTarget;
      public List<BuildTarget> targets;
    }
    Dto dto = new Dto();

    marshaller.populate(
        createCellRoots(filesystem),
        filesystem,
        buildRuleFactoryParams(),
        dto,
        ImmutableSet.<BuildTarget>builder(),
        ImmutableSet.<BuildTargetPattern>builder(),
        ImmutableMap.<String, Object>of(
            "single", "//com/example:cheese",
            "sameBuildFileTarget", ":cake",
            "targets", ImmutableList.of(":cake", "//com/example:cheese")));

    BuildTarget cheese = BuildTargetFactory.newInstance("//com/example:cheese");
    BuildTarget cake = BuildTargetFactory.newInstance("//example/path:cake");

    assertEquals(cheese, dto.single);
    assertEquals(cake, dto.sameBuildFileTarget);
    assertEquals(ImmutableList.of(cake, cheese), dto.targets);
  }
  @Test
  public void onlyFieldNamedDepsAreConsideredDeclaredDeps()
      throws ConstructorArgMarshalException, NoSuchBuildTargetException {

    class Dto {
      public Optional<Set<BuildTarget>> deps;
      public Optional<Set<BuildTarget>> notdeps;
    }

    final String dep = "//is/a/declared:dep";
    final String notDep = "//is/not/a/declared:dep";

    BuildTarget declaredDep = BuildTargetFactory.newInstance(dep);

    Dto dto = new Dto();
    Map<String, Object> args = Maps.newHashMap();
    args.put("deps", ImmutableList.of(dep));
    args.put("notdeps", ImmutableList.of(notDep));

    ImmutableSet.Builder<BuildTarget> declaredDeps = ImmutableSet.builder();

    marshaller.populate(
        createCellRoots(filesystem),
        filesystem,
        buildRuleFactoryParams(),
        dto,
        declaredDeps,
        ImmutableSet.<BuildTargetPattern>builder(),
        args);

    assertEquals(ImmutableSet.of(declaredDep), declaredDeps.build());
  }
  @Test
  public void shouldPopulateSourcePaths()
      throws ConstructorArgMarshalException, NoSuchBuildTargetException {
    class Dto {
      public SourcePath filePath;
      public SourcePath targetPath;
    }

    ProjectFilesystem projectFilesystem = new FakeProjectFilesystem();
    BuildTarget target = BuildTargetFactory.newInstance("//example/path:peas");
    FakeBuildRule rule = new FakeBuildRule(target, new SourcePathResolver(new BuildRuleResolver()));
    ruleResolver.addToIndex(rule);
    Dto dto = new Dto();
    marshaller.populate(
        createCellRoots(filesystem),
        filesystem,
        buildRuleFactoryParams(),
        dto,
        ImmutableSet.<BuildTarget>builder(),
        ImmutableSet.<BuildTargetPattern>builder(),
        ImmutableMap.<String, Object>of(
            "filePath", "cheese.txt",
            "targetPath", ":peas"));

    assertEquals(
        new PathSourcePath(projectFilesystem, Paths.get("example/path/cheese.txt")), dto.filePath);
    assertEquals(new BuildTargetSourcePath(rule.getBuildTarget()), dto.targetPath);
  }
    @Override
    public PlanNode visitIndexJoin(IndexJoinNode node, RewriteContext<Set<Symbol>> context) {
      ImmutableSet.Builder<Symbol> probeInputsBuilder = ImmutableSet.builder();
      probeInputsBuilder
          .addAll(context.get())
          .addAll(Iterables.transform(node.getCriteria(), IndexJoinNode.EquiJoinClause::getProbe));
      if (node.getProbeHashSymbol().isPresent()) {
        probeInputsBuilder.add(node.getProbeHashSymbol().get());
      }
      Set<Symbol> probeInputs = probeInputsBuilder.build();

      ImmutableSet.Builder<Symbol> indexInputBuilder = ImmutableSet.builder();
      indexInputBuilder
          .addAll(context.get())
          .addAll(Iterables.transform(node.getCriteria(), IndexJoinNode.EquiJoinClause::getIndex));
      if (node.getIndexHashSymbol().isPresent()) {
        indexInputBuilder.add(node.getIndexHashSymbol().get());
      }
      Set<Symbol> indexInputs = indexInputBuilder.build();

      PlanNode probeSource = context.rewrite(node.getProbeSource(), probeInputs);
      PlanNode indexSource = context.rewrite(node.getIndexSource(), indexInputs);

      return new IndexJoinNode(
          node.getId(),
          node.getType(),
          probeSource,
          indexSource,
          node.getCriteria(),
          node.getProbeHashSymbol(),
          node.getIndexHashSymbol());
    }
Esempio n. 10
0
    @Override
    public PlanNode visitSemiJoin(SemiJoinNode node, RewriteContext<Set<Symbol>> context) {
      ImmutableSet.Builder<Symbol> sourceInputsBuilder = ImmutableSet.builder();
      sourceInputsBuilder.addAll(context.get()).add(node.getSourceJoinSymbol());
      if (node.getSourceHashSymbol().isPresent()) {
        sourceInputsBuilder.add(node.getSourceHashSymbol().get());
      }
      Set<Symbol> sourceInputs = sourceInputsBuilder.build();

      ImmutableSet.Builder<Symbol> filteringSourceInputBuilder = ImmutableSet.builder();
      filteringSourceInputBuilder.add(node.getFilteringSourceJoinSymbol());
      if (node.getFilteringSourceHashSymbol().isPresent()) {
        filteringSourceInputBuilder.add(node.getFilteringSourceHashSymbol().get());
      }
      Set<Symbol> filteringSourceInputs = filteringSourceInputBuilder.build();

      PlanNode source = context.rewrite(node.getSource(), sourceInputs);
      PlanNode filteringSource = context.rewrite(node.getFilteringSource(), filteringSourceInputs);

      return new SemiJoinNode(
          node.getId(),
          source,
          filteringSource,
          node.getSourceJoinSymbol(),
          node.getFilteringSourceJoinSymbol(),
          node.getSemiJoinOutput(),
          node.getSourceHashSymbol(),
          node.getFilteringSourceHashSymbol());
    }
Esempio n. 11
0
    @Override
    public PlanNode visitJoin(JoinNode node, RewriteContext<Set<Symbol>> context) {
      ImmutableSet.Builder<Symbol> leftInputsBuilder = ImmutableSet.builder();
      leftInputsBuilder
          .addAll(context.get())
          .addAll(Iterables.transform(node.getCriteria(), JoinNode.EquiJoinClause::getLeft));
      if (node.getLeftHashSymbol().isPresent()) {
        leftInputsBuilder.add(node.getLeftHashSymbol().get());
      }
      Set<Symbol> leftInputs = leftInputsBuilder.build();

      ImmutableSet.Builder<Symbol> rightInputsBuilder = ImmutableSet.builder();
      rightInputsBuilder
          .addAll(context.get())
          .addAll(Iterables.transform(node.getCriteria(), JoinNode.EquiJoinClause::getRight));
      if (node.getRightHashSymbol().isPresent()) {
        rightInputsBuilder.add(node.getRightHashSymbol().get());
      }

      Set<Symbol> rightInputs = rightInputsBuilder.build();

      PlanNode left = context.rewrite(node.getLeft(), leftInputs);
      PlanNode right = context.rewrite(node.getRight(), rightInputs);

      return new JoinNode(
          node.getId(),
          node.getType(),
          left,
          right,
          node.getCriteria(),
          node.getLeftHashSymbol(),
          node.getRightHashSymbol());
    }
 static {
   ImmutableSet.Builder<Double> integralBuilder = ImmutableSet.builder();
   ImmutableSet.Builder<Double> fractionalBuilder = ImmutableSet.builder();
   integralBuilder.addAll(Doubles.asList(0.0, -0.0, Double.MAX_VALUE, -Double.MAX_VALUE));
   // Add small multiples of MIN_VALUE and MIN_NORMAL
   for (int scale = 1; scale <= 4; scale++) {
     for (double d : Doubles.asList(Double.MIN_VALUE, Double.MIN_NORMAL)) {
       fractionalBuilder.add(d * scale).add(-d * scale);
     }
   }
   for (double d :
       Doubles.asList(
           0,
           1,
           2,
           7,
           51,
           102,
           Math.scalb(1.0, 53),
           Integer.MIN_VALUE,
           Integer.MAX_VALUE,
           Long.MIN_VALUE,
           Long.MAX_VALUE)) {
     for (double delta : Doubles.asList(0.0, 1.0, 2.0)) {
       integralBuilder.addAll(Doubles.asList(d + delta, d - delta, -d - delta, -d + delta));
     }
     for (double delta : Doubles.asList(0.01, 0.1, 0.25, 0.499, 0.5, 0.501, 0.7, 0.8)) {
       double x = d + delta;
       if (x != Math.round(x)) {
         fractionalBuilder.add(x);
       }
     }
   }
   INTEGRAL_DOUBLE_CANDIDATES = integralBuilder.build();
   fractionalBuilder.add(1.414).add(1.415).add(Math.sqrt(2));
   fractionalBuilder.add(5.656).add(5.657).add(4 * Math.sqrt(2));
   for (double d : INTEGRAL_DOUBLE_CANDIDATES) {
     double x = 1 / d;
     if (x != Math.rint(x)) {
       fractionalBuilder.add(x);
     }
   }
   FRACTIONAL_DOUBLE_CANDIDATES = fractionalBuilder.build();
   FINITE_DOUBLE_CANDIDATES =
       Iterables.concat(FRACTIONAL_DOUBLE_CANDIDATES, INTEGRAL_DOUBLE_CANDIDATES);
   POSITIVE_FINITE_DOUBLE_CANDIDATES =
       Iterables.filter(
           FINITE_DOUBLE_CANDIDATES,
           new Predicate<Double>() {
             @Override
             public boolean apply(Double input) {
               return input.doubleValue() > 0.0;
             }
           });
   DOUBLE_CANDIDATES_EXCEPT_NAN = Iterables.concat(FINITE_DOUBLE_CANDIDATES, INFINITIES);
   ALL_DOUBLE_CANDIDATES = Iterables.concat(DOUBLE_CANDIDATES_EXCEPT_NAN, asList(Double.NaN));
 }
Esempio n. 13
0
 static Set<UUID> extractIndexes(List<ShardIndexInfo> inputShards, int... indexes) {
   ImmutableSet.Builder<UUID> builder = ImmutableSet.builder();
   for (int index : indexes) {
     builder.add(inputShards.get(index).getShardUuid());
   }
   return builder.build();
 }
 /**
  * Returns the configurable attribute conditions necessary to evaluate the given configured
  * target, or null if not all dependencies have yet been SkyFrame-evaluated.
  */
 @Nullable
 private Set<ConfigMatchingProvider> getConfigurableAttributeConditions(
     TargetAndConfiguration ctg, Environment env) {
   if (!(ctg.getTarget() instanceof Rule)) {
     return ImmutableSet.of();
   }
   Rule rule = (Rule) ctg.getTarget();
   RawAttributeMapper mapper = RawAttributeMapper.of(rule);
   Set<SkyKey> depKeys = new LinkedHashSet<>();
   for (Attribute attribute : rule.getAttributes()) {
     for (Label label : mapper.getConfigurabilityKeys(attribute.getName(), attribute.getType())) {
       if (!BuildType.Selector.isReservedLabel(label)) {
         depKeys.add(ConfiguredTargetValue.key(label, ctg.getConfiguration()));
       }
     }
   }
   Map<SkyKey, SkyValue> cts = env.getValues(depKeys);
   if (env.valuesMissing()) {
     return null;
   }
   ImmutableSet.Builder<ConfigMatchingProvider> conditions = ImmutableSet.builder();
   for (SkyValue ctValue : cts.values()) {
     ConfiguredTarget ct = ((ConfiguredTargetValue) ctValue).getConfiguredTarget();
     conditions.add(Preconditions.checkNotNull(ct.getProvider(ConfigMatchingProvider.class)));
   }
   return conditions.build();
 }
 static {
   ImmutableSet.Builder<String> builder = ImmutableSet.builder();
   for (TrackerFilterEnum eventFilter : TrackerFilterEnum.values()) {
     builder.add(eventFilter.getValue());
   }
   valuesSet = builder.build();
 }
Esempio n. 16
0
 private void logManagedObjects() {
   final ImmutableSet.Builder<String> builder = ImmutableSet.builder();
   for (Object bean : lifeCycle.getBeans()) {
     builder.add(bean.getClass().getCanonicalName());
   }
   LOG.debug("managed objects = {}", builder.build());
 }
Esempio n. 17
0
 private void logHealthChecks() {
   final ImmutableSet.Builder<String> builder = ImmutableSet.builder();
   for (HealthCheck healthCheck : healthChecks.build()) {
     builder.add(healthCheck.getClass().getCanonicalName());
   }
   LOG.debug("health checks = {}", builder.build());
 }
  public ImmutableSet<CxxInferCapture> createInferCaptureBuildRules(
      ImmutableMap<String, CxxSource> sources,
      CxxInferTools inferTools,
      CxxInferSourceFilter sourceFilter) {

    ImmutableSet.Builder<CxxInferCapture> objects = ImmutableSet.builder();

    for (Map.Entry<String, CxxSource> entry : sources.entrySet()) {
      String name = entry.getKey();
      CxxSource source = entry.getValue();

      Preconditions.checkState(
          CxxSourceTypes.isPreprocessableType(source.getType()),
          "Only preprocessable source types are currently supported");

      if (sourceFilter.isBlacklisted(source)) {
        continue;
      }

      CxxInferCapture rule = requireInferCaptureBuildRule(name, source, inferTools);
      objects.add(rule);
    }

    return objects.build();
  }
  /**
   * Helper to add srcs and deps Soy files to a SoyFileSet builder. Also does sanity checks.
   *
   * @param sfsBuilder The SoyFileSet builder to add to.
   * @param inputPrefix The input path prefix to prepend to all the file paths.
   * @param srcs The srcs from the --srcs flag. Exactly one of 'srcs' and 'args' must be nonempty.
   * @param args The old-style srcs from the command line (that's how they were specified before we
   *     added the --srcs flag). Exactly one of 'srcs' and 'args' must be nonempty.
   * @param deps The deps from the --deps flag, or empty list if not applicable.
   * @param exitWithErrorFn A function that exits with an error message followed by a usage message.
   */
  static void addSoyFilesToBuilder(
      Builder sfsBuilder,
      String inputPrefix,
      Collection<String> srcs,
      Collection<String> args,
      Collection<String> deps,
      Collection<String> indirectDeps,
      Function<String, Void> exitWithErrorFn) {
    if (srcs.isEmpty() && args.isEmpty()) {
      exitWithErrorFn.apply("Must provide list of source Soy files (--srcs).");
    }
    if (!srcs.isEmpty() && !args.isEmpty()) {
      exitWithErrorFn.apply(
          "Found source Soy files from --srcs and from args (please use --srcs only).");
    }

    // Create Set versions of each of the arguments, and de-dupe. If something is included as
    // multiple file kinds, we'll keep the strongest one; a file in both srcs and deps will be a
    // src, and one in both deps and indirect_deps will be a dep.
    // TODO(gboyer): Maybe stop supporting old style (srcs from command line args) at some point.
    Set<String> srcsSet = ImmutableSet.<String>builder().addAll(srcs).addAll(args).build();
    Set<String> depsSet = Sets.difference(ImmutableSet.copyOf(deps), srcsSet);
    Set<String> indirectDepsSet =
        Sets.difference(ImmutableSet.copyOf(indirectDeps), Sets.union(srcsSet, depsSet));

    for (String src : srcsSet) {
      sfsBuilder.addWithKind(new File(inputPrefix + src), SoyFileKind.SRC);
    }
    for (String dep : depsSet) {
      sfsBuilder.addWithKind(new File(inputPrefix + dep), SoyFileKind.DEP);
    }
    for (String dep : indirectDepsSet) {
      sfsBuilder.addWithKind(new File(inputPrefix + dep), SoyFileKind.INDIRECT_DEP);
    }
  }
  @VisibleForTesting
  public Set<String> getSecurityGroupsForTagAndOptions(
      String region, @Nullable String group, TemplateOptions options) {
    Builder<String> groups = ImmutableSet.builder();

    if (group != null) {
      String markerGroup = namingConvention.create().sharedNameForGroup(group);

      groups.add(markerGroup);

      RegionNameAndIngressRules regionNameAndIngressRulesForMarkerGroup;

      if (userSpecifiedTheirOwnGroups(options)) {
        regionNameAndIngressRulesForMarkerGroup =
            new RegionNameAndIngressRules(region, markerGroup, new int[] {}, false);
        groups.addAll(EC2TemplateOptions.class.cast(options).getGroups());
      } else {
        regionNameAndIngressRulesForMarkerGroup =
            new RegionNameAndIngressRules(region, markerGroup, options.getInboundPorts(), true);
      }
      // this will create if not yet exists.
      securityGroupMap.getUnchecked(regionNameAndIngressRulesForMarkerGroup);
    }
    return groups.build();
  }
  @Test
  public void testGetJobUpdateDiffWithUpdateRemove() throws Exception {
    TaskConfig task1 = defaultTask(false).setNumCpus(1.0);
    TaskConfig task2 = defaultTask(false).setNumCpus(2.0);
    TaskConfig task3 = defaultTask(false).setNumCpus(3.0);

    ImmutableSet.Builder<IScheduledTask> tasks = ImmutableSet.builder();
    makeTasks(0, 10, task1, tasks);
    makeTasks(10, 20, task2, tasks);
    makeTasks(20, 30, task3, tasks);

    expect(storageUtil.jobStore.fetchJob(JOB_KEY)).andReturn(Optional.absent());
    storageUtil.expectTaskFetch(Query.jobScoped(JOB_KEY).active(), tasks.build());

    control.replay();

    JobUpdateRequest request =
        new JobUpdateRequest()
            .setTaskConfig(defaultTask(false).setNumCpus(6.0))
            .setInstanceCount(20)
            .setSettings(new JobUpdateSettings());

    GetJobUpdateDiffResult expected =
        new GetJobUpdateDiffResult()
            .setRemove(ImmutableSet.of(group(task3, new Range(20, 29))))
            .setUpdate(
                ImmutableSet.of(group(task1, new Range(0, 9)), group(task2, new Range(10, 19))))
            .setAdd(ImmutableSet.of())
            .setUnchanged(ImmutableSet.of());

    Response response = assertOkResponse(thrift.getJobUpdateDiff(request));
    assertEquals(expected, response.getResult().getGetJobUpdateDiffResult());
  }
 @Override
 public Set<Integer> getPortsUsed() {
   return ImmutableSet.<Integer>builder()
       .addAll(super.getPortsUsed())
       .addAll(getPortMap().values())
       .build();
 }
Esempio n. 23
0
 /**
  * Returns the context for a LIPO compile action. This uses the include dirs and defines of the
  * library, but the declared inclusion dirs/srcs from both the library and the owner binary.
  *
  * <p>TODO(bazel-team): this might make every LIPO target have an unnecessary large set of
  * inclusion dirs/srcs. The correct behavior would be to merge only the contexts of actual
  * referred targets (as listed in .imports file).
  *
  * <p>Undeclared inclusion checking ({@link #getDeclaredIncludeDirs()}, {@link
  * #getDeclaredIncludeWarnDirs()}, and {@link #getDeclaredIncludeSrcs()}) needs to use the union
  * of the contexts of the involved source files.
  *
  * <p>For include and define command line flags ({@link #getIncludeDirs()} {@link
  * #getQuoteIncludeDirs()}, {@link #getSystemIncludeDirs()}, and {@link #getDefines()}) LIPO
  * compilations use the same values as non-LIPO compilation.
  *
  * <p>Include scanning is not handled by this method. See {@code
  * IncludeScannable#getAuxiliaryScannables()} instead.
  *
  * @param ownerContext the compilation context of the owner binary
  * @param libContext the compilation context of the library
  */
 public static CppCompilationContext mergeForLipo(
     CppCompilationContext ownerContext, CppCompilationContext libContext) {
   ImmutableSet.Builder<Artifact> prerequisites = ImmutableSet.builder();
   prerequisites.addAll(ownerContext.compilationPrerequisites);
   prerequisites.addAll(libContext.compilationPrerequisites);
   ModuleInfo.Builder moduleInfo = new ModuleInfo.Builder();
   moduleInfo.merge(ownerContext.moduleInfo);
   moduleInfo.merge(libContext.moduleInfo);
   ModuleInfo.Builder picModuleInfo = new ModuleInfo.Builder();
   picModuleInfo.merge(ownerContext.picModuleInfo);
   picModuleInfo.merge(libContext.picModuleInfo);
   return new CppCompilationContext(
       libContext.commandLineContext,
       prerequisites.build(),
       mergeSets(ownerContext.declaredIncludeDirs, libContext.declaredIncludeDirs),
       mergeSets(ownerContext.declaredIncludeWarnDirs, libContext.declaredIncludeWarnDirs),
       mergeSets(ownerContext.declaredIncludeSrcs, libContext.declaredIncludeSrcs),
       mergeSets(ownerContext.pregreppedHdrs, libContext.pregreppedHdrs),
       moduleInfo.build(),
       picModuleInfo.build(),
       mergeSets(ownerContext.transitiveModuleMaps, libContext.transitiveModuleMaps),
       mergeSets(ownerContext.directModuleMaps, libContext.directModuleMaps),
       libContext.cppModuleMap,
       libContext.provideTransitiveModuleMaps,
       libContext.useHeaderModules);
 }
Esempio n. 24
0
  private ImmutableSet<AspectWithParameters> requiredAspects(
      AspectDefinition aspectDefinition,
      AspectParameters aspectParameters,
      Attribute attribute,
      Target target,
      Rule originalRule) {
    if (!(target instanceof Rule)) {
      return ImmutableSet.of();
    }

    Set<AspectWithParameters> aspectCandidates =
        extractAspectCandidates(aspectDefinition, aspectParameters, attribute, originalRule);
    RuleClass ruleClass = ((Rule) target).getRuleClassObject();
    ImmutableSet.Builder<AspectWithParameters> result = ImmutableSet.builder();
    for (AspectWithParameters candidateClass : aspectCandidates) {
      ConfiguredAspectFactory candidate =
          (ConfiguredAspectFactory) AspectFactory.Util.create(candidateClass.getAspectFactory());
      if (Sets.difference(
              candidate.getDefinition().getRequiredProviders(), ruleClass.getAdvertisedProviders())
          .isEmpty()) {
        result.add(candidateClass);
      }
    }
    return result.build();
  }
Esempio n. 25
0
  @VisibleForTesting
  List<Module> createModulesForProjectConfigs() throws IOException {
    DependencyGraph dependencyGraph = partialGraph.getDependencyGraph();
    List<Module> modules = Lists.newArrayList();

    // Convert the project_config() targets into modules and find the union of all jars passed to
    // no_dx.
    ImmutableSet.Builder<Path> noDxJarsBuilder = ImmutableSet.builder();
    for (BuildTarget target : partialGraph.getTargets()) {
      BuildRule buildRule = dependencyGraph.findBuildRuleByTarget(target);
      ProjectConfig projectConfig = (ProjectConfig) buildRule.getBuildable();

      BuildRule srcRule = projectConfig.getSrcRule();
      if (srcRule != null) {
        Buildable buildable = srcRule.getBuildable();
        if (buildable instanceof AndroidBinary) {
          AndroidBinary androidBinary = (AndroidBinary) buildable;
          AndroidDexTransitiveDependencies binaryDexTransitiveDependencies =
              androidBinary.findDexTransitiveDependencies();
          noDxJarsBuilder.addAll(binaryDexTransitiveDependencies.noDxClasspathEntries);
        }
      }

      Module module = createModuleForProjectConfig(projectConfig);
      modules.add(module);
    }
    ImmutableSet<Path> noDxJars = noDxJarsBuilder.build();

    // Update module dependencies to apply scope="PROVIDED", where appropriate.
    markNoDxJarsAsProvided(modules, noDxJars);

    return modules;
  }
Esempio n. 26
0
 public static Set<Sort> of(Collection<org.kframework.kil.Sort> sorts) {
   ImmutableSet.Builder<Sort> builder = ImmutableSet.builder();
   for (org.kframework.kil.Sort name : sorts) {
     builder.add(Sort.of(name.getName()));
   }
   return builder.build();
 }
 static {
   ImmutableSet.Builder<Integer> intValues = ImmutableSet.builder();
   // Add boundary values manually to avoid over/under flow (this covers 2^N for 0 and 31).
   intValues.add(Integer.MAX_VALUE - 1, Integer.MAX_VALUE);
   // Add values up to 40. This covers cases like "square of a prime" and such.
   for (int i = 1; i <= 40; i++) {
     intValues.add(i);
   }
   // Now add values near 2^N for lots of values of N.
   for (int exponent : asList(2, 3, 4, 9, 15, 16, 17, 24, 25, 30)) {
     int x = 1 << exponent;
     intValues.add(x, x + 1, x - 1);
   }
   intValues.add(9999).add(10000).add(10001).add(1000000); // near powers of 10
   intValues.add(5792).add(5793); // sqrt(2^25) rounded up and down
   POSITIVE_INTEGER_CANDIDATES = intValues.build();
   NEGATIVE_INTEGER_CANDIDATES =
       ImmutableList.copyOf(
           Iterables.concat(
               Iterables.transform(POSITIVE_INTEGER_CANDIDATES, NEGATE_INT),
               ImmutableList.of(Integer.MIN_VALUE)));
   NONZERO_INTEGER_CANDIDATES =
       ImmutableList.copyOf(
           Iterables.concat(POSITIVE_INTEGER_CANDIDATES, NEGATIVE_INTEGER_CANDIDATES));
   ALL_INTEGER_CANDIDATES = Iterables.concat(NONZERO_INTEGER_CANDIDATES, ImmutableList.of(0));
 }
 protected Builder() {
   id("rackspace-cloudblockstorage-us")
       .name("Rackspace Next Generation Cloud Block Storage US")
       .apiMetadata(
           new CinderApiMetadata()
               .toBuilder()
               .identityName("${userName}")
               .credentialName("${apiKey}")
               .defaultEndpoint("https://identity.api.rackspacecloud.com/v2.0/")
               .endpointName("identity service url ending in /v2.0/")
               .documentation(
                   URI.create(
                       "http://docs.rackspace.com/cbs/api/v1.0/cbs-devguide/content/overview.html"))
               .defaultModules(
                   ImmutableSet.<Class<? extends Module>>builder()
                       .add(CloudIdentityAuthenticationApiModule.class)
                       .add(CloudIdentityAuthenticationModule.class)
                       .add(RegionModule.class)
                       .add(CinderParserModule.class)
                       .add(CinderHttpApiModule.class)
                       .build())
               .build())
       .homepage(URI.create("http://www.rackspace.com/cloud/public/blockstorage/"))
       .console(URI.create("https://mycloud.rackspace.com"))
       .linkedServices("rackspace-cloudservers-us", "cloudfiles-us")
       .iso3166Codes("US-IL", "US-TX", "AU-NSW")
       .endpoint("https://identity.api.rackspacecloud.com/v2.0/")
       .defaultProperties(CloudBlockStorageUSProviderMetadata.defaultProperties());
 }
  @Override
  public AnswerKey apply(AnswerKey input) {
    final Set<Response> existingResponses = Sets.newHashSet(input.allResponses());
    final ImmutableSet.Builder<AssessedResponse> newAssessedResponses = ImmutableSet.builder();
    newAssessedResponses.addAll(input.annotatedResponses());

    for (final AssessedResponse assessedResponse : input.annotatedResponses()) {
      if (assessedResponse.assessment().realis().isPresent()) {
        final Response responseWithAssessedRealis =
            assessedResponse
                .response()
                .copyWithSwappedRealis(assessedResponse.assessment().realis().get());
        if (!existingResponses.contains(responseWithAssessedRealis)) {
          newAssessedResponses.add(
              AssessedResponse.from(responseWithAssessedRealis, assessedResponse.assessment()));
          existingResponses.add(responseWithAssessedRealis);
        }
      }
    }

    return AnswerKey.from(
        input.docId(),
        newAssessedResponses.build(),
        input.unannotatedResponses(),
        input.corefAnnotation());
  }
Esempio n. 30
0
 public Collection<ITrait> getAllTraits() {
   ImmutableSet.Builder<ITrait> builder = ImmutableSet.builder();
   for (List<ITrait> traitlist : traits.values()) {
     builder.addAll(traitlist);
   }
   return builder.build();
 }