Example usage for com.google.common.collect Iterables getLast

List of usage examples for com.google.common.collect Iterables getLast

Introduction

In this page you can find the example usage for com.google.common.collect Iterables getLast.

Prototype

@Nullable
public static <T> T getLast(Iterable<? extends T> iterable, @Nullable T defaultValue) 

Source Link

Document

Returns the last element of iterable or defaultValue if the iterable is empty.

Usage

From source file:org.trancecode.xproc.step.AbstractCompoundStepProcessor.java

protected Environment runSteps(final Iterable<Step> steps, final Environment environment) {
    LOG.trace("steps = {}", steps);

    final Environment initialEnvironment = environment.newChildStepEnvironment();
    final EnvironmentPort parametersPort = environment.getDefaultParametersPort();
    LOG.trace("  parametersPort = {}", parametersPort);

    final Map<Step, Iterable<Step>> stepDependencies = Step.getSubpipelineStepDependencies(steps);
    final Map<Step, Future<Environment>> stepResults = new ConcurrentHashMap<>();
    final List<Future<Environment>> results = Lists.newArrayList();
    final AtomicReference<Throwable> error = new AtomicReference<>();
    for (final Step step : steps) {
        final Future<Environment> result = environment.getPipelineContext().getExecutor().submit(() -> {
            // shortcut in case an error was reported by another
            // task
            if (error.get() != null) {
                throw new IllegalStateException(error.get());
            }/*from w w  w .j a  v  a 2  s.  co m*/

            Environment inputEnvironment = initialEnvironment;
            for (final Step dependency : stepDependencies.get(step)) {
                try {
                    final Environment dependencyResult = stepResults.get(dependency).get();
                    inputEnvironment = inputEnvironment.addPorts(dependencyResult.getOutputPorts());
                    inputEnvironment = inputEnvironment
                            .setDefaultReadablePort(dependencyResult.getDefaultReadablePort());
                    inputEnvironment = inputEnvironment.setDefaultParametersPort(parametersPort);
                    inputEnvironment = inputEnvironment
                            .setXPathContextPort(dependencyResult.getXPathContextPort());
                } catch (final ExecutionException e) {
                    throw Throwables.propagate(e.getCause());
                }
            }

            Environment.setCurrentNamespaceContext(step.getNode());
            inputEnvironment.setCurrentEnvironment();
            return step.run(inputEnvironment);
        });
        stepResults.put(step, result);
        results.add(result);
    }

    final Iterable<Environment> resultEnvironments;
    try {
        resultEnvironments = TcFutures.get(results);
    } catch (final ExecutionException e) {
        TcFutures.cancel(results);
        throw Throwables.propagate(e.getCause());
    } catch (final InterruptedException e) {
        throw new IllegalStateException(e);
    }

    Environment resultEnvironment = Iterables.getLast(resultEnvironments, initialEnvironment);
    for (final Environment intermediateResultEnvironment : Iterables.filter(resultEnvironments,
            Predicates.notNull())) {
        for (final EnvironmentPort port : intermediateResultEnvironment.getOutputPorts()) {
            if (!resultEnvironment.getPorts().containsKey(port.getPortReference())) {
                resultEnvironment = resultEnvironment.addPorts(port);
            }
        }
    }

    return resultEnvironment;
}

From source file:nextmethod.web.razor.editor.internal.BackgroundThread.java

private void workerLoop() {
    final boolean isEditorTracing = Debug.isDebugArgPresent(DebugArgs.EditorTracing);
    final String fileNameOnly = Filesystem.getFileName(fileName);

    Stopwatch sw = null;/* w ww  .  ja va2  s  .co m*/
    if (isEditorTracing) {
        sw = Stopwatch.createUnstarted();
    }

    try {
        RazorEditorTrace.traceLine(RazorResources().traceBackgroundThreadStart(fileNameOnly));
        ensureOnThread();
        while (!shutdownToken.isCancellationRequested()) {
            // Grab the parcel of work to do
            final WorkParcel parcel = main.getParcel();
            if (!parcel.getChanges().isEmpty()) {
                RazorEditorTrace.traceLine(RazorResources().traceChangesArrived(fileNameOnly,
                        String.valueOf(parcel.getChanges().size())));
                try {
                    DocumentParseCompleteEventArgs args = null;
                    try (CancellationTokenSource linkedCancel = CancellationTokenSource
                            .createLinkedTokenSource(shutdownToken, parcel.getCancelToken())) {
                        if (parcel != null && !linkedCancel.isCancellationRequested()) {
                            // Collect ALL changes
                            if (isEditorTracing && previouslyDiscarded != null
                                    && !previouslyDiscarded.isEmpty()) {
                                RazorEditorTrace.traceLine(RazorResources().traceCollectedDiscardedChanges(
                                        fileNameOnly, String.valueOf(parcel.getChanges().size())));
                            }
                            final Iterable<TextChange> allChanges = Iterables
                                    .concat(previouslyDiscarded != null ? previouslyDiscarded
                                            : Collections.<TextChange>emptyList(), parcel.getChanges());

                            final TextChange finalChange = Iterables.getLast(allChanges, null);
                            if (finalChange != null) {
                                if (isEditorTracing) {
                                    assert sw != null;
                                    sw.reset().start();
                                }

                                //noinspection ConstantConditions
                                final GeneratorResults results = parseChange(finalChange.getNewBuffer(),
                                        linkedCancel.getToken());

                                if (isEditorTracing) {
                                    assert sw != null;
                                    sw.stop();
                                }

                                RazorEditorTrace.traceLine(RazorResources().traceParseComplete(fileNameOnly,
                                        sw != null ? sw.toString() : "?"));

                                if (results != null && !linkedCancel.isCancellationRequested()) {
                                    // Clear discarded changes list
                                    previouslyDiscarded = Lists.newArrayList();
                                    // Take the current tree and check for differences
                                    if (isEditorTracing) {
                                        sw.reset().start();
                                    }
                                    final boolean treeStructureChanged = currentParseTree == null
                                            || BackgroundParser.treesAreDifferent(currentParseTree,
                                                    results.getDocument(), allChanges, parcel.getCancelToken());

                                    if (isEditorTracing) {
                                        sw.stop();
                                    }

                                    currentParseTree = results.getDocument();
                                    RazorEditorTrace.traceLine(RazorResources().traceTreesCompared(fileNameOnly,
                                            sw != null ? sw.toString() : "?",
                                            String.valueOf(treeStructureChanged)));

                                    // Build Arguments
                                    args = new DocumentParseCompleteEventArgs(treeStructureChanged, results,
                                            finalChange);
                                } else {
                                    // Parse completed but we were cancelled in the mean time. Add these to the discarded changes set
                                    RazorEditorTrace.traceLine(RazorResources().traceChangesDiscarded(
                                            fileNameOnly, String.valueOf(Iterables.size(allChanges))));
                                    previouslyDiscarded = Lists.newArrayList(allChanges);
                                }

                                if (Debug.isDebugArgPresent(DebugArgs.CheckTree) && args != null) {
                                    // Rewind the buffer and sanity check the line mappings
                                    finalChange.getNewBuffer().setPosition(0);
                                    final String buffer = TextExtensions.readToEnd(finalChange.getNewBuffer());
                                    final int lineCount = Iterables
                                            .size(Splitter.on(CharMatcher.anyOf("\r\n")).split(buffer));
                                    Debug.doAssert(!Iterables.any(
                                            args.getGeneratorResults().getDesignTimeLineMappingEntries(),
                                            input -> input != null
                                                    && input.getValue().getStartLine() > lineCount),
                                            "Found a design-time line mapping referring to a line outside the source file!");

                                    Debug.doAssert(
                                            !Iterables.any(args.getGeneratorResults().getDocument().flatten(),
                                                    input -> input != null
                                                            && input.getStart().getLineIndex() > lineCount),
                                            "Found a span with a line number outside the source file");
                                }
                            }
                        }
                    }
                    if (args != null) {
                        main.returnParcel(args);
                    }
                } catch (OperationCanceledException ignored) {

                }
            } else {
                RazorEditorTrace.traceLine(RazorResources().traceNoChangesArrived(fileName),
                        parcel.getChanges().size());
                Thread.yield();
            }
        }
    } catch (OperationCanceledException ignored) {
    } finally {
        RazorEditorTrace.traceLine(RazorResources().traceBackgroundThreadShutdown(fileNameOnly));
        // Clean up main thread resources
        main.close();
    }
}

From source file:com.palantir.common.collect.IterableView.java

public T getLast(@Nullable T defaultValue) {
    return Iterables.getLast(castAsIterable(), defaultValue);
}

From source file:com.flaptor.indextank.storage.IndexLog.java

public Segment getLastSegment() {
    return Iterables.getLast(Segment.iterateSegments(root, getSegmentsPath()), null);
}

From source file:org.sleuthkit.autopsy.imageanalyzer.ImageAnalyzerModule.java

private static String getFileExtension(AbstractFile file) {
    return Iterables.getLast(Arrays.asList(StringUtils.split(file.getName(), '.')), "");
}

From source file:com.b2international.snowowl.datastore.cdo.CDOConnection.java

@Override
public CDOBranch getBranch(final IBranchPath branchPath) {
    Preconditions.checkNotNull(branchPath, "Branch path argument cannot be null.");
    final List<CDOBranch> branches = getBranches(branchPath);
    return Iterables.getLast(branches, null);
}

From source file:org.apache.metron.stellar.common.shell.DefaultStellarAutoCompleter.java

private static String getLastToken(String buffer) {
    String lastToken = Iterables.getLast(Splitter.on(" ").split(buffer), null);
    return lastToken.trim();
}

From source file:com.google.devtools.build.lib.profiler.memory.AllocationTracker.java

@Nullable
private static RuleFunction getRuleCreationCall(AllocationSample allocationSample) {
    Object topOfCallstack = Iterables.getLast(allocationSample.callstack, null);
    if (topOfCallstack instanceof RuleFunction) {
        return (RuleFunction) topOfCallstack;
    }//  ww w .  j  a v  a  2  s  .c  om
    return null;
}

From source file:com.facebook.swift.generator.SwiftGenerator.java

private String extractThriftNamespace(final URI thriftUri) {
    final String path = thriftUri.getPath();
    final String filename = Iterables.getLast(Splitter.on('/').split(path), null);
    Preconditions.checkState(filename != null, "No thrift namespace found in %s", thriftUri);

    final String name = Iterables.getFirst(Splitter.on('.').split(filename), null);
    Preconditions.checkState(name != null, "No thrift namespace found in %s", thriftUri);
    return name;/*from w  ww  .j av a  2 s.  c  o m*/
}

From source file:io.bazel.rules.closure.worker.PersistentWorker.java

private void loadArguments(boolean isWorker) {
    try {/*from   w  ww  . ja va  2 s . c o  m*/
        String lastArg = Iterables.getLast(arguments, "");
        if (lastArg.startsWith("@")) {
            Path flagFile = fs.getPath(CharMatcher.is('@').trimLeadingFrom(lastArg));
            if ((isWorker && lastArg.startsWith("@@")) || Files.exists(flagFile)) {
                arguments.clear();
                arguments.addAll(Files.readAllLines(flagFile, UTF_8));
            }
        } else {
            List<String> newArguments = new ArrayList<>();
            for (String argument : arguments) {
                if (argument.startsWith(FLAGFILE_ARG)) {
                    newArguments.addAll(
                            Files.readAllLines(fs.getPath(argument.substring(FLAGFILE_ARG.length())), UTF_8));
                }
            }
            if (!newArguments.isEmpty()) {
                arguments.clear();
                arguments.addAll(newArguments);
            }
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}