@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());
    }
Esempio n. 2
0
  private Iterable<Artifact> getFilteredProtoSources() {
    // Transform the well known proto artifacts by removing the external/bazel_tools prefix if
    // present. Otherwise the comparison for filtering out the well known types is not possible.
    ImmutableSet.Builder<PathFragment> wellKnownProtoPathsBuilder = new ImmutableSet.Builder<>();
    for (Artifact wellKnownProto : attributes.getWellKnownTypeProtos()) {
      PathFragment execPath = wellKnownProto.getExecPath();
      if (execPath.startsWith(BAZEL_TOOLS_PREFIX)) {
        wellKnownProtoPathsBuilder.add(execPath.relativeTo(BAZEL_TOOLS_PREFIX));
      } else {
        wellKnownProtoPathsBuilder.add(execPath);
      }
    }

    ImmutableSet<PathFragment> wellKnownProtoPaths = wellKnownProtoPathsBuilder.build();

    // Filter out the well known types from being sent to be generated, as these protos have already
    // been generated and linked in libprotobuf.a.
    ImmutableSet.Builder<Artifact> filteredProtos = new ImmutableSet.Builder<>();
    for (Artifact proto : getAllProtoSources()) {
      if (!wellKnownProtoPaths.contains(proto.getExecPath())) {
        filteredProtos.add(proto);
      }
    }

    return filteredProtos.build();
  }
Esempio n. 3
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());
 }
    @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. 5
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);
  }
    @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());
    }
    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. 8
0
 public ImmutableSet<ViewedDrawable> getViewed() {
   ImmutableSet<Drawable> draw = controller.watch(viewingRect);
   ImmutableSet.Builder<ViewedDrawable> viewed = ImmutableSet.builder();
   for (Drawable d : draw) {
     viewed.add(ViewedDrawable.wrap(d, this));
   }
   LOG.log(Level.INFO, viewed.build().toString());
   return viewed.build();
 }
 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. 10
0
 public Zone build() {
   return new Zone(
       super.id,
       super.creationTimestamp,
       super.selfLink,
       super.name,
       super.description,
       status,
       maintenanceWindows.build(),
       availableMachineTypes.build());
 }
Esempio n. 11
0
 public Project build() {
   return new Project(
       super.id,
       super.creationTimestamp,
       super.selfLink,
       super.name,
       super.description,
       commonInstanceMetadata.build(),
       quotas.build(),
       externalIpAddresses.build());
 }
  public static ImmutableSet<Path> createPackageLookupPathSet(IjModuleGraph moduleGraph) {
    ImmutableSet.Builder<Path> builder = ImmutableSet.builder();

    for (IjModule module : moduleGraph.getModuleNodes()) {
      for (IjFolder folder : module.getFolders()) {
        if (!folder.getWantsPackagePrefix()) {
          continue;
        }
        Optional<Path> firstJavaFile =
            FluentIterable.from(folder.getInputs())
                .filter(
                    new Predicate<Path>() {
                      @Override
                      public boolean apply(Path input) {
                        return input.getFileName().toString().endsWith(".java");
                      }
                    })
                .first();
        if (firstJavaFile.isPresent()) {
          builder.add(firstJavaFile.get());
        }
      }
    }

    return builder.build();
  }
 static {
   ImmutableSet.Builder<String> builder = ImmutableSet.builder();
   for (TrackerFilterEnum eventFilter : TrackerFilterEnum.values()) {
     builder.add(eventFilter.getValue());
   }
   valuesSet = builder.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());
  }
Esempio n. 15
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. 16
0
 /** Get the safe path strings for a list of paths to use in the build variables. */
 private Collection<String> getSafePathStrings(Collection<PathFragment> paths) {
   ImmutableSet.Builder<String> result = ImmutableSet.builder();
   for (PathFragment path : paths) {
     result.add(path.getSafePathString());
   }
   return result.build();
 }
Esempio n. 17
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);
 }
  @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());
  }
 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));
 }
  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();
  }
Esempio n. 21
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();
 }
 private void ensureTagCache() {
   if (tagCache == null) {
     synchronized (this) {
       if (tagCache == null) {
         tagCache = new Long2ObjectOpenHashMap<List<String>>();
         ImmutableSet.Builder<String> vocabBuilder = ImmutableSet.builder();
         Cursor<String[]> lines = null;
         try {
           lines = new DelimitedTextCursor(tagFile, ",");
         } catch (FileNotFoundException e) {
           throw new DataAccessException("cannot open file", e);
         }
         try {
           for (String[] line : lines) {
             long mid = Long.parseLong(line[0]);
             List<String> tags = tagCache.get(mid);
             if (tags == null) {
               tags = new ArrayList<String>();
               tagCache.put(mid, tags);
             }
             tags.add(line[1]);
             vocabBuilder.add(line[1]);
           }
         } finally {
           lines.close();
         }
         vocabCache = vocabBuilder.build();
       }
     }
   }
 }
Esempio n. 23
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;
  }
 /**
  * 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<ObjectType> withPropertyRequired(Set<ObjectType> objs, String pname) {
   ImmutableSet.Builder<ObjectType> newObjs = ImmutableSet.builder();
   for (ObjectType obj : objs) {
     newObjs.add(obj.withPropertyRequired(pname));
   }
   return newObjs.build();
 }
Esempio n. 26
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. 27
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();
 }
Esempio n. 28
0
  /**
   * List the remote's {@link Ref refs}.
   *
   * @param getHeads whether to return refs in the {@code refs/heads} namespace
   * @param getTags whether to return refs in the {@code refs/tags} namespace
   * @return an immutable set of refs from the remote
   */
  @Override
  public ImmutableSet<Ref> listRefs(final boolean getHeads, final boolean getTags) {
    HttpURLConnection connection = null;
    ImmutableSet.Builder<Ref> builder = new ImmutableSet.Builder<Ref>();
    try {
      String expanded = repositoryURL.toString() + "/repo/manifest";
      connection = HttpUtils.connect(expanded);

      // Get Response
      InputStream is = HttpUtils.getResponseStream(connection);
      BufferedReader rd = new BufferedReader(new InputStreamReader(is));
      String line;
      try {
        while ((line = rd.readLine()) != null) {
          if ((getHeads && line.startsWith("refs/heads"))
              || (getTags && line.startsWith("refs/tags"))) {
            builder.add(HttpUtils.parseRef(line));
          }
        }
      } finally {
        rd.close();
      }

    } catch (Exception e) {
      throw Throwables.propagate(e);
    } finally {
      HttpUtils.consumeErrStreamAndCloseConnection(connection);
    }
    return builder.build();
  }
Esempio n. 29
0
 public Collection<ITrait> getAllTraits() {
   ImmutableSet.Builder<ITrait> builder = ImmutableSet.builder();
   for (List<ITrait> traitlist : traits.values()) {
     builder.addAll(traitlist);
   }
   return builder.build();
 }
Esempio n. 30
0
  public ResponseLinking copyWithFilteredResponses(final Predicate<Response> toKeepCondition) {
    final Set<Response> newIncompletes = Sets.filter(incompleteResponses(), toKeepCondition);
    final ImmutableSet.Builder<ResponseSet> newResponseSetsB = ImmutableSet.builder();
    final ImmutableBiMap.Builder<String, ResponseSet> responseSetsIdB = ImmutableBiMap.builder();
    // to account for ResponseSets merging due to lost annotation
    final Set<ResponseSet> alreadyAdded = Sets.newHashSet();
    for (final ResponseSet responseSet : responseSets()) {
      final ImmutableSet<Response> okResponses =
          FluentIterable.from(responseSet.asSet()).filter(toKeepCondition).toSet();
      if (!okResponses.isEmpty()) {
        final ResponseSet newResponseSet = ResponseSet.from(okResponses);
        if (alreadyAdded.contains(newResponseSet)) {
          continue;
        }
        alreadyAdded.add(newResponseSet);
        newResponseSetsB.add(newResponseSet);
        if (responseSetIds().isPresent()) {
          responseSetsIdB.put(responseSetIds().get().inverse().get(responseSet), newResponseSet);
        }
      }
    }

    final ImmutableSet<ResponseSet> newResponseSets = newResponseSetsB.build();
    final ResponseLinking.Builder ret =
        ResponseLinking.builder()
            .docID(docID())
            .responseSets(newResponseSets)
            .incompleteResponses(newIncompletes);
    if (responseSetIds().isPresent()) {
      ret.responseSetIds(responseSetsIdB.build());
    }
    return ret.build();
  }