Ejemplo n.º 1
0
  /**
   * Create all the modules we are capable of representing in IntelliJ from the supplied graph.
   *
   * @param targetGraph graph whose nodes will be converted to {@link IjModule}s.
   * @return map which for every BuildTarget points to the corresponding IjModule. Multiple
   *     BuildTarget can point to one IjModule (many:one mapping), the BuildTargets which can't be
   *     prepresented in IntelliJ are missing from this mapping.
   */
  public static ImmutableMap<BuildTarget, IjModule> createModules(
      TargetGraph targetGraph, IjModuleFactory moduleFactory) {
    ImmutableSet<TargetNode<?>> supportedTargets =
        FluentIterable.from(targetGraph.getNodes())
            .filter(IjModuleFactory.SUPPORTED_MODULE_TYPES_PREDICATE)
            .toSet();
    ImmutableListMultimap<Path, TargetNode<?>> baseTargetPathMultimap =
        FluentIterable.from(supportedTargets)
            .index(
                new Function<TargetNode<?>, Path>() {
                  @Override
                  public Path apply(TargetNode<?> input) {
                    return input.getBuildTarget().getBasePath();
                  }
                });

    ImmutableMap.Builder<BuildTarget, IjModule> moduleMapBuilder = new ImmutableMap.Builder<>();

    for (Path baseTargetPath : baseTargetPathMultimap.keySet()) {
      ImmutableSet<TargetNode<?>> targets =
          FluentIterable.from(baseTargetPathMultimap.get(baseTargetPath)).toSet();

      IjModule module = moduleFactory.createModule(baseTargetPath, targets);

      for (TargetNode<?> target : targets) {
        moduleMapBuilder.put(target.getBuildTarget(), module);
      }
    }

    return moduleMapBuilder.build();
  }
  private void prepareApplications(Person person, int year, Model model) {

    // get the person's applications for the given year
    List<Application> applications =
        FluentIterable.from(
                applicationService.getApplicationsForACertainPeriodAndPerson(
                    DateUtil.getFirstDayOfYear(year), DateUtil.getLastDayOfYear(year), person))
            .filter(input -> !input.hasStatus(ApplicationStatus.REVOKED))
            .toList();

    if (!applications.isEmpty()) {
      ImmutableList<ApplicationForLeave> applicationsForLeave =
          FluentIterable.from(applications)
              .transform(input -> new ApplicationForLeave(input, calendarService))
              .toSortedList(
                  (o1, o2) -> {
                    // show latest applications at first
                    return o2.getStartDate().compareTo(o1.getStartDate());
                  });

      model.addAttribute("applications", applicationsForLeave);

      UsedDaysOverview usedDaysOverview = new UsedDaysOverview(applications, year, calendarService);
      model.addAttribute("usedDaysOverview", usedDaysOverview);
    }
  }
Ejemplo n.º 3
0
  @Test
  public void flagsArePropagated() throws Exception {
    BuildRuleResolver resolver =
        new BuildRuleResolver(TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer());
    BuildTarget target = BuildTargetFactory.newInstance("//foo:bar");
    BuildRuleParams params = new FakeBuildRuleParamsBuilder(target).build();
    Archive archive =
        Archive.from(
            target,
            params,
            new SourcePathResolver(resolver),
            DEFAULT_ARCHIVER,
            ImmutableList.of("-foo"),
            DEFAULT_RANLIB,
            ImmutableList.of("-bar"),
            Archive.Contents.NORMAL,
            DEFAULT_OUTPUT,
            ImmutableList.of(new FakeSourcePath("simple.o")));

    ImmutableList<Step> steps =
        archive.getBuildSteps(FakeBuildContext.NOOP_CONTEXT, new FakeBuildableContext());
    Step archiveStep = FluentIterable.from(steps).filter(ArchiveStep.class).first().get();
    assertThat(
        archiveStep.getDescription(TestExecutionContext.newInstance()), containsString("-foo"));

    Step ranlibStep = FluentIterable.from(steps).filter(RanlibStep.class).first().get();
    assertThat(
        ranlibStep.getDescription(TestExecutionContext.newInstance()), containsString("-bar"));
  }
  @Then("^the book is empty$")
  public void the_book_is_empty() throws Throwable {

    final List<OrderBookRow> actualBuy =
        FluentIterable.from(matchingUnit.getOrders(OrderSide.Buy))
            .transform(OrderBookRow.FROM_Order(matchingUnit))
            .toImmutableList();
    final List<OrderBookRow> actualSell =
        FluentIterable.from(matchingUnit.getOrders(OrderSide.Sell))
            .transform(OrderBookRow.FROM_Order(matchingUnit))
            .toImmutableList();

    assertEquals(new ArrayList<OrderBookRow>(), actualBuy);
    assertEquals(new ArrayList<OrderBookRow>(), actualSell);
  }
Ejemplo n.º 5
0
  @Test
  public void byCommitsOnBranchNotMerged() throws Exception {
    TestRepository<Repo> repo = createProject("repo");
    int n = 10;
    List<String> shas = new ArrayList<>(n);
    List<Integer> expectedIds = new ArrayList<>(n);
    Branch.NameKey dest = null;
    for (int i = 0; i < n; i++) {
      ChangeInserter ins = newChange(repo, null, null, null, null);
      ins.insert();
      if (dest == null) {
        dest = ins.getChange().getDest();
      }
      shas.add(ins.getPatchSet().getRevision().get());
      expectedIds.add(ins.getChange().getId().get());
    }

    for (int i = 1; i <= 11; i++) {
      Iterable<ChangeData> cds =
          internalChangeQuery.byCommitsOnBranchNotMerged(
              indexes.getSearchIndex().getSchema(), dest, shas, i);
      Iterable<Integer> ids =
          FluentIterable.from(cds)
              .transform(
                  new Function<ChangeData, Integer>() {
                    @Override
                    public Integer apply(ChangeData in) {
                      return in.getId().get();
                    }
                  });
      String name = "batch size " + i;
      assertThat(ids).named(name).hasSize(n);
      assertThat(ids).named(name).containsExactlyElementsIn(expectedIds);
    }
  }
  /**
   * Finds types extending {@link ServicesCoreBootstrapGuiceModule}: {@link
   * BeanImplementedServicesCoreGuiceModule}, {@link RESTImplementedServicesCoreGuiceModuleBase},
   * etc if no type is found it returns null
   *
   * @param coreAppCode
   * @param coreModule
   * @return
   */
  @SuppressWarnings("unchecked")
  private Set<Class<? extends ServicesCoreBootstrapGuiceModule>> _findCoreGuiceModulesOrNull(
      final Collection<CoreAppCode> coreAppCodes,
      final Class<? extends ServicesCoreBootstrapGuiceModule> coreGuiceModuleType) {
    List<String> pckgs = Lists.newLinkedList();
    pckgs.add(ServicesCoreBootstrapGuiceModule.class.getPackage().getName());
    pckgs.add(R01F.class.getPackage().getName()); // r01f.internal										
    for (CoreAppCode coreAppCode : coreAppCodes) {
      pckgs.add(ServicesPackages.coreGuiceModulePackage(coreAppCode));
    }
    Set<?> foundBootstrapModuleTypes =
        ServicesPackages.findSubTypesAt(
            coreGuiceModuleType, pckgs, this.getClass().getClassLoader());

    // Filter the interfaces
    Set<Class<? extends ServicesCoreBootstrapGuiceModule>> outModuleTypes =
        (Set<Class<? extends ServicesCoreBootstrapGuiceModule>>) foundBootstrapModuleTypes;
    return FluentIterable.from(outModuleTypes)
        .filter(
            new Predicate<Class<? extends ServicesCoreBootstrapGuiceModule>>() {
              @Override
              public boolean apply(final Class<? extends ServicesCoreBootstrapGuiceModule> module) {
                return ReflectionUtils.isInstanciable(module);
              }
            })
        .toSet();
  }
  public TableLevelWatermarker(State state) {
    this.tableWatermarks = Maps.newHashMap();

    // Load previous watermarks in case of sourceState
    if (state instanceof SourceState) {
      SourceState sourceState = (SourceState) state;
      for (Map.Entry<String, Iterable<WorkUnitState>> datasetWorkUnitStates :
          sourceState.getPreviousWorkUnitStatesByDatasetUrns().entrySet()) {

        // Use the minimum of all previous watermarks for this dataset
        List<LongWatermark> previousWatermarks =
            FluentIterable.from(datasetWorkUnitStates.getValue())
                .filter(Predicates.not(PartitionLevelWatermarker.WATERMARK_WORKUNIT_PREDICATE))
                .transform(
                    new Function<WorkUnitState, LongWatermark>() {
                      @Override
                      public LongWatermark apply(WorkUnitState w) {
                        return w.getActualHighWatermark(LongWatermark.class);
                      }
                    })
                .toList();

        if (!previousWatermarks.isEmpty()) {
          this.tableWatermarks.put(
              datasetWorkUnitStates.getKey(), Collections.min(previousWatermarks));
        }
      }
      log.info("Loaded table watermarks from previous state " + this.tableWatermarks);
    }
  }
  private Set<String> getJcloudsLocationIds(final Collection<? extends String> jcloudsApiIds) {
    Set<String> openstackNovaProviders =
        FluentIterable.from(Providers.all())
            .filter(
                new Predicate<ProviderMetadata>() {
                  @Override
                  public boolean apply(ProviderMetadata providerMetadata) {
                    return jcloudsApiIds.contains(providerMetadata.getApiMetadata().getId());
                  }
                })
            .transform(
                new Function<ProviderMetadata, String>() {
                  @Nullable
                  @Override
                  public String apply(ProviderMetadata input) {
                    return input.getId();
                  }
                })
            .toSet();

    return new ImmutableSet.Builder<String>()
        .addAll(openstackNovaProviders)
        .addAll(jcloudsApiIds)
        .build();
  }
Ejemplo n.º 9
0
    @Value.Lazy
    public List<TypeElement> includedTypes() {
      Optional<IncludeMirror> includes = include();

      ImmutableList<TypeMirror> typeMirrors =
          includes.isPresent()
              ? ImmutableList.copyOf(includes.get().valueMirror())
              : ImmutableList.<TypeMirror>of();

      FluentIterable<TypeElement> typeElements =
          FluentIterable.from(typeMirrors)
              .filter(DeclaredType.class)
              .transform(DeclatedTypeToElement.FUNCTION);

      ImmutableSet<String> uniqueTypeNames =
          typeElements.filter(IsPublic.PREDICATE).transform(ElementToName.FUNCTION).toSet();

      if (uniqueTypeNames.size() != typeMirrors.size()) {
        report()
            .annotationNamed(IncludeMirror.simpleName())
            .warning(
                "Some types were ignored, non-supported for inclusion: duplicates, non declared reference types, non-public");
      }

      return typeElements.toList();
    }
Ejemplo n.º 10
0
    @Override
    public ARGPath getNextPathForInterpolation() {
      ARGState current = sources.remove(0);

      assert current.isTarget() : "current element is not a target";

      ARGPathBuilder errorPathBuilder = ARGPath.reverseBuilder();

      errorPathBuilder.add(
          current, FluentIterable.from(AbstractStates.getOutgoingEdges(current)).first().orNull());

      while (predecessorRelation.get(current) != null) {

        ARGState parent = predecessorRelation.get(current);

        if (stateHasFalseInterpolant(parent)) {
          logger.log(
              Level.FINEST,
              "interpolant on path, namely for state ",
              parent.getStateId(),
              " is already false, so return empty path");
          return EMPTY_PATH;
        }

        if (predecessorRelation.get(parent) != null) {
          errorPathBuilder.add(parent, parent.getEdgeToChild(current));
        }

        current = parent;
      }

      return errorPathBuilder.build(current);
    }
 /**
  * Returns a map with the labels of a certain structure indexed by their oid
  *
  * @param cats
  * @param structureOid
  * @param role
  * @return
  */
 private static Map<String, String> _labelsInStructure(
     final List<R01MSearchResultItemStructureCatalog> cats,
     final String structureOid,
     final String role) {
   if (CollectionUtils.isNullOrEmpty(cats)) return null;
   Collection<R01MSearchResultItemStructureCatalog> roleCats =
       FluentIterable.from(cats)
           .filter(
               new Predicate<R01MSearchResultItemStructureCatalog>() {
                 @Override
                 public boolean apply(final R01MSearchResultItemStructureCatalog cat) {
                   return cat.getStructureOid().equals(structureOid) && cat.getRole().equals(role);
                 }
               })
           .toList();
   // Get the labels descriptions
   Map<String, String> outCats = new HashMap<String, String>(roleCats.size());
   Labels labels = LABELS.get(structureOid);
   for (R01MSearchResultItemStructureCatalog cat : roleCats) {
     String labelOid = cat.getLabelOid();
     String label = labels.getByOid(labelOid);
     if (label != null) outCats.put(labelOid, label);
   }
   return outCats;
 }
Ejemplo n.º 12
0
 /**
  * Displays the aggregate utilization for the entire cluster.
  *
  * @return HTML-formatted cluster utilization.
  */
 @GET
 @Produces(MediaType.TEXT_HTML)
 public Response aggregateCluster() {
   Iterable<DisplayMetric> metrics =
       FluentIterable.from(counter.computeConsumptionTotals()).transform(TO_DISPLAY).toList();
   return Response.ok(fillTemplate(metrics)).build();
 }
Ejemplo n.º 13
0
  private Optional<RuleKey> calculateDepFileRuleKey(
      BuildRule rule, Optional<ImmutableList<String>> depFile, boolean allowMissingInputs)
      throws IOException {

    Preconditions.checkState(useDependencyFileRuleKey(rule));

    // Extract the dep file from the last build.  If we don't find one, abort.
    if (!depFile.isPresent()) {
      return Optional.absent();
    }

    // Add in the inputs explicitly listed in the dep file.  If any inputs are no longer on disk,
    // this means something changed and a dep-file based rule key can't be calculated.
    ImmutableList<Path> inputs =
        FluentIterable.from(depFile.get()).transform(MorePaths.TO_PATH).toList();
    RuleKeyBuilder builder = depFileRuleKeyBuilderFactory.newInstance(rule);
    for (Path input : inputs) {
      try {
        builder.setPath(input);
      } catch (NoSuchFileException e) {
        if (!allowMissingInputs) {
          throw e;
        }
        return Optional.absent();
      }
    }

    return Optional.of(builder.build());
  }
 @Override
 public List<Attachment> findAllChildrenOfParentIds(List<UUID> parents, List<String> extensions) {
   return FluentIterable.from(entities.values())
       .filter(withParentId(parents.toArray(new UUID[parents.size()])))
       .filter(withExtension(extensions.toArray(new String[extensions.size()])))
       .toList();
 }
Ejemplo n.º 15
0
 public static HaskellPackageRule from(
     BuildTarget target,
     BuildRuleParams baseParams,
     final SourcePathResolver resolver,
     final Tool ghcPkg,
     HaskellPackageInfo packageInfo,
     final ImmutableSortedMap<String, HaskellPackage> depPackages,
     ImmutableSortedSet<String> modules,
     final ImmutableSortedSet<SourcePath> libraries,
     final ImmutableSortedSet<SourcePath> interfaces) {
   return new HaskellPackageRule(
       baseParams.copyWithChanges(
           target,
           Suppliers.memoize(
               () ->
                   ImmutableSortedSet.<BuildRule>naturalOrder()
                       .addAll(ghcPkg.getDeps(resolver))
                       .addAll(
                           FluentIterable.from(depPackages.values())
                               .transformAndConcat(HaskellPackage.getDepsFunction(resolver)))
                       .addAll(
                           resolver.filterBuildRuleInputs(Iterables.concat(libraries, interfaces)))
                       .build()),
           Suppliers.ofInstance(ImmutableSortedSet.of())),
       resolver,
       ghcPkg,
       packageInfo,
       depPackages,
       modules,
       libraries,
       interfaces);
 }
Ejemplo n.º 16
0
 @Override
 public ImmutableSortedSet<Path> getSortedMatchingDirectoryContents(
     final Path pathRelativeToProjectRoot, String globPattern) throws IOException {
   Preconditions.checkState(isDirectory(pathRelativeToProjectRoot));
   final PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher("glob:" + globPattern);
   return FluentIterable.from(fileContents.keySet())
       .filter(
           new Predicate<Path>() {
             @Override
             public boolean apply(Path input) {
               return input.getParent().equals(pathRelativeToProjectRoot)
                   && pathMatcher.matches(input.getFileName());
             }
           })
       .toSortedSet(
           Ordering.natural()
               .onResultOf(
                   new Function<Path, FileTime>() {
                     @Override
                     public FileTime apply(Path path) {
                       try {
                         return getLastModifiedTimeFetcher().getLastModifiedTime(path);
                       } catch (IOException e) {
                         throw new RuntimeException(e);
                       }
                     }
                   })
               .compound(Ordering.natural())
               .reverse());
 }
Ejemplo n.º 17
0
  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();
  }
Ejemplo n.º 18
0
 @Override
 public Epoch load(int evolutionId, long epochId, final PopulationConfiguration configuration)
     throws Exception {
   try {
     List<Probe> probes = dao.retrieve(evolutionId, epochId);
     if (probes != null && probes.size() > 0) {
       return Epoch.create(
           probes.get(0).getEpochId(),
           new Population(
               FluentIterable.from(probes)
                   .transform(
                       new Function<Probe, Genome>() {
                         @Override
                         public Genome apply(Probe input) {
                           return new Genome(
                               input.getGenomeId(),
                               input.getGenomeWeights(),
                               configuration.getPerceptronConfiguration());
                         }
                       })
                   .toList(),
               configuration,
               new DefaultPerceptronProvider()));
     } else {
       return null;
     }
   } catch (Exception e) {
     throw new Exception("Loading service failed. Latest epoch hasn't been loaded.", e);
   }
 }
Ejemplo n.º 19
0
 public static ImmutableSet<Path> createFilesystemTraversalBoundaryPathSet(
     ImmutableSet<IjModule> modules) {
   return FluentIterable.from(modules)
       .transform(IjModule.TO_MODULE_BASE_PATH)
       .append(IjProjectWriter.IDEA_CONFIG_DIR_PREFIX)
       .toSet();
 }
Ejemplo n.º 20
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();
  }
Ejemplo n.º 21
0
 public Builder setRuleKeys(Iterable<RuleKey> ruleKeys) {
   // Make sure we expand any lazy evaluation Iterators so Json serialization works correctly.
   List<String> keysAsStrings =
       FluentIterable.from(ruleKeys).transform(Functions.toStringFunction()).toList();
   data.put("rule_keys", keysAsStrings);
   return this;
 }
Ejemplo n.º 22
0
 private Collection<? extends ApiListingReference> apiListingReferences(
     Multimap<String, ApiListing> apiListings, DocumentationContext context) {
   Map<String, Collection<ApiListing>> grouped = Multimaps.asMap(apiListings);
   return FluentIterable.from(grouped.entrySet())
       .transform(toApiListingReference(context))
       .toSet();
 }
Ejemplo n.º 23
0
    public List<Node> selectRandomNodes(int limit) {
      checkArgument(limit > 0, "limit must be at least 1");

      return ImmutableList.copyOf(
          FluentIterable.from(lazyShuffle(nodeMap.get().get().getNodesByHostAndPort().values()))
              .limit(limit));
    }
Ejemplo n.º 24
0
    @Override
    public Number calculate(Iterable<IScheduledTask> tasks, Range<Long> timeFrame) {
      Iterable<IScheduledTask> activeTasks =
          FluentIterable.from(tasks)
              .filter(Predicates.compose(Predicates.in(Tasks.ACTIVE_STATES), Tasks.GET_STATUS));

      List<Long> waitTimes = Lists.newLinkedList();
      for (IScheduledTask task : activeTasks) {
        long pendingTs = 0;
        for (ITaskEvent event : task.getTaskEvents()) {
          if (event.getStatus() == PENDING) {
            pendingTs = event.getTimestamp();
          } else if (event.getStatus() == status && timeFrame.contains(event.getTimestamp())) {

            if (pendingTs == 0) {
              throw new IllegalArgumentException(
                  "SLA: missing PENDING status for:" + task.getAssignedTask().getTaskId());
            }

            waitTimes.add(event.getTimestamp() - pendingTs);
            break;
          }
        }
      }

      return SlaUtil.percentile(waitTimes, 50.0);
    }
Ejemplo n.º 25
0
 private static Map<FileLike, String> traverse(Collection<File> files) throws IOException {
   Collection<Path> paths =
       FluentIterable.from(files)
           .transform(
               new Function<File, Path>() {
                 @Override
                 public Path apply(File file) {
                   return file.toPath();
                 }
               })
           .toList();
   final ImmutableMap.Builder<FileLike, String> completeList = ImmutableMap.builder();
   ClasspathTraverser traverser = new DefaultClasspathTraverser();
   ProjectFilesystem filesystem = new ProjectFilesystem(Paths.get(".").toAbsolutePath());
   traverser.traverse(
       new ClasspathTraversal(paths, filesystem) {
         @Override
         public void visit(FileLike fileLike) {
           String contents;
           try {
             contents = new FileLikeCharSource(fileLike).read();
           } catch (IOException e) {
             throw Throwables.propagate(e);
           }
           completeList.put(fileLike, contents);
         }
       });
   return completeList.build();
 }
Ejemplo n.º 26
0
  /**
   * @param buildTarget target to process.
   * @return the set of {@link BuildTarget}s that must be appended to the dependencies of a node Y
   *     if node Y depends on X.
   */
  public ImmutableSet<BuildTarget> getExportedDepsClosure(BuildTarget buildTarget) {
    if (index.containsKey(buildTarget)) {
      return index.get(buildTarget);
    }

    ImmutableSet<BuildTarget> exportedDeps = ImmutableSet.of();
    TargetNode<?> targetNode = Preconditions.checkNotNull(targetGraph.get(buildTarget));
    if (targetNode.getType().equals(JavaLibraryDescription.TYPE)) {
      JavaLibraryDescription.Arg arg = (JavaLibraryDescription.Arg) targetNode.getConstructorArg();
      exportedDeps = arg.exportedDeps.get();
    } else if (targetNode.getType().equals(AndroidLibraryDescription.TYPE)) {
      AndroidLibraryDescription.Arg arg =
          (AndroidLibraryDescription.Arg) targetNode.getConstructorArg();
      exportedDeps = arg.exportedDeps.get();
    }

    ImmutableSet<BuildTarget> exportedDepsClosure =
        FluentIterable.from(exportedDeps)
            .transformAndConcat(
                new Function<BuildTarget, Iterable<BuildTarget>>() {
                  @Override
                  public Iterable<BuildTarget> apply(BuildTarget input) {
                    return Iterables.concat(ImmutableSet.of(input), getExportedDepsClosure(input));
                  }
                })
            .toSet();
    index.put(buildTarget, exportedDepsClosure);
    return exportedDepsClosure;
  }
 @Then("^no trades are generated$")
 public void no_trades_are_generated() throws Throwable {
   List<TradeRow> actualTrades =
       FluentIterable.from(generatedTrades).transform(TradeRow.FROM_TRADE).toImmutableList();
   List<TradeRow> empty = new ArrayList<TradeRow>();
   assertEquals(empty, actualTrades);
 }
Ejemplo n.º 28
0
  private void fireOrContinue(
      TriggerResult triggerResult, W window, ListState<StreamRecord<IN>> windowState)
      throws Exception {
    if (!triggerResult.isFire()) {
      return;
    }

    timestampedCollector.setAbsoluteTimestamp(window.maxTimestamp());
    Iterable<StreamRecord<IN>> contents = windowState.get();

    // Work around type system restrictions...
    int toEvict = evictor.evict((Iterable) contents, Iterables.size(contents), context.window);

    FluentIterable<IN> projectedContents =
        FluentIterable.from(contents)
            .skip(toEvict)
            .transform(
                new Function<StreamRecord<IN>, IN>() {
                  @Override
                  public IN apply(StreamRecord<IN> input) {
                    return input.getValue();
                  }
                });
    userFunction.apply(context.key, context.window, projectedContents, timestampedCollector);
  }
  public BoundStatementWrapper bindForUpdate(
      PersistentStateHolder context, PreparedStatement ps, List<PropertyMeta> pms) {
    EntityMeta entityMeta = context.getEntityMeta();
    Object entity = context.getEntity();

    log.trace(
        "Bind prepared statement {} for properties {} update of entity {}",
        ps.getQueryString(),
        pms,
        entity);

    ConsistencyLevel consistencyLevel = overrider.getWriteLevel(context);

    List<Object> values = new ArrayList<>();

    final int staticColumnsCount =
        FluentIterable.from(pms).filter(PropertyMeta.STATIC_COLUMN_FILTER).size();
    final boolean onlyStaticColumns = staticColumnsCount > 0 && pms.size() == staticColumnsCount;

    values.addAll(fetchTTLAndTimestampValues(context));
    values.addAll(fetchPropertiesValues(pms, entity));
    values.addAll(fetchPrimaryKeyValues(entityMeta, entity, onlyStaticColumns));
    values.addAll(fetchCASConditionsValues(context, entityMeta));
    BoundStatement bs = ps.bind(values.toArray());

    return new BoundStatementWrapper(
        context.getEntityClass(),
        bs,
        values.toArray(),
        getCQLLevel(consistencyLevel),
        context.getCASResultListener(),
        context.getSerialConsistencyLevel());
  }
Ejemplo n.º 30
0
 /**
  * Filters out {@link Path} objects from {@code paths} that aren't a subpath of {@code root} and
  * returns a set of paths relative to {@code root}.
  */
 public static ImmutableSet<Path> filterForSubpaths(Iterable<Path> paths, final Path root) {
   final Path normalizedRoot = root.toAbsolutePath().normalize();
   return FluentIterable.from(paths)
       .filter(
           new Predicate<Path>() {
             @Override
             public boolean apply(Path input) {
               if (input.isAbsolute()) {
                 return input.normalize().startsWith(normalizedRoot);
               } else {
                 return true;
               }
             }
           })
       .transform(
           new Function<Path, Path>() {
             @Override
             public Path apply(Path input) {
               if (input.isAbsolute()) {
                 return normalizedRoot.relativize(input.normalize());
               } else {
                 return input;
               }
             }
           })
       .toSet();
 }