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

public static <T> T getLast(Iterable<T> iterable) 

Source Link

Document

Returns the last element of iterable .

Usage

From source file:org.sonar.php.checks.formatting.IndentationCheck.java

private void checkArgumentsIndentation(SeparatedList arguments, SyntaxToken functionName, int baseColumn,
        @Nullable SyntaxToken closeParenthesis, boolean isFunctionCall) {
    if (arguments.size() > 1) {
        Tree firstArg = (Tree) arguments.get(0);

        int expectedIndentationColumn = baseColumn + PSR2_INDENTATION;
        int callingLine = functionName.line();

        if (!allArgumentsOnSameLine(functionName, arguments)) {

            if (!isCorrectlySplitOnLines(callingLine, arguments)) {
                check.reportIssue(//from   w ww.  j av  a 2s  . c  om
                        String.format(ARGUMENT_LINE_SPLIT_MESSAGE, expectedIndentationColumn, callingLine),
                        firstArg);

            } else if (!isCorrectlyIndented(expectedIndentationColumn, arguments)) {
                check.reportIssue(String.format(ARGUMENT_INDENTATION_MESSAGE, expectedIndentationColumn),
                        firstArg);
            }

            // Checking parenthesis
            if (closeParenthesis != null) {
                checkClosingParenthesisLocation((Tree) Iterables.getLast(arguments), closeParenthesis,
                        isFunctionCall);
            }
        }
    }
}

From source file:com.twitter.common.thrift.callers.RetryingCaller.java

@Override
public Object call(final Method method, final Object[] args, @Nullable final AsyncMethodCallback callback,
        @Nullable final Amount<Long, Time> connectTimeoutOverride) throws Throwable {
    final AtomicLong retryCounter = stats.get(method);
    final AtomicInteger attempts = new AtomicInteger();
    final List<Throwable> exceptions = Lists.newArrayList();

    final ResultCapture capture = new ResultCapture() {
        @Override/*  www  . java2  s.c o  m*/
        public void success() {
            // No-op.
        }

        @Override
        public boolean fail(Throwable t) {
            if (!isRetryable(t)) {
                if (debug) {
                    LOG.warning(String.format(
                            "Call failed with un-retryable exception of [%s]: %s, previous exceptions: %s",
                            t.getClass().getName(), t.getMessage(), combineStackTraces(exceptions)));
                }

                return true;
            } else if (attempts.get() >= retries) {
                exceptions.add(t);

                if (debug) {
                    LOG.warning(String.format("Retried %d times, last error: %s, exceptions: %s",
                            attempts.get(), t, combineStackTraces(exceptions)));
                }

                return true;
            } else {
                exceptions.add(t);

                if (isAsync() && attempts.incrementAndGet() <= retries) {
                    try {
                        retryCounter.incrementAndGet();
                        // override connect timeout in ThriftCaller to prevent blocking for a connection
                        // for async retries (since this is within the callback in the selector thread)
                        invoke(method, args, callback, this, NONBLOCKING_TIMEOUT);
                    } catch (Throwable throwable) {
                        return fail(throwable);
                    }
                }

                return false;
            }
        }
    };

    boolean continueLoop;
    do {
        try {
            // If this is an async call, the looping will be handled within the capture.
            return invoke(method, args, callback, capture, connectTimeoutOverride);
        } catch (Throwable t) {
            if (!isRetryable(t)) {
                Throwable propagated = t;

                if (!exceptions.isEmpty() && (t instanceof TResourceExhaustedException)) {
                    // If we've been trucking along through retries that have had remote call failures
                    // and we suddenly can't immediately get a connection on the next retry, throw the
                    // previous remote call failure - the idea here is that the remote call failure is
                    // more interesting than a transient inability to get an immediate connection.
                    propagated = exceptions.remove(exceptions.size() - 1);
                }

                if (isAsync()) {
                    callback.onError(propagated);
                } else {
                    throw propagated;
                }
            }
        }

        continueLoop = !isAsync() && attempts.incrementAndGet() <= retries;
        if (continueLoop)
            retryCounter.incrementAndGet();
    } while (continueLoop);

    Throwable lastRetriedException = Iterables.getLast(exceptions);
    if (debug) {
        if (!exceptions.isEmpty()) {
            LOG.warning(String.format("Retried %d times, last error: %s, previous exceptions: %s",
                    attempts.get(), lastRetriedException, combineStackTraces(exceptions)));
        } else {
            LOG.warning(String.format("Retried 1 time, last error: %s", lastRetriedException));
        }
    }

    if (!isAsync())
        throw lastRetriedException;
    return null;
}

From source file:org.sosy_lab.cpachecker.cpa.predicate.PredicateBasedPrefixProvider.java

private InfeasiblePrefix buildInfeasiblePrefix(final ARGPath path, MutableARGPath currentPrefix,
        List<BooleanFormula> interpolantSequence, FormulaManagerView fmgr) {
    MutableARGPath infeasiblePrefix = new MutableARGPath();
    infeasiblePrefix.addAll(currentPrefix);

    // for interpolation/refinement to work properly with existing code,
    // add another transition after the infeasible one, also add FALSE itp
    infeasiblePrefix.add(obtainSuccessorTransition(path, currentPrefix.size()));
    interpolantSequence.add(fmgr.getBooleanFormulaManager().makeBoolean(false));

    // additionally, add final (target) state, also to satisfy requirements of existing code
    infeasiblePrefix/*from   w w w .j  a v a 2  s .  com*/
            .add(Pair.of(Iterables.getLast(path.asStatesList()), Iterables.getLast(path.asEdgesList())));

    return InfeasiblePrefix.buildForPredicateDomain(infeasiblePrefix.immutableCopy(), interpolantSequence,
            fmgr);
}

From source file:com.amazonaws.services.kinesis.application.producer.Generator.java

private static void putOneRecordMethod(final StockTrade trade) throws InterruptedException {

    byte[] bytes = trade.toJsonAsBytes();
    // The bytes could be null if there is an issue with the JSON serialization by the Jackson JSON library.
    if (bytes == null) {
        log.info("Could not get JSON bytes for stock trade");
        return;/*from   w  w  w.ja v  a  2 s. c om*/
    }

    FutureCallback<UserRecordResult> callback = new FutureCallback<UserRecordResult>() {
        @Override
        public void onFailure(Throwable t) {

            if (t instanceof UserRecordFailedException) {
                Attempt last = Iterables.getLast(((UserRecordFailedException) t).getResult().getAttempts());
                log.debug(String.format("Record failed to put - %s : %s : %s", trade.toString(),
                        last.getErrorCode(), last.getErrorMessage()));
                //log.error("Exception during put", t);

            }
        }

        @Override
        public void onSuccess(UserRecordResult result) {
            completed.getAndIncrement();
            /*log.info(String.format(
                    "Succesfully put record, "
                            + "payload=%s", trade.toString()));*/
        }
    };

    while (producer.getOutstandingRecordsCount() > backpressureSize) {
        Thread.sleep(backpressureDelay);
    }

    ListenableFuture<UserRecordResult> f = producer.addUserRecord(streamName, TIMESTAMP,
            Utils.randomExplicitHashKey(), ByteBuffer.wrap(bytes));
    Futures.addCallback(f, callback);
}

From source file:com.google.devtools.build.lib.syntax.Parser.java

private static Location locationFromStatements(Lexer lexer, List<Statement> statements) {
    if (!statements.isEmpty()) {
        return lexer.createLocation(statements.get(0).getLocation().getStartOffset(),
                Iterables.getLast(statements).getLocation().getEndOffset());
    } else {/*from  w w w .  ja va 2s.  c o  m*/
        return Location.fromPathFragment(lexer.getFilename());
    }
}

From source file:com.palantir.atlasdb.sweep.SweepTaskRunnerImpl.java

@Override
public SweepResults run(String tableName, int batchSize, @Nullable byte[] startRow) {
    Preconditions.checkNotNull(tableName);
    Preconditions.checkState(!AtlasDbConstants.hiddenTables.contains(tableName));

    if (tableName.startsWith(AtlasDbConstants.NAMESPACE_PREFIX)) {
        // this happens sometimes; I think it's because some places in the code can
        // start this sweeper without doing the full normally ordered KVSModule startup.
        // I did check and sweep.stats did contain the FQ table name for all of the tables,
        // so it is at least broken in some way that still allows namespaced tables to eventually be swept.
        log.warn("The sweeper should not be run on tables passed through namespace mapping.");
        return SweepResults.EMPTY_SWEEP;
    }/*from w ww  . j  a va2s .  com*/
    if (keyValueService.getMetadataForTable(tableName).length == 0) {
        log.warn("The sweeper tried to sweep table '{}', but the table does not exist. Skipping table.",
                tableName);
        return SweepResults.EMPTY_SWEEP;
    }

    // Earliest start timestamp of any currently open transaction, with two caveats:
    // (1) unreadableTimestamps are calculated via wall-clock time, and so may not be correct
    //     under pathological clock conditions
    // (2) immutableTimestamps do not account for locks have timed out after checking their locks;
    //     such a transaction may have a start timestamp less than the immutableTimestamp, and it
    //     could still get successfully committed (its commit timestamp may or may not be less than
    //     the immutableTimestamp
    // Note that this is fine, because we'll either
    // (1) force old readers to abort (if they read a garbage collection sentinel), or
    // (2) force old writers to retry (note that we must roll back any uncommitted transactions that
    //     we encounter
    SweepStrategy sweepStrategy = sweepStrategyManager.get().get(tableName);
    if (sweepStrategy == null) {
        sweepStrategy = SweepStrategy.CONSERVATIVE;
    } else if (sweepStrategy == SweepStrategy.NOTHING) {
        return SweepResults.EMPTY_SWEEP;
    }
    if (startRow == null) {
        startRow = new byte[0];
    }
    RangeRequest rangeRequest = RangeRequest.builder().startRowInclusive(startRow).batchHint(batchSize).build();

    long sweepTimestamp = getSweepTimestamp(sweepStrategy);
    ClosableIterator<RowResult<Value>> valueResults;
    if (sweepStrategy == SweepStrategy.CONSERVATIVE) {
        valueResults = ClosableIterators.wrap(ImmutableList.<RowResult<Value>>of().iterator());
    } else {
        valueResults = keyValueService.getRange(tableName, rangeRequest, sweepTimestamp);
    }

    ClosableIterator<RowResult<Set<Long>>> rowResults = keyValueService.getRangeOfTimestamps(tableName,
            rangeRequest, sweepTimestamp);

    try {
        List<RowResult<Set<Long>>> rowResultTimestamps = ImmutableList
                .copyOf(Iterators.limit(rowResults, batchSize));
        PeekingIterator<RowResult<Value>> peekingValues = Iterators.peekingIterator(valueResults);
        Set<Cell> sentinelsToAdd = Sets.newHashSet();
        Multimap<Cell, Long> rowTimestamps = getTimestampsFromRowResults(rowResultTimestamps, sweepStrategy);
        Multimap<Cell, Long> cellTsPairsToSweep = getCellTsPairsToSweep(rowTimestamps, peekingValues,
                sweepTimestamp, sweepStrategy, sentinelsToAdd);
        sweepCells(tableName, cellTsPairsToSweep, sentinelsToAdd);
        byte[] nextRow = rowResultTimestamps.size() < batchSize ? null
                : RangeRequests.getNextStartRow(false, Iterables.getLast(rowResultTimestamps).getRowName());
        return new SweepResults(nextRow, rowResultTimestamps.size(), cellTsPairsToSweep.size());
    } finally {
        rowResults.close();
        valueResults.close();
    }
}

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 .jav  a  2 s  .  c  o  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:org.glowroot.ui.GaugeValueJsonService.java

private <K> void syncManualRollupCaptureTimes(Map<K, List<GaugeValue>> map, int rollupLevel) {
    long fixedIntervalMillis = configRepository.getRollupConfigs().get(rollupLevel - 1).intervalMillis();
    Map<K, Long> manualRollupCaptureTimes = Maps.newHashMap();
    long maxCaptureTime = Long.MIN_VALUE;
    for (Map.Entry<K, List<GaugeValue>> entry : map.entrySet()) {
        List<GaugeValue> gaugeValues = entry.getValue();
        if (gaugeValues.isEmpty()) {
            continue;
        }/* ww w. ja  v  a2 s.c  o  m*/
        long lastCaptureTime = Iterables.getLast(gaugeValues).getCaptureTime();
        maxCaptureTime = Math.max(maxCaptureTime, lastCaptureTime);
        if (lastCaptureTime % fixedIntervalMillis != 0) {
            manualRollupCaptureTimes.put(entry.getKey(), lastCaptureTime);
        }
    }
    if (maxCaptureTime == Long.MIN_VALUE) {
        // nothing to sync
        return;
    }
    long maxRollupCaptureTime = CaptureTimes.getRollup(maxCaptureTime, fixedIntervalMillis);
    long maxDiffToSync = Math.min(fixedIntervalMillis / 5, 60000);
    for (Map.Entry<K, Long> entry : manualRollupCaptureTimes.entrySet()) {
        Long captureTime = entry.getValue();
        if (CaptureTimes.getRollup(captureTime, fixedIntervalMillis) != maxRollupCaptureTime) {
            continue;
        }
        if (maxCaptureTime - captureTime > maxDiffToSync) {
            // only sync up times that are close to each other
            continue;
        }
        K key = entry.getKey();
        List<GaugeValue> gaugeValues = checkNotNull(map.get(key));
        // make copy in case ImmutableList
        gaugeValues = Lists.newArrayList(gaugeValues);
        GaugeValue lastGaugeValue = Iterables.getLast(gaugeValues);
        gaugeValues.set(gaugeValues.size() - 1,
                lastGaugeValue.toBuilder().setCaptureTime(maxCaptureTime).build());
        map.put(key, gaugeValues);
    }
}

From source file:edu.harvard.med.screensaver.ui.attachedFiles.AttachedFileSearchResults.java

@Override
protected List<? extends TableColumn<Tuple<Integer>, ?>> buildColumns() {
    List<TableColumn<Tuple<Integer>, ?>> columns = Lists.newArrayList();

    if (_attachedFileTypesFilter == null
            || Iterables.any(_attachedFileTypesFilter, Predicates.instanceOf(UserAttachedFileType.class))) {
        columns.add(//  w  ww .ja  va2 s. co  m
                new IntegerTupleColumn<AttachedFile, Integer>(
                        RelationshipPath.from(AttachedFile.class).to(AttachedFile.screeningRoomUser)
                                .toProperty("id"),
                        "Screener ID", "The identifier of the screener to which the file is attached",
                        TableColumn.UNGROUPED) {

                    @Override
                    public Object cellAction(Tuple<Integer> t) {
                        return _userViewer.viewEntity(getAttachedFile(t).getScreeningRoomUser());
                    }

                    @Override
                    public boolean isCommandLink() {
                        return true;
                    }
                });

        columns.add(new TextTupleColumn<AttachedFile, Integer>(
                RelationshipPath.from(AttachedFile.class).to(AttachedFile.screeningRoomUser)
                        .toProperty("lastName"),
                "User Last Name", "The last name of the user to which the file is attached",
                TableColumn.UNGROUPED));
        columns.add(new TextTupleColumn<AttachedFile, Integer>(
                RelationshipPath.from(AttachedFile.class).to(AttachedFile.screeningRoomUser)
                        .toProperty("firstName"),
                "User First Name", "The first name of the user to which the file is attached",
                TableColumn.UNGROUPED));

        final PropertyPath<AttachedFile> labHeadLabAffiliationPropertyPath = RelationshipPath
                .from(AttachedFile.class).to(AttachedFile.screeningRoomUser).to(ScreeningRoomUser.LabHead)
                .to(LabHead.labAffiliation).toProperty("affiliationName");
        columns.add(new TextTupleColumn<AttachedFile, Integer>(
                RelationshipPath.from(AttachedFile.class).to(AttachedFile.screeningRoomUser)
                        .to(LabHead.labAffiliation).toProperty("affiliationName"),
                "User Lab Affiliation", "The lab affiliation of the user to which the file is attached",
                TableColumn.UNGROUPED) {
            @Override
            public String getCellValue(Tuple<Integer> tuple) {
                String cellValue = super.getCellValue(tuple);
                if (cellValue == null) {
                    cellValue = (String) tuple
                            .getProperty(TupleDataFetcher.makePropertyKey(labHeadLabAffiliationPropertyPath));
                }
                return cellValue;
            }
        });
        ((TextTupleColumn) Iterables.getLast(columns)).addRelationshipPath(labHeadLabAffiliationPropertyPath);
    }

    if (_attachedFileTypesFilter == null
            || Iterables.any(_attachedFileTypesFilter, Predicates.instanceOf(ScreenAttachedFileType.class))) {
        columns.add(new TextTupleColumn<AttachedFile, Integer>(AttachedFile.screen.toProperty("facilityId"),
                "Screen", "The screen to which the file is attached", TableColumn.UNGROUPED) {
            @Override
            public Object cellAction(Tuple<Integer> t) {
                return _screenViewer.viewEntity(getAttachedFile(t).getScreen());
            }

            @Override
            public boolean isCommandLink() {
                return true;
            }
        });
    }

    if (_attachedFileTypesFilter == null || _attachedFileTypesFilter.size() > 1) {
        columns.add(new VocabularyTupleColumn<AttachedFile, Integer, AttachedFileType>(
                RelationshipPath.from(AttachedFile.class).toProperty("fileType"), "Type",
                "The type of the attached file", TableColumn.UNGROUPED,
                new VocabularyConverter<AttachedFileType>(_allAttachedFileTypes), _allAttachedFileTypes));
    }

    columns.add(new TextTupleColumn<AttachedFile, Integer>(
            RelationshipPath.from(AttachedFile.class).toProperty("filename"), "File Name",
            "The name of the attached file", TableColumn.UNGROUPED) {
        @Override
        public Object cellAction(Tuple<Integer> t) {
            try {
                return AttachedFiles.doDownloadAttachedFile(getAttachedFile(t), getFacesContext(), _dao);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        @Override
        public boolean isCommandLink() {
            return true;
        }
    });

    columns.add(new DateTupleColumn<AttachedFile, Integer>(
            RelationshipPath.from(AttachedFile.class).toProperty("fileDate"), "File Date",
            "The date of the attached file", TableColumn.UNGROUPED));

    return columns;
}

From source file:org.opendaylight.mdsal.binding.javav2.generator.util.Types.java

@Nullable
public static String getOuterClassName(final Type valueType) {
    final String pkgName = valueType.getPackageName();
    if (CharMatcher.JAVA_UPPER_CASE.indexIn(pkgName) >= 0) {
        // It is inner class.
        return Iterables.getLast(DOT_SPLITTER.split(pkgName));
    }//w  ww.  j av  a  2 s  .c o m
    return null;
}