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:com.netflix.astyanax.thrift.ThriftAllRowsImpl.java

/**
 * Each call to .iterator() returns a new context starting at the beginning
 * of the column family./*from   www .j a  va  2 s.c  om*/
 */
@Override
public Iterator<Row<K, C>> iterator() {
    return new Iterator<Row<K, C>>() {
        private KeyRange range;
        private org.apache.cassandra.thrift.KeySlice lastRow;
        private List<org.apache.cassandra.thrift.KeySlice> list = null;
        private Iterator<org.apache.cassandra.thrift.KeySlice> iter = null;
        private boolean bContinueSearch = true;
        private boolean bIgnoreTombstones = true;

        {
            String startToken = query.getStartToken() == null ? partitioner.getMinToken()
                    : query.getStartToken();
            String endToken = query.getEndToken() == null ? partitioner.getMaxToken() : query.getEndToken();

            range = new KeyRange().setCount(query.getBlockSize()).setStart_token(startToken)
                    .setEnd_token(endToken);

            if (query.getIncludeEmptyRows() == null) {
                if (query.getPredicate().isSetSlice_range()
                        && query.getPredicate().getSlice_range().getCount() == 0) {
                    bIgnoreTombstones = false;
                }
            } else {
                bIgnoreTombstones = !query.getIncludeEmptyRows();
            }
        }

        @Override
        public boolean hasNext() {
            // Get the next block
            while (iter == null || (!iter.hasNext() && bContinueSearch)) {
                if (lastRow != null) {
                    // Determine the start token for the next page
                    String token = partitioner.getTokenForKey(ByteBuffer.wrap(lastRow.getKey()));
                    if (query.getRepeatLastToken()) {
                        // Start token is non-inclusive
                        range.setStart_token(partitioner.getTokenMinusOne(token));
                    } else {
                        range.setStart_token(token);
                    }
                }

                // Get the next block of rows from cassandra, exit if none returned
                list = query.getNextBlock(range);
                if (list == null || list.isEmpty()) {
                    return false;
                }

                // Since we may trim tombstones set a flag indicating whether a complete
                // block was returned so we can know to try to fetch the next one
                bContinueSearch = (list.size() == query.getBlockSize());

                // Trim the list from tombstoned rows, i.e. rows with no columns
                iter = list.iterator();
                if (iter == null || !iter.hasNext()) {
                    return false;
                }

                KeySlice previousLastRow = lastRow;
                lastRow = Iterables.getLast(list);

                if (query.getRepeatLastToken() && previousLastRow != null) {
                    iter.next();
                    iter.remove();
                }

                if (iter.hasNext() && bIgnoreTombstones) {
                    // Discard any tombstones
                    while (iter.hasNext()) {
                        KeySlice row = iter.next();
                        if (row.getColumns().isEmpty()) {
                            iter.remove();
                        }
                    }

                    // Get the iterator again
                    iter = list.iterator();
                }
            }
            return iter.hasNext();
        }

        @Override
        public Row<K, C> next() {
            org.apache.cassandra.thrift.KeySlice row = iter.next();
            return new ThriftRowImpl<K, C>(columnFamily.getKeySerializer().fromBytes(row.getKey()),
                    ByteBuffer.wrap(row.getKey()), new ThriftColumnOrSuperColumnListImpl<C>(row.getColumns(),
                            columnFamily.getColumnSerializer()));
        }

        @Override
        public void remove() {
            throw new IllegalStateException();
        }
    };
}

From source file:brooklyn.location.softlayer.bms.SoftlayerBmsLocation.java

@Override
public SshMachineLocation obtain(Map<?, ?> flags) throws NoMachinesAvailableException {

    ConfigBag setup = ConfigBag.newInstanceExtending(getAllConfigBag(), flags);
    Integer attempts = setup.get(MACHINE_CREATE_ATTEMPTS);
    List<Exception> exceptions = Lists.newArrayList();
    if (attempts == null || attempts < 1)
        attempts = 1;/*www  .j  a v  a  2s. c o m*/
    for (int i = 1; i <= attempts; i++) {
        try {
            return obtainOnce(setup);
        } catch (RuntimeException e) {
            LOG.warn("Attempt #{}/{} to obtain machine threw error: {}", new Object[] { i, attempts, e });
            exceptions.add(e);
        }
    }
    String msg = format("Failed to get VM after %d attempt%s.", attempts, attempts == 1 ? "" : "s");

    Exception cause = (exceptions.size() == 1) ? exceptions.get(0)
            : new CompoundRuntimeException(msg + " - " + "First cause is " + exceptions.get(0)
                    + " (listed in primary trace); " + "plus " + (exceptions.size() - 1)
                    + " more (e.g. the last is " + exceptions.get(exceptions.size() - 1) + ")",
                    exceptions.get(0), exceptions);

    if (Iterables.getLast(exceptions) instanceof NoMachinesAvailableException) {
        throw new NoMachinesAvailableException(msg, cause);
    } else {
        throw Exceptions.propagate(cause);
    }
}

From source file:com.google.gerrit.server.ApprovalsUtil.java

public void addReviewers(ReviewDb db, LabelTypes labelTypes, Change change, PatchSet ps, PatchSetInfo info,
        Set<Account.Id> wantReviewers, Set<Account.Id> existingReviewers) throws OrmException {
    List<LabelType> allTypes = labelTypes.getLabelTypes();
    if (allTypes.isEmpty()) {
        return;//from w  w w  .  j a  v  a 2s .  co  m
    }

    Set<Account.Id> need = Sets.newHashSet(wantReviewers);
    Account.Id authorId = info.getAuthor() != null ? info.getAuthor().getAccount() : null;
    if (authorId != null && !ps.isDraft()) {
        need.add(authorId);
    }

    Account.Id committerId = info.getCommitter() != null ? info.getCommitter().getAccount() : null;
    if (committerId != null && !ps.isDraft()) {
        need.add(committerId);
    }
    need.remove(change.getOwner());
    need.removeAll(existingReviewers);

    List<PatchSetApproval> cells = Lists.newArrayListWithCapacity(need.size());
    LabelId labelId = Iterables.getLast(allTypes).getLabelId();
    for (Account.Id account : need) {
        PatchSetApproval psa = new PatchSetApproval(new PatchSetApproval.Key(ps.getId(), account, labelId),
                (short) 0);
        psa.cache(change);
        cells.add(psa);
    }
    db.patchSetApprovals().insert(cells);
}

From source file:com.google.security.zynamics.binnavi.API.disassembly.FunctionNode.java

/**
 * Appends a new comment to the node.//from  w w  w.j ava  2  s  . c o  m
 *
 * @param comment The appended node comment.
 *
 * @throws CouldntSaveDataException Thrown if the comment could not be written to the database.
 * @throws CouldntLoadDataException Thrown if the comment could not be loaded after storing it.
 */
public List<IComment> appendComment(final String comment) throws CouldntSaveDataException,
        com.google.security.zynamics.binnavi.API.disassembly.CouldntLoadDataException {

    final List<IComment> comments = new ArrayList<IComment>();

    try {
        comments.addAll(m_node.appendLocalFunctionComment(comment));
    } catch (final com.google.security.zynamics.binnavi.Database.Exceptions.CouldntSaveDataException exception) {
        throw new CouldntSaveDataException(exception);
    } catch (final com.google.security.zynamics.binnavi.Database.Exceptions.CouldntLoadDataException exception) {
        throw new com.google.security.zynamics.binnavi.API.disassembly.CouldntLoadDataException(exception);
    }

    for (final IFunctionNodeListener listener : m_listeners) {
        try {
            listener.appendedComment(this, Iterables.getLast(comments));
        } catch (final Exception exception) {
            CUtilityFunctions.logException(exception);
        }
    }

    return comments;
}

From source file:com.github.fge.jsonpatch.AddOperation.java

private JsonNode addToObject(final JsonPointer path, final JsonNode node) {
    final JsonNode ret = node.deepCopy();
    final ObjectNode target = (ObjectNode) path.parent().get(ret);
    target.set(Iterables.getLast(path).getToken().getRaw(), value);
    return ret;//  w w  w.j  a  v a2 s . c om
}

From source file:org.obm.push.minig.imap.command.Command.java

protected boolean isOk(List<IMAPResponse> rs) {
    return Iterables.getLast(rs).isOk();
}

From source file:com.googlecode.jmxtrans.model.output.StatsDTelegrafWriter.java

private String getBucketType(int resultIndex) {
    if (this.bucketTypes.size() > resultIndex) {
        return bucketTypes.get(resultIndex);
    }//from  ww w .j av a  2  s  .  co m
    return Iterables.getLast(bucketTypes);
}

From source file:org.sonar.java.ast.visitors.MethodVisitor.java

private String extractClassName(AstNode astNode) {
    Preconditions.checkArgument(astNode.is(JavaGrammar.CLASS_TYPE));
    // TODO Godin: verify
    return Iterables.getLast(astNode.getChildren(JavaTokenType.IDENTIFIER)).getTokenValue();
}

From source file:com.google.errorprone.bugpatterns.ClassNewInstance.java

private boolean fixExceptions(final VisitorState state, SuggestedFix.Builder fix) {
    TryTree tryTree = null;/* ww  w  .j  a  va 2 s .co m*/
    OUTER: for (TreePath path = state.getPath(); path != null; path = path.getParentPath()) {
        if (path.getLeaf() instanceof CatchTree) {
            // don't add more catch blocks if newInstance() was called in a catch block
            return false;
        } else if (path.getLeaf() instanceof TryTree && !((TryTree) path.getLeaf()).getCatches().isEmpty()) {
            tryTree = (TryTree) path.getLeaf();
            break;
        }
    }
    if (tryTree == null) {
        return false;
    }
    ImmutableMap.Builder<Type, CatchTree> catches = ImmutableMap.builder();
    for (CatchTree c : tryTree.getCatches()) {
        catches.put(ASTHelpers.getType(c.getParameter().getType()), c);
    }
    UnhandledResult<CatchTree> result = unhandled(catches.build(), state);
    if (result.unhandled.isEmpty()) {
        // no fix needed
        return true;
    }
    {
        // if there's an existing multi-catch at the end that handles reflective exceptions,
        // replace all of them with ROE and leave any non-reflective exceptions.
        // earlier catch blocks are left unchanged.
        CatchTree last = Iterables.getLast(tryTree.getCatches());
        Tree lastType = last.getParameter().getType();
        if (lastType.getKind() == Tree.Kind.UNION_TYPE) {
            Type roe = state.getTypeFromString(ReflectiveOperationException.class.getName());
            Set<String> exceptions = new LinkedHashSet<>();
            boolean foundReflective = false;
            for (Tree alternate : ((UnionTypeTree) lastType).getTypeAlternatives()) {
                if (ASTHelpers.isSubtype(ASTHelpers.getType(alternate), roe, state)) {
                    foundReflective = true;
                    exceptions.add("ReflectiveOperationException");
                } else {
                    exceptions.add(state.getSourceForNode(alternate));
                }
            }
            if (foundReflective) {
                fix.replace(lastType, Joiner.on(" | ").join(exceptions));
                return true;
            }
        }
    }
    // check for duplicated catch blocks that handle reflective exceptions exactly the same way,
    // and merge them into a single block that catches ROE
    Set<String> uniq = new HashSet<>();
    for (CatchTree ct : result.handles.values()) {
        uniq.add(state.getSourceForNode(ct.getBlock()));
    }
    // the catch blocks are all unique, append a new fresh one
    if (uniq.size() != 1) {
        CatchTree last = Iterables.getLast(tryTree.getCatches());
        // borrow the variable name of the previous catch variable, in case the naive 'e' conflicts
        // with something in the current scope
        String name = last.getParameter().getName().toString();
        fix.postfixWith(last, String.format(
                "catch (ReflectiveOperationException %s) {" + " throw new LinkageError(%s.getMessage(), %s); }",
                name, name, name));
        return true;
    }
    // if the catch blocks contain calls to newInstance, don't delete any of them to avoid
    // overlapping fixes
    final AtomicBoolean newInstanceInCatch = new AtomicBoolean(false);
    ((JCTree) result.handles.values().iterator().next()).accept(new TreeScanner() {
        @Override
        public void visitApply(JCTree.JCMethodInvocation tree) {
            if (NEW_INSTANCE.matches(tree, state)) {
                newInstanceInCatch.set(true);
            }
        }
    });
    if (newInstanceInCatch.get()) {
        fix.replace(Iterables.getLast(result.handles.values()).getParameter().getType(),
                "ReflectiveOperationException");
        return true;
    }
    // otherwise, merge the duplicated catch blocks into a single block that
    // handles ROE
    boolean first = true;
    for (CatchTree ct : result.handles.values()) {
        if (first) {
            fix.replace(ct.getParameter().getType(), "ReflectiveOperationException");
            first = false;
        } else {
            fix.delete(ct);
        }
    }
    return true;
}

From source file:de.dennishoersch.web.css.parser.Parser.java

private static List<Style> parseStyles(String styles) {
    Multimap<String, Style> reduced = LinkedHashMultimap.create();
    for (String style_ : _STYLE_SPLITTER.split(styles)) {
        Style style = new Style(style_);
        reduced.put(style.getName(), style);
    }/*ww  w  .j ava 2 s.  co m*/

    // Wenn keiner der Werte zu einem Style ein Vendor-Prefix enthlt, dann
    // kann der letzte alle anderen berschreiben
    List<Style> result = Lists.newArrayList();
    for (Map.Entry<String, Collection<Style>> entry : reduced.asMap().entrySet()) {
        Collection<Style> values = entry.getValue();
        if (Iterables.any(values, HasVendorPrefixValue.INSTANCE)) {
            result.addAll(values);
        } else {
            result.add(Iterables.getLast(values));
        }
    }
    return result;
}