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:eu.interedition.collatex.nmerge.graph.MaximalUniqueMatch.java

/**
 * Construct a MUM//from   ww w  .jav  a2s  .com
 *
 * @param arc        the current or final arc not included yet in path
 * @param graph      the graph to direct align to
 * @param transposed if true we are transposed
 */
MaximalUniqueMatch(VariantGraphSpecialArc<T> arc, VariantGraph<T> graph, boolean transposed) {
    this.arc = arc;
    this.version = Iterables.getFirst(arc.versions, null);
    this.graph = graph;
    this.transposed = transposed;
    table = new HashMap<VariantGraphMatch<T>, VariantGraphMatch<T>>(INITIAL_QUEUE_LEN);
}

From source file:tiger.NewDependencyCollector.java

/**
 * Add dependencies from ctor injected classes needed by requiredKeys recursively to result.
 *///from  w w  w.j  a  v  a 2s .  c  o m
private void addDependenciesForRequiredKeys(SetMultimap<NewBindingKey, NewDependencyInfo> result,
        Set<NewBindingKey> requiredKeys) {
    // Added all the required dependencies from ctor injected classes.
    while (!requiredKeys.isEmpty()) {
        NewBindingKey key = Iterables.getFirst(requiredKeys, null);
        Preconditions.checkNotNull(key);
        requiredKeys.remove(key);
        if (result.containsKey(key)) {
            continue;
        }

        TypeName typeName = key.getTypeName();
        if (Utils.hasBuiltinBinding(typeName)) {
            key = Utils.getElementKeyForBuiltinBinding(key);
            requiredKeys.add(key);
            continue;
        }

        if (Utils.isMapWithBuiltinValueType(key)) {
            NewBindingKey peeledMapKey = Preconditions.checkNotNull(Utils.peelMapWithBuiltinValue(key));
            requiredKeys.add(peeledMapKey);
            continue;
        }

        ClassName className;
        if (typeName instanceof ClassName) {
            className = (ClassName) typeName;
        } else {
            Preconditions.checkState(typeName instanceof ParameterizedTypeName, "Expect a %s but get %s",
                    ParameterizedTypeName.class, typeName);
            ParameterizedTypeName parameterizedTypeName = (ParameterizedTypeName) typeName;
            for (TypeName parameter : parameterizedTypeName.typeArguments) {
                Preconditions.checkState(
                        parameter instanceof ClassName || parameter instanceof ParameterizedTypeName,
                        String.format("Unexpected parameter type %s for type %s.", parameter, typeName));
            }
            NewDependencyInfo dependencyInfo = Utils.getDependencyInfoByGeneric(result, key);
            if (dependencyInfo != null) {
                requiredKeys.addAll(dependencyInfo.getDependencies());
                continue;
            } else {
                className = ((ParameterizedTypeName) typeName).rawType;
            }
        }
        TypeElement classTypeElement = env.getElementUtils()
                .getTypeElement(Utils.getClassCanonicalName(className));
        Preconditions.checkNotNull(classTypeElement, String.format("Class %s not found.", className));
        Collection<NewDependencyInfo> dependencies = collectFromCtorInjectedClass(classTypeElement);
        if (dependencies == null) {
            messager.printMessage(Kind.ERROR, String.format("Binding not found for %s", key));
            continue;
        }
        NewDependencyInfo dependency = Iterables.getOnlyElement(dependencies);
        if (typeName instanceof ParameterizedTypeName) {
            Map<TypeVariableName, TypeName> parameterMap = Utils.getMapFromTypeVariableToSpecialized(
                    (ParameterizedTypeName) typeName,
                    (ParameterizedTypeName) dependency.getDependant().getTypeName());
            requiredKeys.addAll(Utils.specializeIfNeeded(dependency.getDependencies(), parameterMap));
        } else {
            requiredKeys.addAll(dependency.getDependencies());
        }
        checkOneDependency(result, dependency);
        addDependencyInfo(result, dependency);
    }
}

From source file:org.vclipse.vcml.utils.SimplifyingVcmlUtils.java

public Statement mkSimplifiedCompoundStatement(final SimpleStatement... statements) {
    Iterable<SimpleStatement> statementsNonNull = Iterables.filter(Lists.newArrayList(statements),
            Predicates.notNull());/*  ww  w  .j a v a  2s  . com*/
    switch (Iterables.size(statementsNonNull)) {
    case 0:
        return null;
    case 1:
        return Iterables.getFirst(statementsNonNull, null);
    default:
        final CompoundStatement compoundStatement = mkCompoundStatement();
        compoundStatement.getStatements().addAll(Lists.newArrayList(statementsNonNull));
        return compoundStatement;
    }
}

From source file:org.obm.push.mail.MailMessageLoader.java

private MimeMessage getFirstMimeMessage(final List<Long> messageIdAsList) {
    final Collection<MimeMessage> mts = storeClient.uidFetchBodyStructure(messageIdAsList);
    final MimeMessage tree = Iterables.getFirst(mts, null);
    return tree;/*from  ww  w  .j  a  va 2 s. c o  m*/
}

From source file:org.trancecode.collection.TcIterables.java

/**
 * Returns the first non-null element from the specified sequence, or the
 * specified default value if all elements from the sequence were
 * {@code null}.// w  w  w .  ja  v  a  2  s.  com
 */
public static <T> T getFirstNonNull(final Iterable<T> elements, final T defaultValue) {
    return Iterables.getFirst(Iterables.filter(elements, Predicates.notNull()), defaultValue);
}

From source file:ratpack.server.internal.DefaultPublicAddress.java

private HostAndPort getForwardedHostData(Context context) {
    Headers headers = context.getRequest().getHeaders();
    String forwardedHostHeader = Strings.emptyToNull(headers.get(X_FORWARDED_HOST.toString()));
    String hostPortString = forwardedHostHeader != null
            ? Iterables.getFirst(FORWARDED_HOST_SPLITTER.split(forwardedHostHeader), null)
            : null;/*from   w  w  w.j a v a 2 s  .  com*/
    return hostPortString != null ? HostAndPort.fromString(hostPortString) : null;
}

From source file:org.elasticsearch.index.query.IdsQueryParser.java

@Override
public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException {
    XContentParser parser = parseContext.parser();

    List<BytesRef> ids = new ArrayList<>();
    Collection<String> types = null;
    String currentFieldName = null;
    float boost = 1.0f;
    String queryName = null;//ww w . j  a v a  2  s . c o m
    XContentParser.Token token;
    boolean idsProvided = false;
    while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
        if (token == XContentParser.Token.FIELD_NAME) {
            currentFieldName = parser.currentName();
        } else if (token == XContentParser.Token.START_ARRAY) {
            if ("values".equals(currentFieldName)) {
                idsProvided = true;
                while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
                    BytesRef value = parser.bytesOrNull();
                    if (value == null) {
                        throw new QueryParsingException(parseContext.index(),
                                "No value specified for term filter");
                    }
                    ids.add(value);
                }
            } else if ("types".equals(currentFieldName) || "type".equals(currentFieldName)) {
                types = new ArrayList<>();
                while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
                    String value = parser.textOrNull();
                    if (value == null) {
                        throw new QueryParsingException(parseContext.index(),
                                "No type specified for term filter");
                    }
                    types.add(value);
                }
            } else {
                throw new QueryParsingException(parseContext.index(),
                        "[ids] query does not support [" + currentFieldName + "]");
            }
        } else if (token.isValue()) {
            if ("type".equals(currentFieldName) || "_type".equals(currentFieldName)) {
                types = ImmutableList.of(parser.text());
            } else if ("boost".equals(currentFieldName)) {
                boost = parser.floatValue();
            } else if ("_name".equals(currentFieldName)) {
                queryName = parser.text();
            } else {
                throw new QueryParsingException(parseContext.index(),
                        "[ids] query does not support [" + currentFieldName + "]");
            }
        }
    }

    if (!idsProvided) {
        throw new QueryParsingException(parseContext.index(), "[ids] query, no ids values provided");
    }

    if (ids.isEmpty()) {
        return Queries.newMatchNoDocsQuery();
    }

    if (types == null || types.isEmpty()) {
        types = parseContext.queryTypes();
    } else if (types.size() == 1 && Iterables.getFirst(types, null).equals("_all")) {
        types = parseContext.mapperService().types();
    }

    TermsFilter filter = new TermsFilter(UidFieldMapper.NAME, Uid.createTypeUids(types, ids));
    // no need for constant score filter, since we don't cache the filter, and it always takes deletes into account
    ConstantScoreQuery query = new ConstantScoreQuery(filter);
    query.setBoost(boost);
    if (queryName != null) {
        parseContext.addNamedQuery(queryName, query);
    }
    return query;
}

From source file:eu.interedition.collatex.suffixtree.SuffixTree.java

/**
 * Starts Ukkonen's construction algorithm by calling SPA n times, where
 * n is the length of the source string.
 *
 * @param str the source string is a sequence of unsigned characters
 *            (maximum of 256 different symbols). In the original algorithm '$'
 *            was a special character. However,http://www.abc.net.au/news/ in Yona's
 *            version it is appended at the end of the input string and then never used.
 */// w w  w . j a  va2 s  .  c  o m
@SuppressWarnings("unchecked")
private SuffixTree(Iterable<T> str, Comparator<T> comparator) {
    this.length = Iterables.size(str) + 1;
    Preconditions.checkArgument(this.length > 1);
    this.source = (T[]) Array.newInstance(Iterables.getFirst(str, null).getClass(), this.length + 1);
    this.comparator = comparator;
    this.virtualEnd = 1; // added to make 1-character suffix trees work

    int i = 0;
    for (T t : str) {
        this.source[++i] = t;
    }
    // the terminal ('$') is never examined but assumed to be there
    this.source[length] = null;

    this.root = new Node(this, null, 0, 0, 0);

    // allocating first node, child of the root (phase 0), the longest
    // path node
    this.root.firstChild = new Node(this, root, 1, length, 1);
}

From source file:com.google.devtools.build.skyframe.EvaluationResult.java

/**
 * Returns some error info. Convenience method equivalent to
 * Iterables.getFirst({@link #errorMap()}, null).getValue().
 *//*from   ww w  .  ja v  a2 s. com*/
public ErrorInfo getError() {
    return Iterables.getFirst(errorMap.entrySet(), null).getValue();
}

From source file:ninja.utils.FakeContext.java

@Override
public String getParameter(String key) {
    return Iterables.getFirst(params.get(key), null);
}