Example usage for com.google.common.collect ImmutableList forEach

List of usage examples for com.google.common.collect ImmutableList forEach

Introduction

In this page you can find the example usage for com.google.common.collect ImmutableList forEach.

Prototype

default void forEach(Consumer<? super T> action) 

Source Link

Document

Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.

Usage

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 w w w .  j  a va 2 s .co  m
        // 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.versions.ParallelVersionedTargetGraphBuilder.java

@Override
public TargetGraph build() throws VersionException, TimeoutException, InterruptedException {
    LOG.debug("Starting version target graph transformation (nodes %d)",
            unversionedTargetGraphAndBuildTargets.getTargetGraph().getNodes().size());
    long start = System.currentTimeMillis();

    // Walk through explicit built targets, separating them into root and non-root nodes.
    ImmutableList<RootAction> actions = unversionedTargetGraphAndBuildTargets.getBuildTargets().stream()
            .map(this::getNode).map(RootAction::new).collect(ImmutableList.toImmutableList());

    // Add actions to the `rootActions` member for bookkeeping.
    actions.forEach(a -> rootActions.put(a.getRoot().getBuildTarget(), a));

    // Kick off the jobs to process the root nodes.
    actions.forEach(pool::submit);/*from   w  w w. jav a2 s .  com*/

    // Wait for actions to complete.
    for (RootAction action : actions) {
        action.getChecked();
    }

    long end = System.currentTimeMillis();
    LOG.debug("Finished version target graph transformation in %.2f (nodes %d, roots: %d)",
            (end - start) / 1000.0, index.size(), roots.get());

    return targetGraphBuilder.build();
}

From source file:com.facebook.buck.artifact_cache.AbstractAsynchronousCache.java

private void skipAllPendingRequests() {
    ImmutableList<ClaimedFetchRequest> requests = getCheckRequests();
    requests.forEach(AbstractAsynchronousCache::skipPendingRequest);

    while (true) {
        ClaimedFetchRequest request = getFetchRequest();
        if (request == null) {
            break;
        }// w  w w.  j  ava2 s. com
        skipPendingRequest(request);
    }
}

From source file:com.facebook.buck.artifact_cache.AbstractAsynchronousCache.java

private void cancelAllPendingRequests(Exception e) {
    ImmutableList<ClaimedFetchRequest> requests = getCheckRequests();
    requests.forEach(r -> cancelRequest(r, e));

    while (true) {
        ClaimedFetchRequest request = getFetchRequest();
        if (request == null) {
            break;
        }//from  w  ww .  j av a 2  s  .  c  o  m
        cancelRequest(request, e);
    }

    LOG.error(e, "Exception thrown while processing fetch requests.");
}

From source file:com.facebook.buck.versions.VersionedTargetGraphBuilder.java

public TargetGraph build() throws VersionException, InterruptedException {
    LOG.debug("Starting version target graph transformation (nodes %d)",
            unversionedTargetGraphAndBuildTargets.getTargetGraph().getNodes().size());
    long start = System.currentTimeMillis();

    // Walk through explicit built targets, separating them into root and non-root nodes.
    ImmutableList<RootAction> actions = unversionedTargetGraphAndBuildTargets.getBuildTargets().stream()
            .map(this::getNode).map(RootAction::new).collect(MoreCollectors.toImmutableList());

    // Add actions to the `rootActions` member for bookkeeping.
    actions.forEach(a -> rootActions.put(a.getRoot().getBuildTarget(), a));

    // Kick off the jobs to process the root nodes.
    actions.forEach(pool::submit);//w  w w  .  j  a  va2  s  .co  m

    // Wait for actions to complete.
    for (RootAction action : actions) {
        action.getChecked();
    }

    long end = System.currentTimeMillis();
    LOG.debug("Finished version target graph transformation in %.2f (nodes %d, roots: %d)",
            (end - start) / 1000.0, index.size(), roots.get());

    return new VersionedTargetGraph(graph, ImmutableMap.copyOf(index), ImmutableSet.of());
}

From source file:org.eclipse.xtext.idea.completion.AbstractCompletionContributor.java

protected void createParserBasedProposals(final CompletionParameters parameters,
        final CompletionResultSet result) {
    Editor _editor = parameters.getEditor();
    int _offset = parameters.getOffset();
    final TokenSet tokenSet = this._tokenSetProvider.getTokenSet(((EditorEx) _editor), _offset);
    boolean _supportParserBasedProposals = this.supportParserBasedProposals(tokenSet);
    boolean _not = (!_supportParserBasedProposals);
    if (_not) {//ww  w. j a  va  2 s .c  om
        return;
    }
    final ContentAssistContextFactory delegate = this.getParserBasedDelegate();
    boolean _equals = Objects.equal(delegate, null);
    if (_equals) {
        return;
    }
    String _text = this.getText(parameters);
    TextRegion _selection = this.getSelection(parameters);
    int _offset_1 = parameters.getOffset();
    XtextResource _resource = this.getResource(parameters);
    final ContentAssistContext[] contexts = delegate.create(_text, _selection, _offset_1, _resource);
    final java.util.function.Consumer<ContentAssistContext> _function = (ContentAssistContext c) -> {
        ImmutableList<AbstractElement> _firstSetGrammarElements = c.getFirstSetGrammarElements();
        final java.util.function.Consumer<AbstractElement> _function_1 = (AbstractElement e) -> {
            this.createProposal(e, c, parameters, result);
        };
        _firstSetGrammarElements.forEach(_function_1);
    };
    ((List<ContentAssistContext>) Conversions.doWrapArray(contexts)).forEach(_function);
}

From source file:org.zanata.client.commands.push.RawPushCommand.java

@Override
public void run() throws IOException {
    PushCommand.logOptions(log, getOpts());

    consoleInteractor.printfln(DisplayMode.Warning, "Using EXPERIMENTAL project type 'file'.");

    List<FileTypeInfo> serverAcceptedTypes = fileTypeInfoList(client);

    if (getOpts().getListFileTypes()) {
        printFileTypes(serverAcceptedTypes);
        return;/*  w  w w. j  a v a  2  s . c o  m*/
    }

    if (!pushSource() && !pushTrans()) {
        throw new RuntimeException("Invalid option for push type");
    }
    // only supporting single module for now

    File sourceDir = getOpts().getSrcDir();
    if (!sourceDir.exists()) {
        boolean enableModules = getOpts().getEnableModules();
        // TODO(files) remove warning when modules supported
        if (enableModules) {
            consoleInteractor.printfln(DisplayMode.Warning,
                    "enableModules=true but multi-modules not yet supported for this command. Using single module push.");
        }

        throw new RuntimeException("directory '" + sourceDir + "' does not exist - check "
                + getOpts().getSrcDirParameterName() + " option");
    }

    RawPushStrategy strat = new RawPushStrategy();
    strat.setPushOptions(getOpts());

    ImmutableList<FileTypeInfo> actualFileTypes = getActualFileTypes(serverAcceptedTypes,
            getOpts().getFileTypes());

    if (actualFileTypes.isEmpty()) {
        log.info("no valid types specified; nothing to do");
        return;
    }

    ImmutableList.Builder<String> sourceFileExtensionsBuilder = ImmutableList.builder();
    actualFileTypes
            .forEach(fileTypeInfo -> sourceFileExtensionsBuilder.addAll(fileTypeInfo.getSourceExtensions()));
    ImmutableList<String> sourceFileExtensions = sourceFileExtensionsBuilder.build();

    String[] srcFiles = strat.getSrcFiles(sourceDir, getOpts().getIncludes(), getOpts().getExcludes(),
            sourceFileExtensions, true, getOpts().getCaseSensitive());

    SortedSet<String> localDocNames = new TreeSet<String>(Arrays.asList(srcFiles));

    // TODO(files) handle obsolete document deletion
    consoleInteractor.printfln(DisplayMode.Warning,
            "Obsolete document removal is not yet implemented, no documents will be removed from the server.");

    SortedSet<String> docsToPush = localDocNames;
    if (getOpts().getFromDoc() != null) {
        if (!localDocNames.contains(getOpts().getFromDoc())) {
            log.error("Document with id {} not found, unable to start push from unknown document. Aborting.",
                    getOpts().getFromDoc());
            // FIXME should this be throwing an exception to properly abort?
            // need to see behaviour with modules
            return;
        }
        docsToPush = localDocNames.tailSet(getOpts().getFromDoc());
        int numSkippedDocs = localDocNames.size() - docsToPush.size();
        log.info("Skipping {} document(s) before {}.", numSkippedDocs, getOpts().getFromDoc());
    }

    if (docsToPush.isEmpty()) {
        log.info("no documents in module: {}; nothing to do", getOpts().getCurrentModule());
        return;
    } else {
        consoleInteractor.printfln("Found source documents:");
        for (String docName : localDocNames) {
            if (docsToPush.contains(docName)) {
                FileTypeName fileType = getFileTypeNameBySourceExtension(actualFileTypes,
                        FilenameUtils.getExtension(docName));
                consoleInteractor.printfln("           "
                        + Messages.format("push.info.documentToPush", docName, fileType.getName()));
            } else {
                consoleInteractor.printfln(Messages.format("push.info.skipDocument", docName));
            }
        }
    }

    if (pushTrans()) {
        if (getOpts().getLocaleMapList() == null)
            throw new ConfigException(
                    "pushType set to '" + getOpts().getPushType() + "', but project has no locales configured");
        consoleInteractor.printfln(DisplayMode.Warning,
                Messages.format("push.warn.overrideTranslations", getOpts().getPushType()));

        if (getOpts().getPushType() == PushPullType.Both) {
            confirmWithUser("This will overwrite existing documents AND TRANSLATIONS on the server.\n");
            // , and delete obsolete documents.\n");
        } else if (getOpts().getPushType() == PushPullType.Trans) {
            confirmWithUser("This will overwrite existing TRANSLATIONS on the server.\n");
        }
    } else {
        // confirmWithUser("This will overwrite existing documents on the server, and delete obsolete documents.\n");
        confirmWithUser("This will overwrite existing documents on the server.\n");
    }

    boolean hasErrors = false;

    for (final String localDocName : docsToPush) {
        try {
            final String srcExtension = FilenameUtils.getExtension(localDocName);
            final FileTypeInfo fileType = getFileType(actualFileTypes, srcExtension);
            final String qualifiedDocName = qualifiedDocName(localDocName);
            if (pushSource()) {
                if (!getOpts().isDryRun()) {
                    boolean sourcePushed = pushSourceDocumentToServer(sourceDir, localDocName, qualifiedDocName,
                            fileType.getType().getName());
                    // ClientUtility.checkResult(putResponse, uri);
                    if (!sourcePushed) {
                        hasErrors = true;
                    }
                } else {
                    log.info("pushing source doc [qualifiedname={}] to server (skipped due to dry run)",
                            qualifiedDocName);
                }
            }

            if (pushTrans()) {
                Optional<String> translationFileExtension = getTranslationFileExtension(fileType, srcExtension);

                strat.visitTranslationFiles(localDocName, new TranslationFilesVisitor() {

                    @Override
                    public void visit(LocaleMapping locale, File translatedDoc) {
                        log.info("pushing {} translation of {}", locale.getLocale(), qualifiedDocName);
                        pushDocumentToServer(qualifiedDocName, fileType.getType().getName(), locale.getLocale(),
                                translatedDoc);
                    }
                }, translationFileExtension);
            }
        } catch (IOException | RuntimeException e) {
            log.error(
                    "Operation failed: " + e.getMessage() + "\n\n"
                            + "    To retry from the last document, please add the option: {}\n",
                    getOpts().buildFromDocArgument(localDocName));
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    if (hasErrors) {
        throw new RuntimeException("Push completed with errors, see log for details.");
    }

}

From source file:com.facebook.buck.artifact_cache.AbstractAsynchronousCache.java

private void processCheck() {
    try {//w  w w  .j  a  v  a2s.c  om
        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:com.facebook.buck.cxx.AbstractElfRewriteDynStrSectionStep.java

@Override
public StepExecutionResult execute(ExecutionContext context) throws IOException {
    try (FileChannel channel = FileChannel.open(getFilesystem().resolve(getPath()), StandardOpenOption.READ,
            StandardOpenOption.WRITE)) {
        MappedByteBuffer buffer = channel.map(READ_WRITE, 0, channel.size());
        Elf elf = new Elf(buffer);

        ImmutableList<SectionUsingDynamicStrings> processors = getSectionProcesors(elf);

        // Load the dynamic string table.
        ElfSectionLookupResult dynStrSection = elf.getMandatorySectionByName(getPath(), DYNSTR);
        byte[] dynStr = new byte[dynStrSection.getSection().body.remaining()];
        dynStrSection.getSection().body.get(dynStr);

        // Collect all the string references from the section processors.
        ImmutableList<Long> stringIndices = RichStream.from(processors)
                .flatMap(p -> p.getStringReferences().stream()).toImmutableList();

        // Write the new dynamic string table out to a byte array and get the new string indices
        // corresponding to the order of the collected string indices.
        ByteArrayOutputStream newDynStrStream = new ByteArrayOutputStream();
        ImmutableList<Integer> newStringIndices = ElfStringTable.writeStringTableFromStringTable(dynStr,
                RichStream.from(stringIndices).map(i -> (int) (long) i).toImmutableList(), newDynStrStream);
        Preconditions.checkState(stringIndices.size() == newStringIndices.size());
        byte[] newDynStr = newDynStrStream.toByteArray();
        Preconditions.checkState(dynStrSection.getSection().header.sh_size >= newDynStr.length);

        // Generate a map from old to new string indices which sections can use to update themselves.
        Map<Long, Long> newStringIndexMapBuilder = new HashMap<>();
        for (int i = 0; i < stringIndices.size(); i++) {
            newStringIndexMapBuilder.put(stringIndices.get(i), (long) newStringIndices.get(i));
        }//from w  w w  . ja v  a2  s.c  o m
        ImmutableMap<Long, Long> newStringIndexMap = ImmutableMap.copyOf(newStringIndexMapBuilder);

        // Call back into the processors to update themselves with the new string indices.
        processors.forEach(p -> p.processNewStringReferences(newDynStr.length, newStringIndexMap));

        // Rewrite the dynamic string section.
        dynStrSection.getSection().body.rewind();
        dynStrSection.getSection().body.put(newDynStr);

        // Fixup the version section header with the new size and write it out.
        buffer.position((int) (elf.header.e_shoff + dynStrSection.getIndex() * elf.header.e_shentsize));
        dynStrSection.getSection().header.withSize(dynStrSection.getSection().body.position())
                .write(elf.header.ei_class, buffer);
    }
    return StepExecutionResults.SUCCESS;
}