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

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

Introduction

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

Prototype

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

Source Link

Document

Returns the first element in iterable or defaultValue if the iterable is empty.

Usage

From source file:com.google.errorprone.bugpatterns.argumentselectiondefects.Parameter.java

/**
 * Extract the name from an argument.//www.  j a v a  2  s. co m
 *
 * <p>
 *
 * <ul>
 *   <li>IdentifierTree - if the identifier is 'this' then use the name of the enclosing class,
 *       otherwise use the name of the identifier
 *   <li>MemberSelectTree - the name of its identifier
 *   <li>NewClassTree - the name of the class being constructed
 *   <li>Null literal - a wildcard name
 *   <li>MethodInvocationTree - use the method name stripping off 'get', 'set', 'is' prefix. If
 *       this results in an empty name then recursively search the receiver
 * </ul>
 *
 * All other trees (including literals other than Null literal) do not have a name and this method
 * will return the marker for an unknown name.
 */
@VisibleForTesting
static String getArgumentName(ExpressionTree expressionTree) {
    switch (expressionTree.getKind()) {
    case MEMBER_SELECT:
        return ((MemberSelectTree) expressionTree).getIdentifier().toString();
    case NULL_LITERAL:
        // null could match anything pretty well
        return NAME_NULL;
    case IDENTIFIER:
        IdentifierTree idTree = (IdentifierTree) expressionTree;
        if (idTree.getName().contentEquals("this")) {
            // for the 'this' keyword the argument name is the name of the object's class
            Symbol sym = ASTHelpers.getSymbol(idTree);
            return sym != null ? getClassName(ASTHelpers.enclosingClass(sym)) : NAME_NOT_PRESENT;
        } else {
            // if we have a variable, just extract its name
            return idTree.getName().toString();
        }
    case METHOD_INVOCATION:
        MethodInvocationTree methodInvocationTree = (MethodInvocationTree) expressionTree;
        MethodSymbol methodSym = ASTHelpers.getSymbol(methodInvocationTree);
        if (methodSym != null) {
            String name = methodSym.getSimpleName().toString();
            List<String> terms = NamingConventions.splitToLowercaseTerms(name);
            String firstTerm = Iterables.getFirst(terms, null);
            if (METHODNAME_PREFIXES_TO_REMOVE.contains(firstTerm)) {
                if (terms.size() == 1) {
                    ExpressionTree receiver = ASTHelpers.getReceiver(methodInvocationTree);
                    if (receiver == null) {
                        return getClassName(ASTHelpers.enclosingClass(methodSym));
                    }
                    // recursively try to get a name from the receiver
                    return getArgumentName(receiver);
                } else {
                    return name.substring(firstTerm.length());
                }
            } else {
                return name;
            }
        } else {
            return NAME_NOT_PRESENT;
        }
    case NEW_CLASS:
        MethodSymbol constructorSym = ASTHelpers.getSymbol((NewClassTree) expressionTree);
        return constructorSym != null && constructorSym.owner != null
                ? getClassName((ClassSymbol) constructorSym.owner)
                : NAME_NOT_PRESENT;
    default:
        return NAME_NOT_PRESENT;
    }
}

From source file:eu.interedition.collatex.nmerge.graph.MaximalUniqueMatch.java

/**
 * Store in the priority table./*from w  ww  . j  a v  a 2  s . c  o m*/
 *
 * @param start         the nearest node after which the match starts
 * @param graphOffset   the start offset from start in bytes
 * @param matchVersions the versions followed throughout the match
 * @param dataOffset    offset within arc where the alignment starts
 * @param length        the overall path length in bytes
 * @param distance      the distance between graph end and the match
 */
void update(VariantGraphNode<T> start, int graphOffset, Set<Witness> matchVersions, int dataOffset, int length,
        int distance) {
    if (transposed && transposeLeft) {
        distance -= length;
    }
    if (!transposed || withinThreshold(distance, dataOffset, length)) {
        // select first version of match
        Set<Witness> bs = Sets.newHashSet();
        bs.addAll(matchVersions);
        // adjust if alignment is direct
        if (!transposed) {
            bs.retainAll(graph.constraint);
        }
        Witness v = Preconditions.checkNotNull(Iterables.getFirst(bs, null));
        VariantGraphMatch<T> m = new VariantGraphMatch<T>(start, graphOffset, v, dataOffset, length, arc.data);
        VariantGraphMatch<T> q = table.get(m);
        if (q != null) {
            if (!m.overlaps(q)) {
                q.freq++;
            }
            // else it is the same data sharing part of the same
            // path, so it is really the same match
        } else {
            table.put(m, m);
        }
    }
}

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

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

From source file:com.opengamma.integration.viewer.status.impl.ViewStatusResultAggregatorImpl.java

private List<List<Object>> createRowData(final Map<List<String>, Set<String>> fixedRow2Columns,
        final Set<String> extraColumns, List<ViewColumnType> columnTypes) {

    List<List<String>> rows = Lists.newArrayList(fixedRow2Columns.keySet());
    Comparator<List<String>> rowComparator = new Comparator<List<String>>() {

        @Override/* ww w  .j  a  v  a 2  s .co  m*/
        public int compare(List<String> left, List<String> right) {
            int compare = 0;
            for (int i = 0; i < left.size(); i++) {
                compare = left.get(i).compareTo(right.get(i));
                if (compare != 0) {
                    return compare;
                }
            }
            return compare;
        }
    };

    Collections.sort(rows, rowComparator);

    List<List<Object>> processedRows = Lists.newArrayListWithCapacity(rows.size());

    String[] currentRow = new String[Iterables.getFirst(rows, Lists.newArrayList()).size()];
    for (List<String> row : rows) {
        List<Object> processedRow = Lists.newArrayList();
        Iterable<String> columns = Iterables.limit(row, row.size() - 1);
        int count = 0;
        for (String col : columns) {
            if (currentRow[count] == null || !col.equals(currentRow[count])) {
                currentRow[count] = col;
                processedRow.add(col);
            } else {
                processedRow.add(EMPTY_STR);
            }
            count++;
        }
        processedRow.add(Iterables.getLast(row));

        for (String col : extraColumns) {
            List<String> keyMemebers = Lists.newArrayList(row);
            keyMemebers.add(col);
            ViewStatus status = getStatus(keyFromRowValues(keyMemebers, columnTypes));
            if (status == null) {
                processedRow.add(EMPTY_STR);
            } else {
                processedRow.add(status);
            }
        }
        processedRows.add(processedRow);
    }
    return processedRows;
}

From source file:org.sonar.plsqlopen.checks.verifier.PlSqlCheckVerifier.java

private void assertSingleIssue(Collection<AnalyzerMessage> issues) {
    Preconditions.checkState(issues.size() == 1,
            "A single issue is expected with line " + expectFileIssueOnline);
    AnalyzerMessage issue = Iterables.getFirst(issues, null);
    assertThat(issue.getLine()).isEqualTo(expectFileIssueOnline);
    assertThat(issue.getText(Locale.ENGLISH)).isEqualTo(expectFileIssue);
}

From source file:org.apache.james.transport.mailets.remoteDelivery.MailDelivrer.java

private String retrieveTargetHostname(Mail mail) {
    Preconditions.checkArgument(!mail.getRecipients().isEmpty(),
            "Mail should have recipients to attempt delivery");
    MailAddress rcpt = Iterables.getFirst(mail.getRecipients(), null);
    return rcpt.getDomain();
}

From source file:org.apache.james.rrt.lib.MappingsImpl.java

@Override
public Mapping getError() {
    Mappings errors = select(Type.Error);
    Preconditions.checkState(!errors.isEmpty());
    return Iterables.getFirst(errors, null);
}

From source file:org.apache.james.transport.mailets.remote.delivery.MailDelivrer.java

private Domain retrieveTargetHostname(Mail mail) {
    Preconditions.checkArgument(!mail.getRecipients().isEmpty(),
            "Mail should have recipients to attempt delivery");
    MailAddress rcpt = Iterables.getFirst(mail.getRecipients(), null);
    return rcpt.getDomain();
}

From source file:org.apache.aurora.scheduler.storage.mem.MemJobUpdateStore.java

private static JobUpdateState synthesizeUpdateState(JobUpdateDetails update) {
    JobUpdateState state = new JobUpdateState();

    JobUpdateEvent firstEvent = Iterables.getFirst(update.getUpdateEvents(), null);
    if (firstEvent != null) {
        state.setCreatedTimestampMs(firstEvent.getTimestampMs());
    }// w w w .j av  a 2 s  .c  om

    JobUpdateEvent lastEvent = Iterables.getLast(update.getUpdateEvents(), null);
    if (lastEvent != null) {
        state.setStatus(lastEvent.getStatus());
        state.setLastModifiedTimestampMs(lastEvent.getTimestampMs());
    }

    JobInstanceUpdateEvent lastInstanceEvent = Iterables.getLast(update.getInstanceEvents(), null);
    if (lastInstanceEvent != null) {
        state.setLastModifiedTimestampMs(
                Longs.max(state.getLastModifiedTimestampMs(), lastInstanceEvent.getTimestampMs()));
    }

    return state;
}

From source file:fr.mby.opa.picsimpl.dao.DbAlbumDao.java

@Override
public Album loadAlbumById(final Long id) {
    Assert.notNull(id, "Album Id should be supplied !");

    final EmCallback<Album> emCallback = new EmCallback<Album>(this.getEmf()) {

        @Override/* w w w.j a v  a  2 s.c om*/
        @SuppressWarnings("unchecked")
        protected Album executeWithEntityManager(final EntityManager em) throws PersistenceException {
            final Query findByIdQuery = em.createNamedQuery(Album.LOAD_FULL_ALBUM_BY_ID);
            findByIdQuery.setParameter("id", id);

            final Album album = Iterables.getFirst(findByIdQuery.getResultList(), null);
            return album;
        }
    };

    return emCallback.getReturnedValue();
}