List of usage examples for com.google.common.collect ImmutableList isEmpty
boolean isEmpty();
From source file:com.facebook.buck.android.AndroidBinaryBuildable.java
private AbstractExecutionStep createAssetLibrariesMetadataStep(Path libSubdirectory, String metadataFilename, APKModule module, ImmutableSortedSet.Builder<Path> inputAssetLibrariesBuilder) { return new AbstractExecutionStep("write_metadata_for_asset_libraries_" + module.getName()) { @Override/*from ww w . ja va 2 s . c o m*/ public StepExecutionResult execute(ExecutionContext context) throws IOException { ProjectFilesystem filesystem = getProjectFilesystem(); // Walk file tree to find libraries filesystem.walkRelativeFileTree(libSubdirectory, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (!file.toString().endsWith(".so")) { throw new IOException("unexpected file in lib directory"); } inputAssetLibrariesBuilder.add(file); return FileVisitResult.CONTINUE; } }); // Write a metadata ImmutableList.Builder<String> metadataLines = ImmutableList.builder(); Path metadataOutput = libSubdirectory.resolve(metadataFilename); for (Path libPath : inputAssetLibrariesBuilder.build()) { // Should return something like x86/libfoo.so Path relativeLibPath = libSubdirectory.relativize(libPath); long filesize = filesystem.getFileSize(libPath); String desiredOutput = relativeLibPath.toString(); String checksum = filesystem.computeSha256(libPath); metadataLines.add(desiredOutput + ' ' + filesize + ' ' + checksum); } ImmutableList<String> metadata = metadataLines.build(); if (!metadata.isEmpty()) { filesystem.writeLinesToPath(metadata, metadataOutput); } return StepExecutionResults.SUCCESS; } }; }
From source file:com.google.idea.blaze.java.sync.source.SourceDirectoryCalculator.java
public ImmutableList<BlazeContentEntry> calculateContentEntries(Project project, BlazeContext context, WorkspaceRoot workspaceRoot, ArtifactLocationDecoder artifactLocationDecoder, Collection<WorkspacePath> rootDirectories, Collection<SourceArtifact> sources, Map<TargetKey, ArtifactLocation> javaPackageManifests) { ManifestFilePackageReader manifestFilePackageReader = Scope.push(context, (childContext) -> { childContext.push(new TimingScope("ReadPackageManifests")); Map<TargetKey, Map<ArtifactLocation, String>> manifestMap = PackageManifestReader.getInstance() .readPackageManifestFiles(project, childContext, artifactLocationDecoder, javaPackageManifests, packageReaderExecutorService); return new ManifestFilePackageReader(manifestMap); });/*from w ww . j a v a 2 s.c o m*/ final List<JavaPackageReader> javaPackageReaders = Lists.newArrayList(manifestFilePackageReader, JavaSourcePackageReader.getInstance(), generatedFileJavaPackageReader); Collection<SourceArtifact> nonGeneratedSources = filterGeneratedArtifacts(sources); // Sort artifacts and excludes into their respective workspace paths Multimap<WorkspacePath, SourceArtifact> sourcesUnderDirectoryRoot = sortArtifactLocationsByRootDirectory( context, rootDirectories, nonGeneratedSources); List<BlazeContentEntry> result = Lists.newArrayList(); Scope.push(context, (childContext) -> { childContext.push(new TimingScope("CalculateSourceDirectories")); for (WorkspacePath workspacePath : rootDirectories) { File contentRoot = workspaceRoot.fileForPath(workspacePath); ImmutableList<BlazeSourceDirectory> sourceDirectories = calculateSourceDirectoriesForContentRoot( context, workspaceRoot, artifactLocationDecoder, workspacePath, sourcesUnderDirectoryRoot.get(workspacePath), javaPackageReaders); if (!sourceDirectories.isEmpty()) { result.add(new BlazeContentEntry(contentRoot, sourceDirectories)); } } Collections.sort(result, (lhs, rhs) -> lhs.contentRoot.compareTo(rhs.contentRoot)); }); return ImmutableList.copyOf(result); }
From source file:com.google.errorprone.bugpatterns.CatchFail.java
Optional<Fix> deleteFix(TryTree tree, ImmutableList<CatchTree> catchBlocks, VisitorState state) { SuggestedFix.Builder fix = SuggestedFix.builder(); if (tree.getFinallyBlock() != null || catchBlocks.size() < tree.getCatches().size()) { // If the try statement has a finally region, or other catch blocks, delete only the // unnecessary blocks. catchBlocks.forEach(fix::delete); } else {//from www .j ava2 s.com // The try statement has no finally region and all catch blocks are unnecessary. Replace it // with the try statements, deleting all catches. List<? extends StatementTree> tryStatements = tree.getBlock().getStatements(); // If the try block is empty, all of the catches are dead, so just delete the whole try and // don't modify the signature of the method if (tryStatements.isEmpty()) { return Optional.of(fix.delete(tree).build()); } else { String source = state.getSourceCode().toString(); // Replace the full region to work around a GJF partial formatting bug that prevents it from // re-indenting unchanged lines. This means that fixes may overlap, but that's (hopefully) // unlikely. // TODO(b/24140798): emit more precise replacements if GJF is fixed fix.replace(tree, source.substring(((JCTree) tryStatements.get(0)).getStartPosition(), state.getEndPosition(Iterables.getLast(tryStatements)))); } } MethodTree enclosing = findEnclosing(state.getPath()); if (enclosing == null) { // There isn't an enclosing method, possibly because we're in a lambda or initializer block. return Optional.empty(); } if (isExpectedExceptionTest(ASTHelpers.getSymbol(enclosing), state)) { // Replacing the original exception with fail() may break badly-structured expected-exception // tests, so don't use that fix for methods annotated with @Test(expected=...). return Optional.empty(); } // Fix up the enclosing method's throws declaration to include the new thrown exception types. Collection<Type> thrownTypes = ASTHelpers.getSymbol(enclosing).getThrownTypes(); Types types = state.getTypes(); // Find all types in the deleted catch blocks that are not already in the throws declaration. ImmutableList<Type> toThrow = catchBlocks.stream().map(c -> ASTHelpers.getType(c.getParameter())) // convert multi-catch to a list of component types .flatMap(t -> t instanceof UnionClassType ? ImmutableList.copyOf(((UnionClassType) t).getAlternativeTypes()).stream() : Stream.of(t)) .filter(t -> thrownTypes.stream().noneMatch(x -> types.isAssignable(t, x))) .collect(toImmutableList()); if (!toThrow.isEmpty()) { if (!JUnitMatchers.TEST_CASE.matches(enclosing, state)) { // Don't add throws declarations to methods that don't look like test cases, since it may // not be a safe local refactoring. return Optional.empty(); } String throwsString = toThrow.stream().map(t -> SuggestedFixes.qualifyType(state, fix, t)).distinct() .collect(joining(", ")); if (enclosing.getThrows().isEmpty()) { // Add a new throws declaration. fix.prefixWith(enclosing.getBody(), "throws " + throwsString); } else { // Append to an existing throws declaration. fix.postfixWith(Iterables.getLast(enclosing.getThrows()), ", " + throwsString); } } return Optional.of(fix.build()); }
From source file:com.facebook.buck.artifact_cache.AbstractAsynchronousCache.java
private void processCheck() { try {/*from www. j a va 2 s. c o m*/ if (markAllFetchRequestsAsSkipped) { // Build is finished/terminated, all pending fetch requests should be set to skipped state. skipAllPendingRequests(); return; } ImmutableList<ClaimedFetchRequest> requests = getCheckRequests(); if (requests.isEmpty()) { return; } else if (requests.size() == 1) { // If there is just single fetch request get it directly try (ClaimedFetchRequest request = requests.get(0)) { doFetch(request.getRequest()); } } else { ImmutableMap.Builder<RuleKey, ClaimedFetchRequest> requestsBuilder = ImmutableMap.builder(); try { for (ClaimedFetchRequest request : requests) { requestsBuilder.put(request.getRequest().getRuleKey(), request); } ImmutableMap<RuleKey, ClaimedFetchRequest> ruleKeyToRequest = requestsBuilder.build(); doMultiCheck(ruleKeyToRequest); } finally { requests.forEach(ClaimedFetchRequest::close); } } } catch (Exception e) { // If any exception is thrown in trying to process requests, just fulfill everything with an // error. cancelAllPendingRequests(e); } }
From source file:org.androidtransfuse.experiment.generators.ObservesExpressionGenerator.java
@Override public void schedule(final ComponentBuilder builder, ComponentDescriptor descriptor) { builder.add(creationMethod, GenerationPhase.POSTINJECTION, new ComponentMethodGenerator() { @Override/*from w ww . j a v a 2 s. co m*/ public void generate(MethodDescriptor methodDescriptor, JBlock block) { try { ImmutableList<InjectionNode> observableInjectionNodes = FluentIterable .from(builder.getExpressionMap().keySet()).filter(new Predicate<InjectionNode>() { @Override public boolean apply(InjectionNode injectionNode) { return injectionNode.containsAspect(ObservesAspect.class); } }).toList(); if (!observableInjectionNodes.isEmpty()) { //mapping from event type -> observer final JVar observerCollection = getObserversCollection(builder, observableInjectionNodes); if (observerCollection != null) { final JVar eventManager = getEventManager(builder, builder.getExpressionMap(), builder.getScopes()); builder.add(registerMethod, GenerationPhase.REGISTRATION, new ComponentMethodGenerator() { @Override public void generate(MethodDescriptor methodDescriptor, JBlock block) { final JClass mapEntryType = generationUtil.ref(Map.Entry.class) .narrow(EventObserver.class, Class.class); JForEach forEachLoop = block.forEach(mapEntryType, variableNamer.generateName(EventObserver.class), observerCollection.invoke("entrySet")); forEachLoop.body().invoke(eventManager, "register") .arg(forEachLoop.var().invoke("getValue")) .arg(forEachLoop.var().invoke("getKey")); } }); builder.add(unregisterMethod, GenerationPhase.REGISTRATION, new ComponentMethodGenerator() { @Override public void generate(MethodDescriptor methodDescriptor, JBlock block) { JForEach forEachLoop = block.forEach( generationUtil.ref(EventObserver.class), variableNamer.generateName(EventObserver.class), observerCollection.invoke("keySet")); forEachLoop.body().invoke(eventManager, "unregister") .arg(forEachLoop.var()); } }); builder.add(destroyMethod, GenerationPhase.TEARDOWN, new ComponentMethodGenerator() { @Override public void generate(MethodDescriptor methodDescriptor, JBlock block) { block.invoke(observerCollection, "clear"); } }); } } } catch (JClassAlreadyExistsException e) { throw new TransfuseAnalysisException("Tried to generate a class that already exists", e); } } }); }
From source file:org.ow2.authzforce.core.pdp.impl.ModularAttributeProvider.java
protected ModularAttributeProvider( final ImmutableListMultimap<AttributeFqn, NamedAttributeProvider> attributeProviderModulesByAttributeId, final Set<AttributeDesignatorType> selectedAttributeSupport, final boolean strictAttributeIssuerMatch) { assert attributeProviderModulesByAttributeId != null; if (selectedAttributeSupport == null) { designatorModsByAttrId = attributeProviderModulesByAttributeId; } else {/*from w ww . j ava 2 s .c om*/ final ListMultimap<AttributeFqn, NamedAttributeProvider> mutableModsByAttrIdMap = ArrayListMultimap .create(selectedAttributeSupport.size(), 1); for (final AttributeDesignatorType requiredAttr : selectedAttributeSupport) { final AttributeFqn requiredAttrGUID = AttributeFqns.newInstance(requiredAttr); final ImmutableList<NamedAttributeProvider> requiredAttrProviderMods = attributeProviderModulesByAttributeId .get(requiredAttrGUID); /* * According to doc, a non-null empty list is returned if no mappings */ assert requiredAttrProviderMods != null; /* * Empty requiredAttrProviderMod means it should be provided by the request context (in the initial request from PEP) */ if (!requiredAttrProviderMods.isEmpty()) { mutableModsByAttrIdMap.putAll(requiredAttrGUID, requiredAttrProviderMods); } } designatorModsByAttrId = ImmutableListMultimap.copyOf(mutableModsByAttrIdMap); } this.issuedToNonIssuedAttributeCopyMode = strictAttributeIssuerMatch ? ISSUED_TO_NON_ISSUED_ATTRIBUTE_COPY_DISABLED_MODE : ISSUED_TO_NON_ISSUED_ATTRIBUTE_COPY_ENABLED_MODE; }
From source file:com.facebook.buck.cli.BuckConfig.java
public ArtifactCache createArtifactCache(Optional<String> currentWifiSsid, BuckEventBus buckEventBus) { ImmutableList<String> modes = getArtifactCacheModes(); if (modes.isEmpty()) { return new NoopArtifactCache(); }//w w w . ja va 2 s .com ImmutableList.Builder<ArtifactCache> builder = ImmutableList.builder(); try { for (String mode : modes) { switch (ArtifactCacheNames.valueOf(mode)) { case dir: ArtifactCache dirArtifactCache = createDirArtifactCache(); buckEventBus.register(dirArtifactCache); builder.add(dirArtifactCache); break; case cassandra: ArtifactCache cassandraArtifactCache = createCassandraArtifactCache(currentWifiSsid, buckEventBus); if (cassandraArtifactCache != null) { builder.add(cassandraArtifactCache); } break; } } } catch (IllegalArgumentException e) { throw new HumanReadableException("Unusable cache.mode: '%s'", modes.toString()); } ImmutableList<ArtifactCache> artifactCaches = builder.build(); if (artifactCaches.size() == 1) { // Don't bother wrapping a single artifact cache in MultiArtifactCache. return artifactCaches.get(0); } else { return new MultiArtifactCache(artifactCaches); } }
From source file:com.facebook.buck.artifact_cache.AbstractAsynchronousCache.java
private void processFetch() { try {//w ww . j a va2s.com if (markAllFetchRequestsAsSkipped) { // Build is finished/terminated, all pending fetch requests should be set to skipped state. skipAllPendingRequests(); return; } int multiFetchLimit = enableMultiFetch ? getMultiFetchBatchSize(pendingFetchRequests.size()) : 0; if (multiFetchLimit > 0) { ImmutableList.Builder<ClaimedFetchRequest> requestsBuilder = ImmutableList.builder(); try { for (int i = 0; i < multiFetchLimit; i++) { ClaimedFetchRequest request = getFetchRequest(); if (request == null) { break; } requestsBuilder.add(request); } ImmutableList<ClaimedFetchRequest> requests = requestsBuilder.build(); if (requests.isEmpty()) { return; } doMultiFetch(requests); } finally { requestsBuilder.build().forEach(ClaimedFetchRequest::close); } } else { try (ClaimedFetchRequest request = getFetchRequest()) { if (request == null) { return; } doFetch(request.getRequest()); } } } catch (Exception e) { // If any exception is thrown in trying to process requests, just fulfill everything with an // error. cancelAllPendingRequests(e); } }
From source file:org.pircbotx.dcc.DccHandler.java
protected ServerSocket createServerSocket(User user) throws IOException, DccException { InetAddress address = bot.getConfiguration().getDccLocalAddress(); ImmutableList<Integer> dccPorts = bot.getConfiguration().getDccPorts(); if (address == null) //Default to bots address address = bot.getLocalAddress(); ServerSocket ss = null;/* w ww. j a va 2 s . c o m*/ if (dccPorts.isEmpty()) // Use any free port. ss = new ServerSocket(0, 1, address); else { for (int currentPort : dccPorts) try { ss = new ServerSocket(currentPort, 1, address); // Found a port number we could use. break; } catch (Exception e) { // Do nothing; go round and try another port. log.debug("Failed to create server socket on port " + currentPort + ", trying next one", e); } if (ss == null) // No ports could be used. throw new DccException(DccException.Reason.DccPortsInUse, user, "Ports " + dccPorts + " are in use."); } return ss; }
From source file:com.kolich.curacao.CuracaoControllerInvoker.java
@Override public final Object call() throws Exception { // The path within the application represents the part of the URI // without the Servlet context, if any. For example, if the Servlet // content is "/foobar" and the incoming request was GET:/foobar/baz, // then this method will return just "/baz". final String pathWithinApplication = pathHelper_.getPathWithinApplication(ctx_); logger__.debug("Computed path within application context " + "(requestUri={}, computedPath={})", ctx_.comment_, pathWithinApplication); // Attach the path within the application to the mutable context. ctx_.setPathWithinApplication(pathWithinApplication); // Get a list of all supported application routes based on the // incoming HTTP request method. final ImmutableList<CuracaoInvokable> candidates = ctx_.requestMappingTable_ .getRoutesByHttpMethod(ctx_.method_); logger__.debug("Found {} controller candidates for request: {}:{}", candidates.size(), ctx_.method_, pathWithinApplication);/*from w w w . java 2s . com*/ // Check if we found any viable candidates for the incoming HTTP // request method. If we didn't find any, immediately bail letting // the user know this incoming HTTP request method just isn't // supported by the implementation. if (candidates.isEmpty()) { throw new PathNotFoundException( "Found 0 (zero) controller " + "candidates for request: " + ctx_.comment_); } // For each viable option, need to compare the path provided // with the attached invokable method annotation to decide // if that path matches the request. CuracaoInvokable invokable = null; Map<String, String> pathVars = null; for (final CuracaoInvokable i : candidates) { // O(n) logger__.debug("Checking invokable method candidate: {}", i); // Get the matcher instance from the invokable. final CuracaoPathMatcher matcher = i.matcher_.instance_; // The matcher will return 'null' if the provided pattern did not // match the path within application. pathVars = matcher.match(ctx_, // The path mapping registered with the invokable. i.mapping_, // The path within the application. pathWithinApplication); if (pathVars != null) { // Matched! logger__.debug("Extracted path variables: {}", pathVars); invokable = i; break; } } // If we found ~some~ method that supports the incoming HTTP request // type, but no proper annotated controller method that matches // the request path, that means we've got nothing. if (invokable == null) { throw new PathNotFoundException( "Found no invokable controller " + "method worthy of servicing request: " + ctx_.comment_); } // Attach extracted path variables from the matcher onto the mutable context. ctx_.setPathVariables(pathVars); // Invoke each of the request filters attached to the controller // method invokable, in order. Any filter may throw an exception, // which is totally fair and will be handled by the upper-layer. for (final InvokableClassWithInstance<? extends CuracaoRequestFilter> filter : invokable.filters_) { filter.instance_.filter(ctx_); } // Build the parameter list to be passed into the controller method // via reflection. final Object[] parameters = buildPopulatedParameterList(invokable); // Reflection invoke the discovered "controller" method. final Object invokedResult = invokable.method_.invoke( // The controller class. invokable.controller_.instance_, // Method arguments/parameters. parameters); // A set of hard coded controller return type pre-processors. That is, // we take the type/object that the controller returned once invoked // and see if we need to do anything special with it in this request // context (using the thread that's handling the _REQUEST_). Object o = invokedResult; if (invokedResult instanceof Callable) { o = ((Callable<?>) invokedResult).call(); } else if (invokedResult instanceof Future) { o = ((Future<?>) invokedResult).get(); } return o; }