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.b2international.snowowl.datastore.cdo.CDOConnectionFactoryProvider.java

public ICDOConnectionFactory getConnectionFactory() {
    final List<IConfigurationElement> factories = Lists
            .newArrayList(Platform.getExtensionRegistry().getConfigurationElementsFor(CONNECTION_FACTORY_ID));

    if (CompareUtils.isEmpty(factories)) {
        throw new RuntimeException("There are no CDO connection factory registered to the application."
                + "\nConnection factory can be added via 'connectionFactory.exsd' extension point. See also: "
                + ICDOConnectionFactory.class.getName());
    }/*from  ww w  . j  a  v a2  s. c  o m*/

    if (factories.size() > 1) {
        LOGGER.warn("More than one CDO connection factory are registered to the application. "
                + "The first applicable is configured to the application.");
    }

    final IConfigurationElement configurationElement = Iterables.getFirst(factories, null);

    Object extension = null;
    try {
        extension = configurationElement.createExecutableExtension(CLASS_ATTRIBUTE_ID);
    } catch (final CoreException e) {
        LOGGER.error("Error while creating executable extension for " + configurationElement);
        //intentionally fall through
    }

    if (extension instanceof ICDOConnectionFactory) {
        return (ICDOConnectionFactory) extension;
    }

    throw new RuntimeException(
            "Error while creating executable extension for 'connection factory' extension point.");
}

From source file:com.google.idea.blaze.base.run.rulefinder.RuleFinder.java

@Nullable
public RuleIdeInfo findFirstRule(Project project, Predicate<RuleIdeInfo> predicate) {
    return Iterables.getFirst(findRules(project, predicate), null);
}

From source file:org.jclouds.virtualbox.domain.StorageController.java

public HardDisk getHardDisk(String diskName) {

    final Iterable<HardDisk> hardDisks = filter(getHardDisks(), new HardDiskPredicate(diskName));
    return Iterables.getFirst(hardDisks,
            HardDisk.builder().diskpath("notfound").controllerPort(0).deviceSlot(0).build());
}

From source file:com.google.devtools.build.lib.repository.ExternalPackageUtil.java

/**
 * Loads the external package and then calls the selector to find matching rules.
 *
 * @param env the environment to use for lookups
 * @param returnFirst whether to return only the first rule found
 * @param selector the function to call to load rules
 *///from ww w. j a v  a2s.  c  om
@Nullable
private static List<Rule> getRules(Environment env, boolean returnFirst,
        Function<Package, Iterable<Rule>> selector) throws ExternalPackageException, InterruptedException {
    SkyKey packageLookupKey = PackageLookupValue.key(Label.EXTERNAL_PACKAGE_IDENTIFIER);
    PackageLookupValue packageLookupValue = (PackageLookupValue) env.getValue(packageLookupKey);
    if (packageLookupValue == null) {
        return null;
    }
    RootedPath workspacePath = packageLookupValue.getRootedPath(Label.EXTERNAL_PACKAGE_IDENTIFIER);

    List<Rule> rules = ImmutableList.of();
    SkyKey workspaceKey = WorkspaceFileValue.key(workspacePath);
    do {
        WorkspaceFileValue value = (WorkspaceFileValue) env.getValue(workspaceKey);
        if (value == null) {
            return null;
        }
        Package externalPackage = value.getPackage();
        if (externalPackage.containsErrors()) {
            Event.replayEventsOn(env.getListener(), externalPackage.getEvents());
            throw new ExternalPackageException(
                    new BuildFileContainsErrorsException(Label.EXTERNAL_PACKAGE_IDENTIFIER,
                            "Could not load //external package"),
                    Transience.PERSISTENT);
        }
        Iterable<Rule> results = selector.apply(externalPackage);
        if (results != null) {
            rules = ImmutableList.copyOf(results);
            if (returnFirst && !rules.isEmpty()) {
                return ImmutableList.of(Iterables.getFirst(results, null));
            }
        }
        workspaceKey = value.next();
    } while (workspaceKey != null);

    return rules;
}

From source file:eu.interedition.collatex.dekker.DekkerAlgorithm.java

@Override
public void collate(VariantGraph graph, Iterable<Token> tokens) {
    Preconditions.checkArgument(!Iterables.isEmpty(tokens), "Empty witness");
    final Witness witness = Iterables.getFirst(tokens, null).getWitness();

    if (LOG.isTraceEnabled()) {
        LOG.trace("{} + {}: {} vs. {}", new Object[] { graph, witness, graph.vertices(), tokens });
    }//from   w  w w.j a v  a 2 s  . c  o m

    LOG.debug("{} + {}: Match and link tokens", graph, witness);
    tokenLinks = tokenLinker.link(graph, tokens, comparator);
    if (LOG.isTraceEnabled()) {
        for (Map.Entry<Token, VariantGraphVertex> tokenLink : tokenLinks.entrySet()) {
            LOG.trace("{} + {}: Token match: {} = {}",
                    new Object[] { graph, witness, tokenLink.getValue(), tokenLink.getKey() });
        }
    }

    LOG.debug("{} + {}: Detect phrase matches", graph, witness);
    phraseMatches = phraseMatchDetector.detect(tokenLinks, graph, tokens);
    if (LOG.isTraceEnabled()) {
        for (List<Match> phraseMatch : phraseMatches) {
            LOG.trace("{} + {}: Phrase match: {}",
                    new Object[] { graph, witness, Iterables.toString(phraseMatch) });
        }
    }

    LOG.debug("{} + {}: Detect transpositions", graph, witness);
    transpositions = transpositionDetector.detect(phraseMatches, graph);
    if (LOG.isTraceEnabled()) {
        for (List<Match> transposition : transpositions) {
            LOG.trace("{} + {}: Transposition: {}",
                    new Object[] { graph, witness, Iterables.toString(transposition) });
        }
    }

    LOG.debug("{} + {}: Determine aligned tokens by filtering transpositions", graph, witness);
    alignments = Maps.newHashMap(tokenLinks);

    for (List<Match> transposedPhrase : transpositions) {
        for (Match match : transposedPhrase) {
            alignments.remove(match.token);
        }
    }
    if (LOG.isTraceEnabled()) {
        for (Map.Entry<Token, VariantGraphVertex> alignment : alignments.entrySet()) {
            LOG.trace("{} + {}: Alignment: {} = {}",
                    new Object[] { graph, witness, alignment.getValue(), alignment.getKey() });
        }
    }

    merge(graph, tokens, alignments);
    mergeTranspositions(graph, transpositions);

    if (LOG.isTraceEnabled()) {
        LOG.trace("!{}: {}", graph, Iterables.toString(graph.vertices()));
    }
}

From source file:com.spotify.asyncdatastoreclient.QueryResult.java

/**
 * Return the first entity returned from the query or null if not found.
 *
 * This is a shortcut for {@code getAll().get(0)}
 *
 * @return an entity returned from the Datastore.
 *//*ww  w  .j  a  va2s  .co m*/
public Entity getEntity() {
    return Iterables.getFirst(entities, null);
}

From source file:org.n52.sos.decode.xml.stream.NillableReader.java

@Override
protected void begin() throws XMLStreamException, OwsExceptionReport {
    Optional<String> attr = attr(W3CConstants.QN_XSI_NIL);
    if (attr.isPresent() && attr.get().equals("true")) {
        List<QName> attributeNames = getPossibleNilReasonAttributes();
        Iterable<Optional<String>> attributes = attr(attributeNames);
        Iterable<String> reasons = Optional.presentInstances(attributes);
        this.nillable = Nillable.nil(Iterables.getFirst(reasons, null));
    } else {//  w w  w.j  av a2  s. co  m
        this.nillable = Nillable.of(delegate(getDelegate()));
    }
}

From source file:org.jclouds.cloudtransformer.openstack.CreateDevstackNode.java

@Override
public NodeMetadata apply(ComputeServiceContext input) {
    ComputeService original = input.getComputeService();

    logger.info("Creating devstack node on provider: %s", input.getProviderSpecificContext().getDescription());
    NodeMetadata devstackNode;/*from   w  w  w  . j  a v a 2  s .  c  om*/

    try {
        devstackNode = Iterables.getOnlyElement(input.getComputeService().createNodesInGroup("devstack", 1));
    } catch (RunNodesException e) {
        throw Throwables.propagate(e);
    }
    original.runScriptOnNode(devstackNode.getId(), AdminAccess.standard());
    String address = Iterables.getFirst(devstackNode.getPublicAddresses(), null);
    logger.info("Running devstack script on node: [id= " + devstackNode.getId() + " address= " + address + "]");
    try {
        checkState(original.submitScriptOnNode(devstackNode.getId(), Devstack.inVm(), RunScriptOptions.NONE)
                .get(20, TimeUnit.MINUTES).getExitStatus() == 0);
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
    logger.info("Devstack installed. Dashboard available at: http://%s Ssh available at: ssh me@%s", address,
            address);
    return devstackNode;

}

From source file:org.opendaylight.netconf.notifications.impl.ops.NotificationsTransformUtil.java

private static RpcDefinition findCreateSubscriptionRpc() {
    return Iterables.getFirst(
            Collections2.filter(NOTIFICATIONS_SCHEMA_CTX.getOperations(), new Predicate<RpcDefinition>() {
                @Override/*  w w  w .j a  v  a2  s.c o m*/
                public boolean apply(final RpcDefinition input) {
                    return input.getQName().getLocalName().equals(CreateSubscription.CREATE_SUBSCRIPTION);
                }
            }), null);
}

From source file:org.eclipse.elk.tree.TreeUtil.java

/**
 * This method returns the leftmost node at the given level. This is implemented using a
 * postorder walk of the subtree under given level, depth levels down. Depth here refers to the
 * level below where the leftmost descendant is being found.
 * /*from  w  ww.  j a  v  a2s.c om*/
 * If given level is negative it returns the leftmost node at the deepest level.
 * 
 * @param currentlevel
 *            a list of nodes at level one
 * @param depth
 *            the depth to search for
 * @return the leftmost descendant at depth levels down
 */
public static TNode getLeftMost(final Iterable<TNode> currentlevel, final int depth) {
    if (0 < Iterables.size(currentlevel)) {
        int d = depth;

        // the leftmost descendant at depth levels down
        if (1 < d) {
            d--;
            // build empty iterator
            Iterable<TNode> nextLevel = new Iterable<TNode>() {

                public Iterator<TNode> iterator() {
                    return Iterators.emptyIterator();
                }
            };

            for (TNode cN : currentlevel) {
                // append the children of the current node to the next level
                nextLevel = Iterables.concat(nextLevel, cN.getChildren());
            }
            return getLeftMost(nextLevel, d);
        }

        // the leftmost node at the deepest level
        if (d < 0) {
            // build empty iterator
            Iterable<TNode> nextLevel = new Iterable<TNode>() {

                public Iterator<TNode> iterator() {
                    return Iterators.emptyIterator();
                }
            };

            for (TNode cN : currentlevel) {
                // append the children of the current node to the next level
                nextLevel = Iterables.concat(nextLevel, cN.getChildren());
            }

            //
            if (0 < Iterables.size(nextLevel)) {
                return getLeftMost(nextLevel, d);
            }
        }
    }
    // return the leftmost node at the current level
    return Iterables.getFirst(currentlevel, null);
}