com.google.common.collect.FluentIterable Java Examples
The following examples show how to use
com.google.common.collect.FluentIterable.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TMServiceTest.java From mojito with Apache License 2.0 | 6 votes |
private String getExpectedLocalizedXLIFFContent(final String targetLocaleBcp47Tag, Pair<TMTextUnit, TMTextUnitVariant>... tmTextUnitsWithVariants) { Function<Pair<TMTextUnit, TMTextUnitVariant>, TextUnit> toTextUnitFunction = new Function<Pair<TMTextUnit, TMTextUnitVariant>, TextUnit>() { @Override public TextUnit apply(Pair<TMTextUnit, TMTextUnitVariant> input) { return createTextUnitFromTmTextUnitsWithVariant(targetLocaleBcp47Tag, input.getLeft(), input.getRight()); } }; List<Pair<TMTextUnit, TMTextUnitVariant>> tmTextUnitWithVariantList = Arrays.asList(tmTextUnitsWithVariants); List<TextUnit> textUnitList = FluentIterable.from(tmTextUnitWithVariantList).transform(toTextUnitFunction).toList(); return xliffDataFactory.generateTargetXliff(textUnitList, targetLocaleBcp47Tag); }
Example #2
Source File: ExecutionPhasesTask.java From Elasticsearch with Apache License 2.0 | 6 votes |
@Override public void start() { FluentIterable<NodeOperation> nodeOperations = FluentIterable.from(nodeOperationTrees) .transformAndConcat(new Function<NodeOperationTree, Iterable<? extends NodeOperation>>() { @Nullable @Override public Iterable<? extends NodeOperation> apply(NodeOperationTree input) { return input.nodeOperations(); } }); Map<String, Collection<NodeOperation>> operationByServer = NodeOperationGrouper.groupByServer(nodeOperations); InitializationTracker initializationTracker = new InitializationTracker(operationByServer.size()); List<Tuple<ExecutionPhase, RowReceiver>> handlerPhases = createHandlerPhases(initializationTracker); try { setupContext(operationByServer, handlerPhases, initializationTracker); } catch (Throwable throwable) { for (SettableFuture<TaskResult> result : results) { result.setException(throwable); } } }
Example #3
Source File: ConfigHelper.java From sfs with Apache License 2.0 | 6 votes |
public static Iterable<String> getArrayFieldOrEnv(JsonObject config, String name, Iterable<String> defaultValue) { String envVar = formatEnvVariable(name); //USED_ENV_VARS.add(envVar); if (config.containsKey(name)) { JsonArray values = config.getJsonArray(name); if (values != null) { Iterable<String> iterable = FluentIterable.from(values) .filter(Predicates.notNull()) .filter(input -> input instanceof String) .transform(input -> input.toString()); log(name, envVar, name, iterable); return iterable; } } else { String value = System.getenv(envVar); if (value != null) { log(name, envVar, envVar, value); return Splitter.on(',').split(value); } } log(name, envVar, null, defaultValue); return defaultValue; }
Example #4
Source File: FilterToolHelp.java From circus-train with Apache License 2.0 | 6 votes |
@Override public String toString() { Iterable<String> errorMessages = FluentIterable.from(errors).transform(OBJECT_ERROR_TO_TABBED_MESSAGE); StringBuilder help = new StringBuilder(500) .append("Usage: check-filters.sh --config=<config_file>[,<config_file>,...]") .append(System.lineSeparator()) .append("Errors found in the provided configuration file:") .append(System.lineSeparator()) .append(Joiner.on(System.lineSeparator()).join(errorMessages)) .append(System.lineSeparator()) .append("Configuration file help:") .append(System.lineSeparator()) .append(TAB) .append("For more information and help please refer to ") .append("https://github.com/HotelsDotCom/circus-train/tree/master/circus-train-tool-parent"); return help.toString(); }
Example #5
Source File: EmbeddedMetaStore.java From pentaho-kettle with Apache License 2.0 | 6 votes |
@Override public List<String> getNamespaces() throws MetaStoreException { return MetaStoreUtil.executeLockedOperation( readLock(), new Callable<List<String>>() { @Override public List<String> call() throws Exception { return FluentIterable.from( attributesInterface.getAttributesMap().keySet() ) .filter( new Predicate<String>() { @Override public boolean apply( String groupName ) { return groupName.startsWith( METASTORE_PREFIX ); } } ) .transform( new Function<String, String>() { @Override public String apply( String input ) { return input.substring( METASTORE_PREFIX.length() ); } } ) .toList(); } } ); }
Example #6
Source File: BadCommandTargets.java From estatio with Apache License 2.0 | 6 votes |
@Action(semantics = SemanticsOf.SAFE, restrictTo = RestrictTo.PROTOTYPING) public List<BadTarget> findBadCommandTargets() { Set<String> badObjectTypes = Sets.newTreeSet(); List<Map<String, Object>> rows = isisJdoSupport .executeSql("select distinct(substring(target, 1, charindex(':', target)-1)) as objectType from isiscommand.Command order by 1"); for (Map<String, Object> row : rows) { String targetStr = (String) row.get("objectType"); addIfBad(badObjectTypes, targetStr); } return Lists.newArrayList( FluentIterable.from(badObjectTypes) .transform(x -> new BadTarget(x)) .toList()); }
Example #7
Source File: ValidateSystemOutput.java From tac-kbp-eal with MIT License | 6 votes |
/** * Warns about CAS offsets for Responses being inconsistent with actual document text for non-TIME * roles */ private void warnOnMissingOffsets(final File systemOutputStoreFile, final Symbol docID, final ImmutableSet<Response> responses, final Map<Symbol, File> docIDMap) throws IOException { final String text = Files.asCharSource(docIDMap.get(docID), Charsets.UTF_8).read(); for (final Response r : FluentIterable.from(responses) .filter(Predicates.compose(not(equalTo(TIME)), ResponseFunctions.role()))) { final KBPString cas = r.canonicalArgument(); final String casTextInRaw = resolveCharOffsets(cas.charOffsetSpan(), docID, text).replaceAll("\\s+", " "); // allow whitespace if (!casTextInRaw.contains(cas.string())) { log.warn("Warning for {} - response {} CAS does not match text span of {} ", systemOutputStoreFile.getAbsolutePath(), renderResponse(r, text), casTextInRaw); } } }
Example #8
Source File: SameEventTypeLinker.java From tac-kbp-eal with MIT License | 6 votes |
private ResponseLinking linkResponses(final Symbol docId, final Iterable<Response> responses) { final Predicate<Response> HasRelevantRealis = compose(in(realisesWhichMustBeAligned), ResponseFunctions.realis()); final ImmutableSet<Response> systemResponsesAlignedRealis = FluentIterable.from(responses).filter(HasRelevantRealis).toSet(); final Multimap<Symbol, Response> responsesByEventType = Multimaps.index(systemResponsesAlignedRealis, ResponseFunctions.type()); final ImmutableSet.Builder<ResponseSet> ret = ImmutableSet.builder(); for (final Collection<Response> responseSet : responsesByEventType.asMap().values()) { ret.add(ResponseSet.from(responseSet)); } return ResponseLinking.builder().docID(docId).addAllResponseSets(ret.build()).build(); }
Example #9
Source File: AttributeAggregate.java From attic-aurora with Apache License 2.0 | 6 votes |
@VisibleForTesting static AttributeAggregate create( final Supplier<Iterable<IScheduledTask>> taskSupplier, final AttributeStore attributeStore) { final Function<String, Iterable<IAttribute>> getHostAttributes = host -> { // Note: this assumes we have access to attributes for hosts where all active tasks // reside. requireNonNull(host); return attributeStore.getHostAttributes(host).get().getAttributes(); }; return create(Suppliers.compose( tasks -> FluentIterable.from(tasks) .transform(Tasks::scheduledToSlaveHost) .transformAndConcat(getHostAttributes), taskSupplier)); }
Example #10
Source File: AppleResources.java From buck with Apache License 2.0 | 6 votes |
/** * Collect resources from recursive dependencies. * * @param targetGraph The {@link TargetGraph} containing the node and its dependencies. * @param targetNode {@link TargetNode} at the tip of the traversal. * @return The recursive resource buildables. */ public static ImmutableSet<AppleResourceDescriptionArg> collectRecursiveResources( XCodeDescriptions xcodeDescriptions, TargetGraph targetGraph, Optional<AppleDependenciesCache> cache, TargetNode<?> targetNode, RecursiveDependenciesMode mode) { return FluentIterable.from( AppleBuildRules.getRecursiveTargetNodeDependenciesOfTypes( xcodeDescriptions, targetGraph, cache, mode, targetNode, ImmutableSet.of(AppleResourceDescription.class))) .transform(input -> (AppleResourceDescriptionArg) input.getConstructorArg()) .toSet(); }
Example #11
Source File: AddEqualsAndHashCodeWithSubclasses.java From raml-java-tools with Apache License 2.0 | 6 votes |
private void createHashCode(List<FieldSpec> specs, TypeSpec.Builder incoming) { String fields = FluentIterable.from(specs).transform(new Function<FieldSpec, String>() { @Nullable @Override public String apply(@Nullable FieldSpec fieldSpec) { return fieldSpec.name; } }).join(Joiner.on(",")); MethodSpec.Builder method = MethodSpec.methodBuilder("hashCode") .addAnnotation(ClassName.get(Override.class)).addModifiers(Modifier.PUBLIC) .returns(TypeName.INT) .addCode(CodeBlock.builder().addStatement("return $T.hash($L)", Objects.class, fields).build()); incoming.addMethod( method.build() ); }
Example #12
Source File: EntitiesYamlIntegrationTest.java From brooklyn-library with Apache License 2.0 | 6 votes |
@Test(groups = "Integration") public void testStartTomcatCluster() throws Exception { Entity app = createAndStartApplication(loadYaml("test-tomcat-cluster.yaml")); waitForApplicationTasks(app); assertNotNull(app); assertEquals(app.getChildren().size(), 1); final Entity entity = Iterables.getOnlyElement(app.getChildren()); assertTrue(entity instanceof ControlledDynamicWebAppCluster, "entity="+entity); ControlledDynamicWebAppCluster cluster = (ControlledDynamicWebAppCluster) entity; assertTrue(cluster.getController() instanceof NginxController, "controller="+cluster.getController()); Iterable<TomcatServer> tomcats = FluentIterable.from(cluster.getCluster().getMembers()).filter(TomcatServer.class); assertEquals(Iterables.size(tomcats), 2); for (TomcatServer tomcat : tomcats) { assertTrue(tomcat.getAttribute(TomcatServer.SERVICE_UP), "serviceup"); } EntitySpec<?> spec = entity.getConfig(DynamicCluster.MEMBER_SPEC); assertNotNull(spec); assertEquals(spec.getType(), TomcatServer.class); assertEquals(spec.getConfig().get(DynamicCluster.QUARANTINE_FAILED_ENTITIES), Boolean.FALSE); assertEquals(spec.getConfig().get(DynamicCluster.INITIAL_QUORUM_SIZE), 2); }
Example #13
Source File: InjectingSerializer.java From dremio-oss with Apache License 2.0 | 6 votes |
protected CachedField[] transform(final CachedField[] fields) { return FluentIterable .from(Arrays.asList(fields)) .transform(new Function<CachedField, CachedField>() { @Nullable @Override public CachedField apply(@Nullable final CachedField field) { final CachedField newField = mapping.findInjection(field.getField().getType()) .transform(new Function<Injection, CachedField>() { @Nullable @Override public CachedField apply(@Nullable final Injection injection) { return new InjectingCachedField(field, injection.getValue()); } }) .or(field); return newField; } }) .toArray(CachedField.class); }
Example #14
Source File: AddEqualsAndHashCode.java From raml-java-tools with Apache License 2.0 | 6 votes |
private void createHashCode(List<FieldSpec> specs, TypeSpec.Builder incoming) { String fields = FluentIterable.from(specs).transform(new Function<FieldSpec, String>() { @Nullable @Override public String apply(@Nullable FieldSpec fieldSpec) { return fieldSpec.name; } }).join(Joiner.on(",")); MethodSpec.Builder method = MethodSpec.methodBuilder("hashCode") .addAnnotation(ClassName.get(Override.class)).addModifiers(Modifier.PUBLIC) .returns(TypeName.INT) .addCode(CodeBlock.builder().addStatement("return $T.hash($L)", Objects.class, fields).build()); incoming.addMethod( method.build() ); }
Example #15
Source File: Proto.java From immutables with Apache License 2.0 | 6 votes |
@Value.Derived @Value.Auxiliary public Set<EncodingInfo> encodings() { if (qualifiedName().endsWith("Enabled") || CustomImmutableAnnotations.annotations().contains(qualifiedName()) || style().isPresent()) { // See if it is encoding enabled itself Optional<EncodingInfo> encoding = EncMetadataMirror.find(element()).transform(ENCODING_INFLATER); if (encoding.isPresent()) { return encoding.asSet(); } // trying to find it as meta-meta annotation List<EncodingInfo> result = new ArrayList<>(); for (AnnotationMirror m : element().getAnnotationMirrors()) { MetaAnnotated metaAnnotated = MetaAnnotated.from(m, environment()); result.addAll(metaAnnotated.encodings()); } if (!result.isEmpty()) { return FluentIterable.from(result).toSet(); } } return ImmutableSet.of(); }
Example #16
Source File: DiskRunManager.java From dremio-oss with Apache License 2.0 | 6 votes |
public int getMedianMaxBatchSize() { if (diskRuns.size() == 0) { return 0; } return FluentIterable.from(diskRuns) .transform(new Function<DiskRun, Integer>() { @Override public Integer apply(DiskRun diskRun) { return diskRun.largestBatch; } }) .toSortedList(new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return Integer.compare(o1, o2); } }) .get(diskRuns.size() / 2); }
Example #17
Source File: ComparisonToolHelp.java From circus-train with Apache License 2.0 | 6 votes |
@Override public String toString() { Iterable<String> errorMessages = FluentIterable.from(errors).transform(OBJECT_ERROR_TO_TABBED_MESSAGE); StringBuilder help = new StringBuilder(500) .append("Usage: compare-tables.sh --config=<config_file>[,<config_file>,...] --" + ComparisonToolArgs.OUTPUT_FILE + "=<output_file> [--" + ComparisonToolArgs.SOURCE_PARTITION_BATCH_SIZE + "=1000] [--" + ComparisonToolArgs.REPLICA_PARTITION_BUFFER_SIZE + "=1000]") .append(System.lineSeparator()) .append("Errors found in the provided configuration file:") .append(System.lineSeparator()) .append(Joiner.on(System.lineSeparator()).join(errorMessages)) .append(System.lineSeparator()) .append("Configuration file help:") .append(System.lineSeparator()) .append(TAB) .append("For more information and help please refer to ") .append("https://github.com/HotelsDotCom/circus-train/blob/master/circus-train-tool/" + "circus-train-comparison-tool/README.md"); return help.toString(); }
Example #18
Source File: ByEventTypeResultWriter.java From tac-kbp-eal with MIT License | 5 votes |
private void writeOverallArgumentScoresForTransformedResults( final List<EALScorer2015Style.Result> perDocResults, final Function<EALScorer2015Style.ArgResult, EALScorer2015Style.ArgResult> filterFunction, final File outputDir) throws IOException { // this has a lot of repetition with writeBothScores // we'd like to fix this eventually final ImmutableList<EALScorer2015Style.ArgResult> relevantArgumentScores = FluentIterable.from(perDocResults).transform(GET_ARG_SCORES_ONLY) .transform(filterFunction) .toList(); PerDocResultWriter.writeArgPerDoc(relevantArgumentScores, new File(outputDir, "scoresByDocument.txt")); final ImmutableAggregate2015ArgScoringResult argScores = AggregateResultWriter.computeArgScoresFromArgResults(relevantArgumentScores); Files.asCharSink(new File(outputDir, "aggregateScore.txt"), Charsets.UTF_8).write( String .format("%30s:%8.2f\n", "Aggregate argument precision", argScores.precision()) + String.format("%30s:%8.2f\n", "Aggregate argument recall", argScores.recall()) + String .format("%30s:%8.2f\n\n", "Aggregate argument score", argScores.overall())); final File jsonFile = new File(outputDir, "aggregateScore.json"); final JacksonSerializer jacksonSerializer = JacksonSerializer.builder().forJson() .prettyOutput().build(); jacksonSerializer.serializeTo(argScores, GZIPByteSink.gzipCompress(Files.asByteSink(jsonFile))); }
Example #19
Source File: LogTestRule.java From ArchUnit with Apache License 2.0 | 5 votes |
private Iterable<RecordedLogEvent> filterByLevel(List<RecordedLogEvent> events, final Level level) { return FluentIterable.from(events).filter(new Predicate<RecordedLogEvent>() { @Override public boolean apply(RecordedLogEvent input) { return input.getLevel().equals(level); } }); }
Example #20
Source File: QuotaManager.java From attic-aurora with Apache License 2.0 | 5 votes |
private static ResourceBag getNonCronConsumption( Map<IJobKey, IJobUpdateInstructions> updatesByKey, FluentIterable<IAssignedTask> tasks, final Predicate<ITaskConfig> configFilter) { // 1. Get all active tasks that belong to jobs without active updates OR unaffected by an // active update working set. An example of the latter would be instances not updated by // the update due to being already in desired state or outside of update range (e.g. // not in JobUpdateInstructions.updateOnlyTheseInstances). Calculate consumed resources // as "nonUpdateConsumption". // // 2. Calculate consumed resources from instances affected by the active job updates as // "updateConsumption". // // 3. Add up the two to yield total consumption. ResourceBag nonUpdateConsumption = fromTasks(tasks .filter(buildNonUpdatingTasksFilter(updatesByKey)) .transform(IAssignedTask::getTask)); final Predicate<IInstanceTaskConfig> instanceFilter = compose(configFilter, IInstanceTaskConfig::getTask); ResourceBag updateConsumption = addAll(Iterables.transform(updatesByKey.values(), updateResources(instanceFilter))); return nonUpdateConsumption.add(updateConsumption); }
Example #21
Source File: JavaClassDependencies.java From ArchUnit with Apache License 2.0 | 5 votes |
private Set<Dependency> inheritanceDependenciesFromSelf() { ImmutableSet.Builder<Dependency> result = ImmutableSet.builder(); for (JavaClass superType : FluentIterable.from(javaClass.getInterfaces()).append(javaClass.getSuperClass().asSet())) { result.add(Dependency.fromInheritance(javaClass, superType)); } return result.build(); }
Example #22
Source File: DumpUtils.java From android-test with Apache License 2.0 | 5 votes |
private static Predicate<MethodData> runnerFilter(TestRelatedClassData testData) { boolean hasRunWith = FluentIterable.from(testData.aggregatedClassAnnotations.get()) .anyMatch(HAS_RUN_WITH_ANNOTATION); if (hasRunWith) { return IS_J4_TEST_METHOD; } if (testData.descendsFromJUnit3TestCase) { return IS_J3_TEST_METHOD; } return Predicates.<MethodData>alwaysFalse(); }
Example #23
Source File: AllResourceSelectorTest.java From raml-java-tools with Apache License 2.0 | 5 votes |
@Test public void fromResource() throws Exception { when(resource.resources()).thenReturn(Collections.singletonList(subResource)); AllResourceSelector allResourceSelector = new AllResourceSelector(); FluentIterable<Resource> apiElements = allResourceSelector.fromResource(resource); assertThat(apiElements, containsInAnyOrder(subResource)); verify(resource).resources(); verify(subResource).resources(); }
Example #24
Source File: WindowFunction.java From morf with Apache License 2.0 | 5 votes |
@Override public Builder partitionBy(AliasedField... partitionByFields) { if(partitionByFields == null || partitionByFields.length == 0) { throw new IllegalArgumentException("No partitionBy fields specified"); } this.partitionBy.addAll(FluentIterable.from(partitionByFields).toList()); return this; }
Example #25
Source File: NovaLauncherTest.java From karamel with Apache License 2.0 | 5 votes |
@Test public void uploadSSHPublicKeyAndCreate() throws KaramelException { String keypairName = "pepeKeyPair"; KeyPair pair = mock(KeyPair.class); List<KeyPair> keyPairList = new ArrayList<>(); FluentIterable<KeyPair> keys = FluentIterable.from(keyPairList); when(keyPairApi.list()).thenReturn(keys); when(keyPairApi.createWithPublicKey(keypairName, sshKeyPair.getPublicKey())).thenReturn(pair); NovaLauncher novaLauncher = new NovaLauncher(novaContext, sshKeyPair); boolean uploadSuccessful = novaLauncher.uploadSshPublicKey(keypairName, nova, false); assertTrue(uploadSuccessful); }
Example #26
Source File: HttpTemplateParserTest.java From api-compiler with Apache License 2.0 | 5 votes |
private void assertParsingFailure(final String path, int configVersion, String... expectedErrors) { SimpleDiagCollector diag = new SimpleDiagCollector(); new HttpTemplateParser(diag, TEST_LOCATION, path, configVersion).parse(); List<Diag> expectedDiagErrors = FluentIterable.from(Arrays.asList(expectedErrors)) .transform(new Function<String, Diag>() { @Override public Diag apply(String input) { return Diag.error(TEST_LOCATION, "In path template '" + path + "': " + input); }}).toList(); List<Diag> actualErrors = diag.getErrors(); Assert.assertEquals(expectedDiagErrors, actualErrors); }
Example #27
Source File: ReadOnlySchedulerImpl.java From attic-aurora with Apache License 2.0 | 5 votes |
@Override public Response getJobSummary(@Nullable String maybeNullRole) { Optional<String> ownerRole = Optional.ofNullable(maybeNullRole); Multimap<IJobKey, IScheduledTask> tasks = getTasks(maybeRoleScoped(ownerRole)); Map<IJobKey, IJobConfiguration> jobs = getJobs(ownerRole, tasks); Function<IJobKey, JobSummary> makeJobSummary = jobKey -> { IJobConfiguration job = jobs.get(jobKey); JobSummary summary = new JobSummary() .setJob(job.newBuilder()) .setStats(Jobs.getJobStats(tasks.get(jobKey)).newBuilder()); if (job.isSetCronSchedule()) { CrontabEntry crontabEntry = CrontabEntry.parse(job.getCronSchedule()); Optional<Date> nextRun = cronPredictor.predictNextRun(crontabEntry); return nextRun.map(date -> summary.setNextCronRunMs(date.getTime())).orElse(summary); } else { return summary; } }; ImmutableSet<JobSummary> jobSummaries = FluentIterable.from(jobs.keySet()).transform(makeJobSummary).toSet(); return ok(Result.jobSummaryResult(new JobSummaryResult().setSummaries(jobSummaries))); }
Example #28
Source File: AccelerationManagerImpl.java From dremio-oss with Apache License 2.0 | 5 votes |
private List<ReflectionDimensionField> toDimensionFields(List<SqlCreateReflection.NameAndGranularity> fields) { return FluentIterable.from(AccelerationUtils.selfOrEmpty(fields)) .transform(new Function<SqlCreateReflection.NameAndGranularity, ReflectionDimensionField>() { @Nullable @Override public ReflectionDimensionField apply(@Nullable final SqlCreateReflection.NameAndGranularity input) { final DimensionGranularity granularity = input.getGranularity() == SqlCreateReflection.Granularity.BY_DAY ? DimensionGranularity.DATE : DimensionGranularity.NORMAL; return new ReflectionDimensionField() .setName(input.getName()) .setGranularity(granularity); } }) .toList(); }
Example #29
Source File: ObjectPluginContextImpl.java From raml-java-tools with Apache License 2.0 | 5 votes |
@Override public Set<CreationResult> childClasses(String ramlTypeName) { return FluentIterable.from(generationContext.childClasses(ramlTypeName)).transform(new Function<String, CreationResult>() { @Nullable @Override public CreationResult apply(@Nullable String input) { return generationContext.findCreatedType(input, null); } }).toSet(); }
Example #30
Source File: TaskStateMachineTest.java From attic-aurora with Apache License 2.0 | 5 votes |
private void legalTransition(TaskState state, Set<SideEffect.Action> expectedActions) { ScheduleStatus previousState = stateMachine.getPreviousState(); TransitionResult result = stateMachine.updateState(state.getStatus()); assertEquals("Transition to " + state + " was not successful", SUCCESS, result.getResult()); assertNotEquals(previousState, stateMachine.getPreviousState()); assertEquals( FluentIterable.from(expectedActions).transform(TO_SIDE_EFFECT).toSet(), result.getSideEffects()); }