下面列出了com.google.common.collect.FluentIterable#from ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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();
}
@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);
}
@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);
}
@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);
}
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);
}
@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();
}
};
}
/**
* 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()
));
}
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);
}
@Override
public FluentIterable<Resource> fromResource(Resource resource) {
return FluentIterable.from(resource.resources());
}
@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));
}
@Override
public Iterable<Group> getExtraneousGroups(DeviceId deviceId) {
// flatten and make iterator unmodifiable
return FluentIterable.from(
getExtraneousGroupIdTable(deviceId).values());
}
private FluentIterable<ValueAttribute> attributes() {
return FluentIterable.from(attributes);
}
@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());
}
@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);
}
SimpleIterableDocumentProvider(Iterable<E> documents) {
this.documents = FluentIterable.from(documents);
}
public static FluentIterable<Path> fileTreeWalker(final Path root) {
return FluentIterable.from(Iterables.concat(groupFilesByDir(root)));
}
@Override
public FluentIterable deserialize(DeserializationContext context, CodedInputStream codedIn)
throws SerializationException, IOException {
return FluentIterable.from(IterableCodecs.deserialize(context, codedIn));
}
/**
* 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);
}