com.google.common.collect.FluentIterable#from ( )源码实例Demo

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

源代码1 项目: dremio-oss   文件: MaterializationStore.java
public FluentIterable<Refresh> getRefreshes(final Materialization materialization) {
  Long seriesId = materialization.getSeriesId();
  Integer seriesOrdinal = materialization.getSeriesOrdinal();

  if(seriesId == null || seriesOrdinal == null) {
    return FluentIterable.from(ImmutableList.<Refresh>of());
  }

  final LegacyFindByCondition condition = new LegacyFindByCondition()
      .setCondition(and(
        newTermQuery(ReflectionIndexKeys.REFRESH_REFLECTION_ID, materialization.getReflectionId().getId()),
        newTermQuery(ReflectionIndexKeys.REFRESH_SERIES_ID, seriesId),
        newRangeInt(ReflectionIndexKeys.REFRESH_SERIES_ORDINAL.getIndexFieldName(), 0, seriesOrdinal, true, true)
      ));
    return FluentIterable.from(refreshStore.get().find(condition)).transform(new Function<Entry<RefreshId, Refresh>, Refresh>(){

      @Override
      public Refresh apply(Entry<RefreshId, Refresh> input) {
        return inlineUpgrade(input.getValue());
      }});
}
 
/**
 * Goes over the specified metrics and if both execute-count and execute-latency are present,
 * computes the capacity metric according to the formula capacity = execute-count * execute-latency / time-window-ms
 *
 * @param component2metrics metrics keyed by component name.
 * @param taskInfo          additional task information pertaining to the reporting task.
 * @return The capacity metrics that were calculated based on the specified input metrics.
 */
public static ImmutableList<Metric> calculateCapacityMetrics(final Map<String, List<Metric>> component2metrics,
                                                             final IMetricsConsumer.TaskInfo taskInfo) {

  final Function<Map.Entry<String, List<Metric>>, Optional<Metric>> toCapacityMetric =
          new Function<Map.Entry<String, List<Metric>>, Optional<Metric>>() {
            @Override
            public Optional<Metric> apply(final Map.Entry<String, List<Metric>> componentMetrics) {

              final String component = componentMetrics.getKey();
              final FluentIterable<Metric> metrics = FluentIterable.from(componentMetrics.getValue());
              final Optional<Metric> count = metrics.firstMatch(isExecuteCountMetric);
              final Optional<Metric> latency = metrics.firstMatch(isExecuteLatencyMetric);

              return calculateCapacityMetric(component, count, latency, taskInfo.updateIntervalSecs);
            }
          };

  return FluentIterable
          .from(component2metrics.entrySet())
          .transform(toCapacityMetric)
          .filter(Metric.Option.isPresent)
          .transform(Metric.Option.getValue)
          .toList();
}
 
源代码3 项目: karamel   文件: NovaLauncherTest.java
@Test
public void uploadSSHPublicKeyAndRecreateOld() throws KaramelException {
  String keypairName = "pepeKeyPair";
  KeyPair pair = mock(KeyPair.class);

  List<KeyPair> keyPairList = new ArrayList<>();
  keyPairList.add(pair);
  FluentIterable<KeyPair> keys = FluentIterable.from(keyPairList);

  when(keyPairApi.list()).thenReturn(keys);
  when(keyPairApi.delete(keypairName)).thenReturn(true);
  when(keyPairApi.createWithPublicKey(keypairName, sshKeyPair.getPublicKey())).thenReturn(pair);

  NovaLauncher novaLauncher = new NovaLauncher(novaContext, sshKeyPair);
  boolean uploadSuccessful = novaLauncher.uploadSshPublicKey(keypairName, nova, true);
  assertTrue(uploadSuccessful);
}
 
源代码4 项目: karamel   文件: NovaLauncherTest.java
@Test
public void uploadSSHPublicKeyAndNotRecreateOldFail() throws KaramelException {
  String keypairName = "pepeKeyPair";
  KeyPair pair = mock(KeyPair.class);

  List<KeyPair> keyPairList = new ArrayList<>();
  keyPairList.add(pair);
  FluentIterable<KeyPair> keys = FluentIterable.from(keyPairList);

  when(keyPairApi.list()).thenReturn(keys);
  when(keyPairApi.delete(keypairName)).thenReturn(true);
  when(keyPairApi.createWithPublicKey(keypairName, sshKeyPair.getPublicKey())).thenReturn(pair);

  NovaLauncher novaLauncher = new NovaLauncher(novaContext, sshKeyPair);
  boolean uploadSuccessful = novaLauncher.uploadSshPublicKey(keypairName, nova, false);
  assertFalse(uploadSuccessful);
}
 
源代码5 项目: attic-aurora   文件: MetricCalculator.java
@Timed("sla_stats_computation")
@Override
public void run() {
  FluentIterable<IScheduledTask> tasks =
      FluentIterable.from(Storage.Util.fetchTasks(storage, Query.unscoped()));

  List<IScheduledTask> prodTasks = tasks.filter(Predicates.compose(
      Predicates.and(ITaskConfig::isProduction, IS_SERVICE),
      Tasks::getConfig)).toList();

  List<IScheduledTask> nonProdTasks = tasks.filter(Predicates.compose(
      Predicates.and(Predicates.not(ITaskConfig::isProduction), IS_SERVICE),
      Tasks::getConfig)).toList();

  long nowMs = clock.nowMillis();
  Range<Long> timeRange = Range.closedOpen(nowMs - settings.refreshRateMs, nowMs);

  runAlgorithms(prodTasks, settings.prodMetrics, timeRange, NAME_QUALIFIER_PROD);
  runAlgorithms(nonProdTasks, settings.nonProdMetrics, timeRange, NAME_QUALIFIER_NON_PROD);
}
 
源代码6 项目: brooklyn-server   文件: ItemLister.java
private <T extends BrooklynObject> List<Class<? extends T>> getTypes(List<URL> urls, Class<T> type, Boolean catalogOnlyOverride) {
    // TODO this only really works if you give it lots of URLs - see comment on "--jar" argument
    // NB if the ReflectionScanner class is given "null" then it will scan, better than INITIAL_CLASSPATH 
    FluentIterable<Class<? extends T>> fluent = FluentIterable.from(ClassFinder.findClasses(urls, type));
    if (typeRegex != null) {
        fluent = fluent.filter(ClassFinder.withClassNameMatching(typeRegex));
    }
    if (catalogOnlyOverride == null ? !allClasses : catalogOnlyOverride) {
        fluent = fluent.filter(ClassFinder.withAnnotation(Catalog.class));
    }
    List<Class<? extends T>> filtered = fluent.toList();
    Collection<Class<? extends T>> result;
    if (!includeImpls) {
        result = MutableSet.copyOf(filtered);
        for (Class<? extends T> clazz : filtered) {
            ImplementedBy implementedBy = clazz.getAnnotation(ImplementedBy.class);
            if (implementedBy != null) {
                result.remove(implementedBy.value());
            }
        }
    } else {
        result = filtered;
    }
    itemCount += result.size();
    return ImmutableList.copyOf(result);
}
 
源代码7 项目: tac-kbp-eal   文件: GraphAnalyses.java
@SuppressWarnings("unchecked")
static <T, V> Function<File, List<V>> deserializeAndTransformFunction(
    final Function<T, V> transformer)
    throws IOException {
  final JacksonSerializer jacksonSerializer = JacksonSerializer.json().prettyOutput().build();

  return new Function<File, List<V>>() {
    @Override
    public List<V> apply(final File f) {
      final FluentIterable<T> from;
      try {
        from = FluentIterable.from((Iterable<T>) jacksonSerializer
            .deserializeFrom(GZIPByteSource.fromCompressed(Files.asByteSource(f))));
      } catch (IOException e) {
        throw new RuntimeException(e);
      }
      return from.transform(transformer).toList();
    }
  };
}
 
源代码8 项目: morf   文件: AbstractSqlDialectTest.java
/**
 * The window functions to test
 */
private FluentIterable<AliasedField> windowFunctions(){
  return FluentIterable.from(Lists.newArrayList(
    windowFunction(count()).build(),
    windowFunction(count()).partitionBy(field("field1")).build(),
    windowFunction(sum(field("field1"))).partitionBy(field("field2"),field("field3")).orderBy(field("field4")).build(),
    windowFunction(max(field("field1"))).partitionBy(field("field2"),field("field3")).orderBy(field("field4").asc()).build(),
    windowFunction(min(field("field1"))).partitionBy(field("field2"),field("field3")).orderBy(field("field4").desc(),field("field5")).build(),
    windowFunction(min(field("field1"))).orderBy(field("field2")).build(),
    select( windowFunction(min(field("field1"))).orderBy(field("field2")).build().as("window")).from(tableRef("srcTable")).asField()
    ));
}
 
源代码9 项目: buck   文件: XcodeNativeTargetGenerator.java
private FluentIterable<TargetNode<?>> collectRecursiveLibraryDepTargets(
    TargetNode<?> targetNode) {
  FluentIterable<TargetNode<?>> allDeps =
      FluentIterable.from(
          AppleBuildRules.getRecursiveTargetNodeDependenciesOfTypes(
              xcodeDescriptions,
              targetGraph,
              Optional.of(dependenciesCache),
              RecursiveDependenciesMode.LINKING,
              targetNode,
              xcodeDescriptions.getXCodeDescriptions()));
  return allDeps.filter(this::isLibraryWithSourcesToCompile);
}
 
源代码10 项目: raml-java-tools   文件: TopResourceSelector.java
@Override
public FluentIterable<Resource> fromResource(Resource resource) {
    return FluentIterable.from(resource.resources());
}
 
源代码11 项目: onos   文件: SimpleVirtualGroupStore.java
@Override
public Iterable<Group> getExtraneousGroups(NetworkId networkId, DeviceId deviceId) {
    // flatten and make iterator unmodifiable
    return FluentIterable.from(
            getExtraneousGroupIdTable(networkId, deviceId).values());
}
 
static FluentIterable<Integer> createFluentIterable() {
    return FluentIterable.from(Sets.newHashSet(1, 2, 3));
}
 
源代码13 项目: onos   文件: DistributedGroupStore.java
@Override
public Iterable<Group> getExtraneousGroups(DeviceId deviceId) {
    // flatten and make iterator unmodifiable
    return FluentIterable.from(
            getExtraneousGroupIdTable(deviceId).values());
}
 
源代码14 项目: immutables   文件: ValueType.java
private FluentIterable<ValueAttribute> attributes() {
  return FluentIterable.from(attributes);
}
 
源代码15 项目: karamel   文件: NovaLauncherTest.java
@Ignore
@Test
public void testForkMachines() throws KaramelException, RunNodesException {
  NovaLauncher novaLauncher = new NovaLauncher(novaContext, sshKeyPair);
  //mocking uploadSSHPublicKey
  String keypairName = "pepeKeyPair";
  KeyPair pair = mock(KeyPair.class);

  List<KeyPair> keyPairList = new ArrayList<>();
  keyPairList.add(pair);
  FluentIterable<KeyPair> keys = FluentIterable.from(keyPairList);

  when(keyPairApi.list()).thenReturn(keys);
  when(keyPairApi.delete(keypairName)).thenReturn(true);
  when(keyPairApi.createWithPublicKey(keypairName, sshKeyPair.getPublicKey())).thenReturn(pair);

  //mocking
  JsonCluster cluster = mock(JsonCluster.class);
  ClusterRuntime clusterRuntime = mock(ClusterRuntime.class);
  when(clusterRuntime.getName()).thenReturn(clusterName);
  List<JsonGroup> groups = new ArrayList<>();

  //mocking json group
  JsonGroup group = mock(JsonGroup.class);
  groups.add(group);
  when(group.getName()).thenReturn(groupName);
  when(group.getProvider()).thenReturn(nova);
  when(group.getSize()).thenReturn(1);

  //mocking json cluster
  when(cluster.getGroups()).thenReturn(groups);
  when(cluster.getProvider()).thenReturn(nova);
  when(cluster.getName()).thenReturn(clusterName);

  //mocking group runtime
  List<GroupRuntime> groupRuntimes = new ArrayList<>();
  GroupRuntime groupRuntime = mock(GroupRuntime.class);
  when(groupRuntime.getName()).thenReturn(groupName);
  when(groupRuntime.getId()).thenReturn("10");
  when(groupRuntime.getCluster()).thenReturn(clusterRuntime);
  groupRuntimes.add(groupRuntime);

  //mocking clusterRuntime
  when(clusterRuntime.getGroups()).thenReturn(groupRuntimes);

  //mocking templateOptions
  NovaTemplateOptions novaTemplateOptions = mock(NovaTemplateOptions.class);
  TemplateBuilder templateBuilder = mock(TemplateBuilder.class);

  TemplateOptions templateOptions = mock(TemplateOptions.class);

  when(novaContext.getComputeService()).thenReturn(novaComputeService);
  when(novaComputeService.templateOptions()).thenReturn(novaTemplateOptions);

  when(novaTemplateOptions.securityGroups(Matchers.anyCollection())).thenReturn(novaTemplateOptions);
  when(templateOptions.as(NovaTemplateOptions.class)).thenReturn(novaTemplateOptions);
  when(novaComputeService.templateBuilder()).thenReturn(templateBuilder);

  //mock builder
  when(novaTemplateOptions.keyPairName(keypairName)).thenReturn(novaTemplateOptions);
  when(novaTemplateOptions.autoAssignFloatingIp(true)).thenReturn(novaTemplateOptions);
  when(novaTemplateOptions.nodeNames(Matchers.anyCollection())).thenReturn(novaTemplateOptions);

  //mock success nodes
  Set<NodeMetadata> succeededNodes = new HashSet<>();
  NodeMetadata succeededNode = mock(NodeMetadata.class);

  succeededNodes.add(succeededNode);
  doReturn(succeededNodes).when(novaComputeService)
          .createNodesInGroup(Matchers.anyString(), eq(1), Matchers.any(Template.class));

  LoginCredentials loginCredentials = mock(LoginCredentials.class);
  Set<String> ipAddresses = new HashSet<>();
  ipAddresses.add("127.0.0.1");
  when(succeededNode.getPublicAddresses()).thenReturn(ipAddresses);
  when(succeededNode.getPrivateAddresses()).thenReturn(ipAddresses);
  when(succeededNode.getLoginPort()).thenReturn(22);
  when(succeededNode.getCredentials()).thenReturn(loginCredentials);
  when(loginCredentials.getUser()).thenReturn("ubuntu");

  //testing method
  List<MachineRuntime> forkedMachines =novaLauncher.forkMachines(cluster,clusterRuntime,groupName);

  assertNotNull(forkedMachines);
  assertFalse(forkedMachines.isEmpty());
}
 
源代码16 项目: karamel   文件: NovaLauncherTest.java
@Test
public void cleanup() throws KaramelException{
  String uniqueGroup = NovaSetting.NOVA_UNIQUE_GROUP_NAME(clusterName, groupName);

  //mocking
  JsonCluster cluster = mock(JsonCluster.class);
  ClusterRuntime clusterRuntime = mock(ClusterRuntime.class);
  when(clusterRuntime.getName()).thenReturn(clusterName);

  List<JsonGroup> groups = new ArrayList<>();
  JsonGroup group = mock(JsonGroup.class);
  groups.add(group);
  when(cluster.getGroups()).thenReturn(groups);
  when(cluster.getProvider()).thenReturn(nova);
  when(cluster.getName()).thenReturn(clusterName);

  //mocking json group
  when(group.getName()).thenReturn(groupName);
  when(group.getProvider()).thenReturn(nova);
  when(group.getSize()).thenReturn(1);

  //mocking group runtime
  List<GroupRuntime> groupRuntimes = new ArrayList<>();
  GroupRuntime groupRuntime = mock(GroupRuntime.class);
  when(groupRuntime.getName()).thenReturn(groupName);
  when(groupRuntime.getId()).thenReturn("10");
  when(groupRuntime.getCluster()).thenReturn(clusterRuntime);
  groupRuntimes.add(groupRuntime);

  //mocking clusterRuntime
  when(clusterRuntime.getGroups()).thenReturn(groupRuntimes);

  //mocking securityGroups
  SecurityGroup securityGroup = mock(SecurityGroup.class);
  List<SecurityGroup> securityGroupList = new ArrayList<>();
  securityGroupList.add(securityGroup);
  FluentIterable<SecurityGroup> securityGroupFluentIterable = FluentIterable.from(securityGroupList);

  when(novaContext.getSecurityGroupApi()).thenReturn(securityGroupApi);
  when(securityGroupApi.list()).thenReturn(securityGroupFluentIterable);
  when(securityGroup.getName()).thenReturn(uniqueGroup);

  NovaLauncher novaLauncher = new NovaLauncher(novaContext, sshKeyPair);
  novaLauncher.cleanup(cluster, clusterRuntime);
}
 
源代码17 项目: mongowp   文件: SimpleIterableDocumentProvider.java
SimpleIterableDocumentProvider(Iterable<E> documents) {
  this.documents = FluentIterable.from(documents);
}
 
源代码18 项目: newts   文件: FileIterable.java
public static FluentIterable<Path> fileTreeWalker(final Path root) {
    return FluentIterable.from(Iterables.concat(groupFilesByDir(root)));
}
 
源代码19 项目: bazel   文件: IterableCodecs.java
@Override
public FluentIterable deserialize(DeserializationContext context, CodedInputStream codedIn)
    throws SerializationException, IOException {
  return FluentIterable.from(IterableCodecs.deserialize(context, codedIn));
}
 
源代码20 项目: deadcode4j   文件: Utils.java
/**
 * Returns the given <code>Iterable</code> or an empty list if it is <code>null</code> as a {@link FluentIterable}.
 *
 * @since 2.0.0
 */
@Nonnull
public static <E> FluentIterable<E> emptyIfNull(@Nullable Iterable<E> iterable) {
    return FluentIterable.from(iterable == null ? Collections.<E>emptyList() : iterable);
}