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:io.druid.server.initialization.jetty.JettyServerModule.java

@Provides
@LazySingleton//w  ww . j  av  a2  s .c  om
public Server getServer(Injector injector, Lifecycle lifecycle, @Self DruidNode node, ServerConfig config) {
    JettyServerInitializer initializer = injector.getInstance(JettyServerInitializer.class);

    final Server server = makeJettyServer(node, config);
    try {
        initializer.initialize(server, injector);
    } catch (ConfigurationException e) {
        throw new ProvisionException(Iterables.getFirst(e.getErrorMessages(), null).getMessage());
    }

    lifecycle.addHandler(new Lifecycle.Handler() {
        @Override
        public void start() throws Exception {
            server.start();
        }

        @Override
        public void stop() {
            try {
                server.stop();
            } catch (Exception e) {
                log.warn(e, "Unable to stop Jetty server.");
            }
        }
    });
    return server;
}

From source file:org.loadui.testfx.service.finder.impl.NodeFinderImpl.java

public Node node(Matcher<Object> matcher) {
    Set<Node> resultNodes = nodes(matcher);
    return Iterables.getFirst(resultNodes, null);
}

From source file:com.davidbracewell.data.DataFrame.java

private DataFrame slice(Iterable<Row> rows) {
    if (rows != null) {
        Row first = Iterables.getFirst(rows, null);
        if (first != null) {
            return new DataFrame(first.dataFrame.columnNames, rows);
        }/*from w  w  w . ja v a  2 s.c o  m*/
    }
    return new DataFrame();
}

From source file:minium.actions.internal.AbstractInteraction.java

/**
 * Gets the first.// w ww . j  a v a  2 s . c  o m
 *
 * @param elems
 *            the elems
 * @return the first
 */
protected Elements getFirst(Elements elems) {
    @SuppressWarnings("unchecked")
    IterableElements<Elements> iterableElems = elems.as(IterableElements.class);
    return Iterables.getFirst(iterableElems, null);
}

From source file:org.tensorics.core.tensor.variance.CoContraDimensionPairs.java

/**
 * Choses one pair for a type of dimension to use. The current algorithm is:
 * <ul>//  w  ww .j  a  va 2  s . c  om
 * <li>If only one pair is available (how it should be in most cases), then this one is returned.
 * <li>If two are present, then the one which is covariant on the left is preferred
 * <li>If none is contained in the collection or none which is covariant in the left shape, then an exception is
 * thrown (This is an inconsistent state!)
 * </ul>
 * 
 * @param pairsForOneDimension the pairs from which to choose one
 * @return one pair to use for that dimension
 */
private static CoContraDimensionPair choose(Collection<CoContraDimensionPair> pairsForOneDimension) {
    checkState(!pairsForOneDimension.isEmpty(),
            "No pairs of dimension found for one dimension-type. " + "Must be some wrong call to this method.");
    if (pairsForOneDimension.size() == 1) {
        return Iterables.getFirst(pairsForOneDimension, null);
    }

    checkState(pairsForOneDimension.size() <= 2, "More then 2 matching co- contravariant dimension found "
            + "for the same contravariant dimension. This should not be possible!?");
    for (CoContraDimensionPair pair : pairsForOneDimension) {
        if (Covariants.isCovariant(pair.left())) {
            return pair;
        }
    }
    throw new IllegalStateException("No valid dimension pair could be found within the collection.");
}

From source file:com.flexive.rest.FxRestApiUtils.java

/**
 * Apply common request parameters such as the requested language. Call this before <em>any</em> API call
 * as it processes security configuration and sets request context information that will be used later.
 *
 * <p>//from w  ww  .  j  a v  a2  s  . c o m
 *     This method is called automatically on JAX-RS classes or methods annotated with {@link com.flexive.rest.interceptors.FxRestApi @FxRestApi}.
 * </p>
 */
public static void applyRequestParameters(HttpHeaders headers, UriInfo uriInfo) throws FxApplicationException {
    final MultivaluedMap<String, String> queryParameters = uriInfo.getQueryParameters(true);

    if (!isRequestContextAvailable()) {
        // set context for the first request only, subsequent JAX-RS handler invocations in this request
        // should reuse the existing context
        FxContext.get().setAttribute(CTX_REQUEST, new RequestContext(headers, uriInfo));
    }

    // get access token
    String token = queryParameters.getFirst(FxRestApiConst.HEADER_TOKEN);
    if (token == null && headers.getRequestHeader(FxRestApiConst.HEADER_TOKEN) != null) {
        token = Iterables.getFirst(headers.getRequestHeader(FxRestApiConst.HEADER_TOKEN), null);
    }
    if (StringUtils.isNotBlank(token)) {
        EJBLookup.getAccountEngine().loginByRestToken(token);
    }
    if (FxContext.getUserTicket().isGuest() && !FxBasicFilter.isGuestAccessAllowed()) {
        throw new GuestAccessDisabledException();
    }

    final String lang = queryParameters.getFirst("lang");
    if (StringUtils.isNotBlank(lang)) {
        // override request user's language
        final FxLanguage overrideLang;
        if (StringUtils.isNumeric(lang)) {
            overrideLang = CacheAdmin.getEnvironment().getLanguage(Long.parseLong(lang));
        } else {
            overrideLang = CacheAdmin.getEnvironment().getLanguage(lang);
        }
        FxContext.getUserTicket().setLanguage(overrideLang);
    }
}

From source file:com.google.security.zynamics.binnavi.yfileswrap.Gui.GraphWindows.NodeChooser.CNodeChooserRenderer.java

/**
 * Returns the text to be shown in the node chooser table for a given node.
 *
 * @param node The node to display./*  w  w w . j a v  a 2  s. c  o  m*/
 *
 * @return The display text of the node.
 */
private static String getNodeText(final INaviViewNode node) {
    if (node instanceof INaviFunctionNode) {
        return ((INaviFunctionNode) node).getFunction().getName();
    } else if (node instanceof INaviCodeNode) {
        return Iterables.getFirst(((INaviCodeNode) node).getInstructions(), null).getAddress().toHexString();
    } else if (node instanceof INaviGroupNode) {
        return "GroupNode"; // ((INaviGroupNode) node).getComment(); //TODO fix this.
    } else if (node instanceof INaviTextNode) {
        return "Comment node";
    } else {
        throw new IllegalStateException("IE01152: Invalid node in node chooser");
    }
}

From source file:org.obm.servlet.filter.qos.handlers.RequestInfo.java

public ContinuationId nextContinuation() {
    return Iterables.getFirst(continuationIds, null);
}

From source file:org.apache.whirr.service.hadoop.HadoopConfigurationBuilder.java

@VisibleForTesting
static Configuration buildMapReduceConfiguration(ClusterSpec clusterSpec, Cluster cluster,
        Configuration defaults) throws ConfigurationException, IOException {
    Configuration config = build(clusterSpec, cluster, defaults, "hadoop-mapreduce");

    Set<Instance> taskTrackers = cluster.getInstancesMatching(role(HadoopTaskTrackerClusterActionHandler.ROLE));

    if (!taskTrackers.isEmpty()) {

        Hardware hardware = Iterables.getFirst(taskTrackers, null).getNodeMetadata().getHardware();

        /* null when using the BYON jclouds compute provider */
        if (hardware != null) {

            int coresPerNode = 0;
            for (Processor processor : hardware.getProcessors()) {
                coresPerNode += processor.getCores();
            }/*from w  ww .  j av  a  2 s.co  m*/
            int mapTasksPerNode = (int) Math.ceil(coresPerNode * 1.0);
            int reduceTasksPerNode = (int) Math.ceil(coresPerNode * 0.75);

            setIfAbsent(config, "mapred.tasktracker.map.tasks.maximum", mapTasksPerNode + "");
            setIfAbsent(config, "mapred.tasktracker.reduce.tasks.maximum", reduceTasksPerNode + "");

            int clusterReduceSlots = taskTrackers.size() * reduceTasksPerNode;
            setIfAbsent(config, "mapred.reduce.tasks", clusterReduceSlots + "");

        }
    }

    Set<Instance> jobtracker = cluster.getInstancesMatching(role(HadoopJobTrackerClusterActionHandler.ROLE));
    if (!jobtracker.isEmpty()) {
        config.setProperty("mapred.job.tracker",
                String.format("%s:8021", Iterables.getOnlyElement(jobtracker).getPublicHostName()));
    }

    return config;
}

From source file:org.apache.brooklyn.core.mgmt.rebind.InitialFullRebindIteration.java

@Override
protected void loadManifestFiles() throws Exception {
    checkEnteringPhase(1);/*from  ww  w. j  a  va 2  s  . c  om*/
    Preconditions.checkState(mementoRawData == null,
            "Memento raw data should not yet be set when calling this");
    mementoRawData = persistenceStoreAccess.loadMementoRawData(exceptionHandler);

    preprocessManifestFiles();

    if (!isEmpty) {
        if (!ManagementNodeState.isHotProxy(mode) || readOnlyRebindCount.get() == 1) {
            LOG.info("Rebinding from " + getPersister().getBackingStoreDescription() + " for "
                    + Strings.toLowerCase(Strings.toString(mode)) + " "
                    + managementContext.getManagementNodeId() + "...");
        }
    } else {
        if (!ManagementNodeState.isHotProxy(mode)) {
            LOG.info("Rebind check: no existing state; will persist new items to "
                    + getPersister().getBackingStoreDescription());
        }
    }
    if (!ManagementNodeState.isHotProxy(mode)) {
        if (!managementContext.getEntityManager().getEntities().isEmpty()
                || !managementContext.getLocationManager().getLocations().isEmpty()) {
            // this is discouraged if we were already master
            Entity anEntity = Iterables.getFirst(managementContext.getEntityManager().getEntities(), null);
            if (anEntity != null && !((EntityInternal) anEntity).getManagementSupport().isReadOnly()) {
                // NB: there is some complexity which can happen in this situation; "initial-full" rebind really expected everything is being
                // initially bound from persisted state, and completely so; "active-partial" is much more forgiving.
                // one big difference is in behaviour of management: it is recursive for most situations, and initial-full assumes recursive,
                // but primary-primary is *not* recursive;
                // as a result some "new" entities created during rebind might be left unmanaged; they should get GC'd,
                // but it's possible the new entity impl or even a new proxy could leak.
                // see HighAvailabilityManagerInMemoryTest.testLocationsStillManagedCorrectlyAfterDoublePromotion
                // (i've plugged the known such leaks, but still something to watch out for); -Alex 2015-02
                overwritingMaster = true;
                LOG.warn("Rebind requested for " + mode + " node " + managementContext.getManagementNodeId()
                        + " " + "when it already has active state; discouraged, " + "will likely overwrite: "
                        + managementContext.getEntityManager().getEntities() + " and "
                        + managementContext.getLocationManager().getLocations() + " and more");
            }
        }
    }
}