List of usage examples for com.google.common.collect ImmutableList stream
default Stream<E> stream()
From source file:com.google.errorprone.bugpatterns.UnsafeFinalization.java
@Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { MethodSymbol sym = ASTHelpers.getSymbol(tree); // Match invocations of static native methods. if (sym == null || !sym.isStatic() || !Flags.asFlagSet(sym.flags()).contains(Flag.NATIVE)) { return NO_MATCH; }/*from w w w .j a v a 2s .com*/ // Find the enclosing method declaration where the invocation occurs. MethodTree method = enclosingMethod(state); if (method == null) { return NO_MATCH; } // Don't check native methods called from static methods and constructors: // static methods don't have an instance to finalize, and we shouldn't need to worry about // finalization during construction. MethodSymbol enclosing = ASTHelpers.getSymbol(method); if (enclosing == null || enclosing.isStatic() || enclosing.isConstructor()) { return NO_MATCH; } // Check if any arguments of the static native method are members (e.g. fields) of the enclosing // class. We're only looking for cases where the static native uses state of the enclosing class // that may become invalid after finalization. ImmutableList<Symbol> arguments = tree.getArguments().stream().map(ASTHelpers::getSymbol) .filter(x -> x != null).collect(toImmutableList()); if (arguments.stream() .filter(x -> EnumSet.of(TypeKind.INT, TypeKind.LONG) .contains(state.getTypes().unboxedTypeOrType(x.asType()).getKind())) .noneMatch(arg -> arg.isMemberOf(enclosing.enclClass(), state.getTypes()))) { // no instance state is passed to the native method return NO_MATCH; } if (arguments.stream().anyMatch(arg -> arg.getSimpleName().contentEquals("this") && arg.isMemberOf(enclosing.enclClass(), state.getTypes()))) { // the instance is passed to the native method return NO_MATCH; } Symbol finalizeSym = getFinalizer(state, enclosing.enclClass()); if (finalizeSym == null || finalizeSym.equals(enclosing)) { // Don't check native methods called from within the implementation of finalize. return NO_MATCH; } if (finalizeSym.enclClass().equals(state.getSymtab().objectType.asElement())) { // Inheriting finalize from Object doesn't count. return NO_MATCH; } boolean[] sawFence = { false }; new TreeScanner<Void, Void>() { @Override public Void visitMethodInvocation(MethodInvocationTree tree, Void unused) { if (FENCE_MATCHER.matches(tree, state)) { sawFence[0] = true; } return null; } }.scan(state.getPath().getCompilationUnit(), null); if (sawFence[0]) { // Ignore methods that contain a use of reachabilityFence. return NO_MATCH; } return describeMatch(tree); }
From source file:com.spectralogic.ds3autogen.python.generators.response.HeadResponseGenerator.java
/** * Gets all response codes/*from www . j av a 2s.c om*/ */ @Override public ImmutableList<Integer> getStatusCodes(final ImmutableList<Ds3ResponseCode> ds3ResponseCodes, final String requestName) { if (isEmpty(ds3ResponseCodes)) { throw new IllegalArgumentException(requestName + " must have response codes 200, and 404"); } final ImmutableList<Integer> codes = ds3ResponseCodes.stream().map(Ds3ResponseCode::getCode) .collect(GuavaCollectors.immutableList()); if (!codes.contains(200) || !codes.contains(404)) { throw new IllegalArgumentException( requestName + " should contain the response codes 200, and 404. Actual: " + codes); } if (codes.contains(403)) { return codes; } //If 403 is not in expected codes, add it, and sort the list final ImmutableList.Builder<Integer> builder = ImmutableList.builder(); builder.addAll(codes).add(403); return builder.build().stream().sorted().collect(GuavaCollectors.immutableList()); }
From source file:org.apache.james.jmap.methods.MessageAppender.java
private ImmutableList<MessageAttachment> getMessageAttachments(MailboxSession session, ImmutableList<Attachment> attachments) throws MailboxException { ThrowingFunction<Attachment, Optional<MessageAttachment>> toMessageAttachment = att -> messageAttachment( session, att);/* w w w .j av a 2 s . c o m*/ return attachments.stream().map(Throwing.function(toMessageAttachment).sneakyThrow()) .flatMap(OptionalUtils::toStream).collect(Guavate.toImmutableList()); }
From source file:com.spectralogic.ds3autogen.java.generators.responseparser.BaseResponseParserGenerator.java
/** * Gets the non-error response codes required to generate this response *///from w w w. j a v a 2s.c o m @Override public ImmutableList<ResponseCode> toResponseCodeList(final ImmutableList<Ds3ResponseCode> ds3ResponseCodes, final String responseName, final boolean hasPaginationHeaders) { final ImmutableList<Ds3ResponseCode> filteredResponseCodes = removeErrorResponseCodes(ds3ResponseCodes); final boolean hasResponsePayload = hasResponsePayload(filteredResponseCodes); return filteredResponseCodes.stream() .map(rc -> toResponseCode(rc, responseName, hasResponsePayload, hasPaginationHeaders)) .collect(GuavaCollectors.immutableList()); }
From source file:com.facebook.buck.android.GenerateStringResources.java
protected GenerateStringResources(BuildTarget buildTarget, ProjectFilesystem projectFilesystem, SourcePathRuleFinder ruleFinder, ImmutableList<FilteredResourcesProvider> filteredResourcesProviders) { super(buildTarget, projectFilesystem); this.ruleFinder = ruleFinder; this.filteredResourcesProviders = filteredResourcesProviders; this.filteredResources = filteredResourcesProviders.stream() .flatMap(provider -> provider.getResDirectories().stream()) .collect(ImmutableList.toImmutableList()); }
From source file:com.spectralogic.ds3autogen.python.generators.response.BaseResponseGenerator.java
/** * Gets all non error response codes// w w w . j a v a 2s . c o m */ @Override public ImmutableList<Integer> getStatusCodes(final ImmutableList<Ds3ResponseCode> ds3ResponseCodes, final String requestName) { if (isEmpty(ds3ResponseCodes)) { LOG.error("There are no response codes for request: " + requestName); return ImmutableList.of(); } return ds3ResponseCodes.stream().map(Ds3ResponseCode::getCode).filter(ResponsePayloadUtil::isNonErrorCode) .collect(GuavaCollectors.immutableList()); }
From source file:com.facebook.buck.jvm.kotlin.Kotlinc.java
default ImmutableList<Path> getExpandedSourcePaths(ProjectFilesystem projectFilesystem, ProjectFilesystemFactory projectFilesystemFactory, ImmutableSet<Path> kotlinSourceFilePaths, Optional<Path> workingDirectory) throws InterruptedException, IOException { // Add sources file or sources list to command ImmutableList.Builder<Path> sources = ImmutableList.builder(); for (Path path : kotlinSourceFilePaths) { String pathString = path.toString(); if (pathString.endsWith(".kt") || pathString.endsWith(".kts") || pathString.endsWith(".java")) { sources.add(path);// w w w. ja v a 2 s. c om } else if (pathString.endsWith(SRC_ZIP) || pathString.endsWith(SRC_JAR)) { // For a Zip of .java files, create a JavaFileObject for each .java entry. ImmutableList<Path> zipPaths = ArchiveFormat.ZIP.getUnarchiver().extractArchive( projectFilesystemFactory, projectFilesystem.resolve(path), projectFilesystem.resolve(workingDirectory.orElse(path)), ExistingFileMode.OVERWRITE); sources.addAll(zipPaths .stream().filter(input -> input.toString().endsWith(".kt") || input.toString().endsWith(".kts") || input.toString().endsWith(".java")) .iterator()); } } return sources.build(); }
From source file:com.facebook.buck.features.go.CGoLibrary.java
public static BuildRule create(BuildRuleParams params, BuildTarget buildTarget, ProjectFilesystem projectFilesystem, ActionGraphBuilder graphBuilder, SourcePathResolver pathResolver, CellPathResolver cellRoots, CxxBuckConfig cxxBuckConfig, GoPlatform platform, CgoLibraryDescriptionArg args, Iterable<BuildTarget> cxxDeps, Tool cgo) { SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(graphBuilder); CxxDeps allDeps = CxxDeps.builder().addDeps(cxxDeps).addPlatformDeps(args.getPlatformDeps()).build(); // generate C sources with cgo tool (go build writes c files to _obj dir) ImmutableMap<Path, SourcePath> headers = CxxDescriptionEnhancer.parseHeaders(buildTarget, graphBuilder, ruleFinder, pathResolver, Optional.of(platform.getCxxPlatform()), args); HeaderSymlinkTree headerSymlinkTree = getHeaderSymlinkTree(buildTarget, projectFilesystem, ruleFinder, graphBuilder, platform.getCxxPlatform(), cxxDeps, headers); ImmutableSet.Builder<SourcePath> cxxSourcesFromArg = ImmutableSet.builder(); ImmutableSet.Builder<SourcePath> goSourcesFromArg = ImmutableSet.builder(); for (SourceWithFlags srcWithFlags : args.getSrcs()) { SourcePath pth = srcWithFlags.getSourcePath(); String ext = Files.getFileExtension(pathResolver.getAbsolutePath(pth).toString()); if (CxxSource.Type.fromExtension(ext).equals(Optional.of(CxxSource.Type.C))) { cxxSourcesFromArg.add(pth);//from ww w . j av a 2s.c o m } else if (ext.equals("go")) { goSourcesFromArg.add(pth); } } CGoGenSource genSource = (CGoGenSource) graphBuilder .computeIfAbsent(buildTarget.withAppendedFlavors(InternalFlavor.of("cgo-gen-sources")), target -> new CGoGenSource(target, projectFilesystem, ruleFinder, pathResolver, goSourcesFromArg.build(), headerSymlinkTree, cgo, args.getCgoCompilerFlags(), platform)); // generated c files needs to be compiled and linked into a single object // file (equivalent of (_cgo_.o), includes: // * _cgo_export.o // * _cgo_main.o // * all of the *.cgo2.o CxxLink cgoBin = (CxxLink) graphBuilder.computeIfAbsent( buildTarget.withAppendedFlavors(InternalFlavor.of("cgo-first-step")), target -> nativeBinCompilation(target, projectFilesystem, graphBuilder, pathResolver, cellRoots, cxxBuckConfig, platform.getCxxPlatform(), args, new ImmutableList.Builder<BuildRule>().add(genSource) .addAll(allDeps.get(graphBuilder, platform.getCxxPlatform())).build(), new ImmutableMap.Builder<Path, SourcePath>().putAll(headers) .put(pathResolver.getAbsolutePath(genSource.getExportHeader()).getFileName(), genSource.getExportHeader()) .build(), new ImmutableList.Builder<SourcePath>().addAll(cxxSourcesFromArg.build()) .addAll(genSource.getCFiles()).addAll(genSource.getCgoFiles()).build(), args.getLinkerFlags())); // generate cgo_import.h with previously generated object file (_cgo.o) BuildRule cgoImport = graphBuilder.computeIfAbsent( buildTarget.withAppendedFlavors(InternalFlavor.of("cgo-gen-import")), target -> new CGoGenImport(target, projectFilesystem, ruleFinder, pathResolver, cgo, platform, // take first source file in the list to infer the package // name via go list goSourcesFromArg.build().iterator().next(), Objects.requireNonNull(cgoBin.getSourcePathToOutput()))); // filter out compiled object only for the sources we are interested in ImmutableList<String> linkableObjectFiles = Stream.concat( cxxSourcesFromArg.build().stream() .map(x -> pathResolver.getAbsolutePath(x).getFileName().toString()), ImmutableList.of(".cgo2.c", "_cgo_export.c").stream()).collect(ImmutableList.toImmutableList()); // generate final object file (equivalent of _all.o) which includes: // * _cgo_export.o // * all of the *.cgo2.o files ImmutableList<Arg> cxxArgs = ImmutableList.<Arg>builder().addAll(StringArg.from("-r", "-nostdlib")) .addAll(cgoBin.getArgs().stream().filter(FileListableLinkerInputArg.class::isInstance) .map(FileListableLinkerInputArg.class::cast).filter(arg -> { Path pth = pathResolver.getAbsolutePath(arg.getPath()); String fileName = pth.getFileName().toString(); return pth.toString().contains("cgo-first-step") && linkableObjectFiles.stream().anyMatch(x -> fileName.contains(x)); }).collect(ImmutableList.toImmutableList())) .build(); CxxLink cgoAllBin = (CxxLink) graphBuilder.computeIfAbsent( buildTarget.withAppendedFlavors(InternalFlavor.of("cgo-second-step")), target -> CxxLinkableEnhancer.createCxxLinkableBuildRule(cellRoots, cxxBuckConfig, platform.getCxxPlatform(), projectFilesystem, graphBuilder, ruleFinder, target, BuildTargetPaths.getGenPath(projectFilesystem, target, "%s/_all.o"), ImmutableMap.of(), cxxArgs, // collection of selected object files args.getLinkStyle().orElse(Linker.LinkableDepType.STATIC_PIC), CxxLinkOptions.of(), Optional.empty())); // output (referenced later on by GoCompile) provides: // * _cgo_gotypes.go // * _cgo_import.go // * all of the *.cgo1.go files // // the go sources should be appended to sources list and _all.o file should // be appended to the output binary (pack step) return graphBuilder.computeIfAbsent(buildTarget, target -> new CGoLibrary( params.withDeclaredDeps(ImmutableSortedSet.<BuildRule>naturalOrder() .addAll(ruleFinder.filterBuildRuleInputs(cgoAllBin.getSourcePathToOutput())) .addAll(ruleFinder.filterBuildRuleInputs(new Builder<SourcePath>() .addAll(genSource.getGoFiles()) .add(Objects.requireNonNull(cgoImport.getSourcePathToOutput())).build())) .build()).withoutExtraDeps(), target, projectFilesystem, new Builder<SourcePath>().addAll(genSource.getGoFiles()) .add(Objects.requireNonNull(cgoImport.getSourcePathToOutput())).build(), Objects.requireNonNull(cgoAllBin.getSourcePathToOutput()), Objects.requireNonNull(allDeps.get(graphBuilder, platform.getCxxPlatform())))); }
From source file:io.appform.nautilus.funnel.graphmanagement.ESEdgeBasedGraphBuilder.java
@Override public Graph build(final String tenant, Context analyticsContext, GraphRequest graphRequest) throws Exception { try {/*from w ww . jav a 2 s . c o m*/ SearchRequestBuilder sessionSummary = analyticsContext.getEsConnection().client() .prepareSearch(ESUtils.getAllIndicesForTenant(tenant)) //TODO::SELECT RELEVANT INDICES ONLY .setQuery(QueryBuilders.boolQuery() .filter(QueryBuilders.hasParentQuery(TypeUtils.typeName(Session.class), ESUtils.query(graphRequest)))) .setTypes(TypeUtils.typeName(StateTransition.class)).setFetchSource(false).setSize(0) .setIndicesOptions(IndicesOptions.lenientExpandOpen()) .addAggregation(AggregationBuilders.terms("from_nodes").field("from") .subAggregation(AggregationBuilders.terms("to_nodes").field("to").size(0))); SearchRequestBuilder stateTransitionSummary = analyticsContext.getEsConnection().client() .prepareSearch(ESUtils.getAllIndicesForTenant(tenant)).setQuery(ESUtils.query(graphRequest)) .setTypes(TypeUtils.typeName(Session.class)).setFetchSource(false).setSize(0) .setIndicesOptions(IndicesOptions.lenientExpandOpen()) .addAggregation(AggregationBuilders.terms("paths").field("normalizedPath").size(0)); log.debug("Session query: {}", sessionSummary); log.debug("State Query: {}", stateTransitionSummary); MultiSearchResponse multiSearchResponse = analyticsContext.getEsConnection().client() .prepareMultiSearch().add(sessionSummary).add(stateTransitionSummary) .setIndicesOptions(IndicesOptions.lenientExpandOpen()).execute().actionGet(); List<GraphEdge> edges = Lists.newArrayList(); { SearchResponse edgeGroupingResponse = multiSearchResponse.getResponses()[0].getResponse(); Aggregations aggregations = edgeGroupingResponse.getAggregations(); if (null == aggregations) { return Graph.builder().build(); } Terms terms = aggregations.get("from_nodes"); for (Terms.Bucket fromBucket : terms.getBuckets()) { final String fromNodeName = PathUtils.transformBack(fromBucket.getKey().toString()); Terms toTerms = fromBucket.getAggregations().get("to_nodes"); for (Terms.Bucket toBucket : toTerms.getBuckets()) { final String toNodeName = PathUtils.transformBack(toBucket.getKey().toString()); edges.add(GraphEdge.builder().from(fromNodeName).to(toNodeName) .value(toBucket.getDocCount()).build()); } } } Map<String, GraphNode> vertices = Maps.newHashMap(); int nodeCounter = 0; ImmutableList.Builder<FlatPath> flatPathListBuilder = ImmutableList.builder(); { SearchResponse response = multiSearchResponse.getResponses()[1].getResponse(); Aggregations aggregations = response.getAggregations(); Terms terms = aggregations.get("paths"); for (Terms.Bucket buckets : terms.getBuckets()) { final String flatPath = PathUtils.transformBack(buckets.getKey().toString()); final long count = buckets.getDocCount(); final String pathNodes[] = flatPath.split(Constants.PATH_STATE_SEPARATOR); flatPathListBuilder.add(FlatPath.builder().path(flatPath).count(count).build()); for (final String pathNode : pathNodes) { final String original = PathUtils.transformBack(pathNode); if (!vertices.containsKey(original)) { vertices.put(pathNode, GraphNode.builder().id(nodeCounter++).name(original).build()); } } } } ImmutableList<FlatPath> paths = flatPathListBuilder.build(); PathUtils .rankNodes( paths.stream().map(FlatPath::getPath).collect(Collectors.toCollection(ArrayList::new))) .entrySet().stream().forEach(rank -> { String nodeName = rank.getKey(); int nodeRank = rank.getValue(); if (vertices.containsKey(nodeName)) { GraphNode node = vertices.get(nodeName); node.setRank(nodeRank); } }); ArrayList<GraphNode> verticesList = new ArrayList<>(vertices.values()); verticesList.sort((GraphNode lhs, GraphNode rhs) -> Integer.compare(lhs.getId(), rhs.getId())); return Graph.builder().vertices(verticesList).edges(edges).build(); } catch (Exception e) { log.error("Error running grouping: ", e); throw new NautilusException(ErrorMessageTable.ErrorCode.ANALYTICS_ERROR, e); } }
From source file:org.mskcc.shenkers.control.track.gene.GTFGeneModelProvider.java
private void createGtfBgz(File gtf_file, File gtf_bgz_file) throws IOException { logger.info("reading {}", gtf_file.getAbsolutePath()); AbstractFeatureReader<GTFContext, LineIterator> afr = AbstractFeatureReader .getFeatureReader(gtf_file.getAbsolutePath(), codec, false); CloseableTribbleIterator<GTFContext> iterator = afr.iterator(); List<GTFContext> gtf = new ArrayList<>(); while (iterator.hasNext()) { GTFContext next = iterator.next(); gtf.add(next);//www. j ava 2 s. c o m } ImmutableListMultimap<String, GTFContext> transcript_id_multimap = Multimaps.index(gtf.iterator(), GTFContext::getTranscriptId); logger.info("adding transcript ranges"); gtf.addAll(transcript_id_multimap.keySet().stream().map(key -> { System.out.println(key); ImmutableList<GTFContext> contexts = transcript_id_multimap.get(key); Range<Integer> span = contexts.stream().map(c -> Range.closed(c.getStart(), c.getEnd())) .collect(new RangeSetCollector()).span(); GTFContext context = new GTFContext(contexts.get(0).getChr(), span.lowerEndpoint(), span.upperEndpoint()); context.setFeature("transcript"); context.setFrame("."); context.setName("."); context.setScore("."); context.setSource("."); context.setStrand('.'); context.setAttributes(String.format("transcript_id \"%s\";", key)); return context; }).collect(Collectors.toList())); logger.info("sorting"); Collections.sort(gtf, new CoordinateOrderComparator()); logger.info("writing to compressed output stream"); BlockCompressedOutputStream os = new BlockCompressedOutputStream(gtf_bgz_file); Writer w = new OutputStreamWriter(os); for (GTFContext feature : gtf) { w.write(codec.encodeToString(feature)); } w.close(); }