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:org.eclipse.xtext.xbase.ui.debug.JavaBreakPointProvider.java

private IEclipseTrace getJavaTrace(final IJavaStratumLineBreakpoint breakpoint) throws CoreException {
    IEclipseTrace result;// ww w  .  j a  v a2 s  .c o m
    IClassFile classFile = getClassFile(breakpoint);
    if (classFile == null) {
        URI uri = URI.createURI((String) breakpoint.getMarker()
                .getAttribute(StratumBreakpointAdapterFactory.ORG_ECLIPSE_XTEXT_XBASE_SOURCE_URI));
        Pair<IStorage, IProject> storage = Iterables.getFirst(storage2UriMapper.getStorages(uri), null);
        if (storage == null)
            return null;
        result = traceForStorageProvider.getTraceToTarget(storage.getFirst());
    } else {
        result = traceForTypeRootProvider.getTraceToSource(classFile);
    }
    return result;
}

From source file:nz.co.testamation.core.client.SeleniumBrowserDriver.java

public WebElement findElement(By by) {
    List<WebElement> elements = findElements(by);
    logger.debug("Find element " + by + " found " + elements.size());
    if (elements.isEmpty()) {
        return null;
    }/*from   w w w . java2  s.c  o m*/
    return Iterables.getFirst(elements, null);
}

From source file:org.onebusaway.nyc.vehicle_tracking.impl.inference.BlockStateSamplingStrategyImpl.java

@Override
public BlockStateObservation samplePriorScheduleState(BlockInstance blockInstance, Observation obs) {

    /*/* w w w  .  ja v  a  2  s  . c  o m*/
     * Our initial block proposals will yield 0 d.a.b. in some cases. It could
     * be that there is no snapped position for a block, yet it isn't actually
     * deadheading-before, it could be deadheading-during. That is why we sample
     * schedule deviations around the current obs time when the obs time is
     * after the block's start.
     */
    final double currentTime = (obs.getTime() - blockInstance.getServiceDate()) / 1000;

    /*
     * Get the location at for the current time, then sample a location
     * based on that time and the travel time to that location (for when
     * we're not anywhere nearby).
     */
    final int startSchedTime = Iterables.getFirst(blockInstance.getBlock().getStopTimes(), null).getStopTime()
            .getArrivalTime();
    final int endSchedTime = Iterables.getLast(blockInstance.getBlock().getStopTimes(), null).getStopTime()
            .getDepartureTime();

    final double timeToGetToCurrentTimeLoc;
    if (currentTime > startSchedTime && currentTime < endSchedTime && obs.getPreviousObservation() != null) {
        final ScheduledBlockLocation blockLocation = _scheduledBlockLocationService
                .getScheduledBlockLocationFromScheduledTime(blockInstance.getBlock(), (int) currentTime);

        /*
         * If the current time puts us in deadhead-during between trips, then
         * it's possible that the block location will be at the start
         * of the previous trip (potentially very far away), so we skip
         * these situations.
         */
        if (JourneyStateTransitionModel.isLocationOnATrip(blockLocation)) {
            final double impliedVelocity = obs.getDistanceMoved() / obs.getTimeDelta();
            timeToGetToCurrentTimeLoc = TurboButton.distance(blockLocation.getLocation(), obs.getLocation())
                    / impliedVelocity;
        } else {
            timeToGetToCurrentTimeLoc = 0d;
        }
    } else {
        timeToGetToCurrentTimeLoc = 0d;
    }

    /*
     * TODO Note that we're using the non-run-matching prior distribution.
     * Should we?
     */
    final StudentTDistribution schedDist = ScheduleLikelihood.getSchedDevNonRunDist();
    final double schedTimeError = 60d * schedDist.sample(ParticleFactoryImpl.getLocalRng());
    double newSchedTime = currentTime + timeToGetToCurrentTimeLoc
            + Math.max(schedTimeError, -timeToGetToCurrentTimeLoc / 3d);

    if (Double.isInfinite(newSchedTime))
        return null;

    BlockStateObservation schedState;
    if (newSchedTime < startSchedTime) {
        schedState = _blocksFromObservationService.getBlockStateObservationFromDist(obs, blockInstance, 0.0);
    } else if (endSchedTime < newSchedTime) {
        return null;
    } else {
        /**
         * Important note about prior distribution sampling: to reduce/remove
         * confusion caused by deadhead states having no pre-defined trajectory,
         * we simply don't allow prior sampling of deadhead states for certain
         * situations.
         */
        schedState = _blocksFromObservationService.getBlockStateObservationFromTime(obs, blockInstance,
                (int) newSchedTime);
        if (!schedState.isOnTrip()) {
            return null;
        }
    }

    return orientationCheck(null, schedState, obs);
}

From source file:org.jclouds.abiquo.domain.infrastructure.ManagedRack.java

/**
 * Retrieve the first blade matching the filter within the list of machines
 * in this rack.//from  w  w w.  j av  a 2  s  .c  om
 * 
 * @param filter
 *           Filter to be applied to the list.
 * @see API: <a href=
 *      "http://community.abiquo.com/display/ABI20/MachineResource#MachineResource-RetrievealistofMachines"
 *      > http://community.abiquo.com/display/ABI20/MachineResource#
 *      MachineResource- RetrievealistofMachines</a>
 */
public Blade findMachine(final Predicate<Blade> filter) {
    return Iterables.getFirst(filter(listMachines(), filter), null);
}

From source file:eu.trentorise.opendata.semtext.SemTexts.java

/**
 *
 * Checks spans are all be valid spans (see {@link SemTexts#checkSpan(int, int, Object)
 * }/*from   w  w w. j av  a  2  s  . c o  m*/
 * and are non-overlapping (a span end offset may coincide with next span
 * start offset). Spans must be contained within {@code leftOffset} and
 * {@code rightOffset} (last span end offset may coincide with
 * {@code rightOffset}).
 *
 * @param prependedErrorMessage the exception message to use if the check
 * fails; will be converted to a string using String.valueOf(Object) and
 * prepended to more specific error messages.
 *
 * @throws IllegalArgumentException on invalid spans
 */
public static void checkSpans(Iterable<? extends Span> spans, int leftOffset, int rightOffset,
        @Nullable Object prependedErrorMessage) {

    checkArgument(spans != null, "%s -- spans are null!", prependedErrorMessage);
    checkSpan(leftOffset, rightOffset, prependedErrorMessage);

    // check containment        
    if (!Iterables.isEmpty(spans)) {
        int lowerBound = Iterables.getFirst(spans, null).getStart();
        int upperBound = Iterables.getLast(spans).getEnd();
        if (lowerBound < leftOffset || upperBound > rightOffset) {
            throw new IllegalArgumentException(String.valueOf(prependedErrorMessage)
                    + " -- Reason: Provided spans exceed container span! Expected: [" + leftOffset + ","
                    + rightOffset + "] - Found: [" + lowerBound + "," + upperBound + "]");
        }
    }

    // check overlaps
    @Nullable
    Span lastSpan = null;
    for (Span span : spans) {
        checkSpan(span.getStart(), span.getEnd(), prependedErrorMessage);
        if (lastSpan != null && lastSpan.getEnd() > span.getStart()) {
            throw new IllegalArgumentException(String.valueOf(prependedErrorMessage)
                    + " -- Found overlapping span! Span " + lastSpan + " overlaps with span " + span);
        }
        lastSpan = span;
    }

}

From source file:com.blackducksoftware.bdio.model.ExternalIdentifier.java

@Nullable
public String getSuiteReleaseTag() {
    return Iterables.getFirst(Iterables.skip(getBdSuiteId(), 1), null);

}

From source file:com.eucalyptus.walrus.pipeline.WalrusRESTPipeline.java

/**
 * Is walrus domainname a subdomain of the host header host. If so, then it is likely a bucket prefix.
 * But, since S3 buckets can include '.' can't just parse on '.'s
 * @param fullHostHeader/*from  w  w  w  .  ja  v  a2s.  c om*/
 * @return
 */
private boolean maybeBucketHostedStyle(String fullHostHeader) {
    try {
        return DomainNames
                .absolute(
                        Name.fromString(Iterables.getFirst(hostSplitter.split(fullHostHeader), fullHostHeader)))
                .subdomain(DomainNames.externalSubdomain(WalrusBackend.class));
    } catch (Exception e) {
        LOG.error("Error parsing domain name from hostname: " + fullHostHeader, e);
        return false;
    }
}

From source file:com.android.tools.idea.editors.strings.StringResourceData.java

@VisibleForTesting
@NotNull/*from  ww  w .java  2  s. co m*/
static String summarizeLocales(@NotNull Collection<Locale> locales) {
    if (locales.isEmpty()) {
        return "";
    }

    final int size = locales.size();

    if (size == 1) {
        return getLabel(Iterables.getFirst(locales, null));
    }

    final int max = 3;
    List<Locale> sorted = getLowest(locales, max);
    if (size <= max) {
        return getLabels(sorted.subList(0, size - 1)) + " and " + getLabel(sorted.get(size - 1));
    } else {
        return String.format("%1$s and %2$d more", getLabels(sorted), size - max);
    }
}

From source file:com.google.gerrit.server.change.Submit.java

private void approve(PatchSet rev, IdentifiedUser caller, Timestamp timestamp) throws OrmException {
    PatchSetApproval submit = Iterables.getFirst(Iterables.filter(
            dbProvider.get().patchSetApprovals().byPatchSetUser(rev.getId(), caller.getAccountId()),
            new Predicate<PatchSetApproval>() {
                @Override/*  ww w.  j  a  v a 2  s .c om*/
                public boolean apply(PatchSetApproval input) {
                    return input.isSubmit();
                }
            }), null);
    if (submit == null) {
        submit = new PatchSetApproval(
                new PatchSetApproval.Key(rev.getId(), caller.getAccountId(), LabelId.SUBMIT), (short) 1);
    }
    submit.setValue((short) 1);
    submit.setGranted(timestamp);
    dbProvider.get().patchSetApprovals().upsert(Collections.singleton(submit));
}

From source file:org.opendaylight.netconf.sal.rest.impl.RestconfDocumentedExceptionMapper.java

private static MapEntryNode toErrorEntryNode(final RestconfError error,
        final DataSchemaNode errListSchemaNode) {
    Preconditions.checkArgument(errListSchemaNode instanceof ListSchemaNode,
            "errListSchemaNode has to be of type ListSchemaNode");
    final ListSchemaNode listStreamSchemaNode = (ListSchemaNode) errListSchemaNode;
    final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> errNodeValues = Builders
            .mapEntryBuilder(listStreamSchemaNode);

    List<DataSchemaNode> lsChildDataSchemaNode = ControllerContext
            .findInstanceDataChildrenByName((listStreamSchemaNode), "error-type");
    final DataSchemaNode errTypSchemaNode = Iterables.getFirst(lsChildDataSchemaNode, null);
    Preconditions.checkState(errTypSchemaNode instanceof LeafSchemaNode);
    errNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) errTypSchemaNode)
            .withValue(error.getErrorType().getErrorTypeTag()).build());

    lsChildDataSchemaNode = ControllerContext.findInstanceDataChildrenByName((listStreamSchemaNode),
            "error-tag");
    final DataSchemaNode errTagSchemaNode = Iterables.getFirst(lsChildDataSchemaNode, null);
    Preconditions.checkState(errTagSchemaNode instanceof LeafSchemaNode);
    errNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) errTagSchemaNode)
            .withValue(error.getErrorTag().getTagValue()).build());

    if (error.getErrorAppTag() != null) {
        lsChildDataSchemaNode = ControllerContext.findInstanceDataChildrenByName((listStreamSchemaNode),
                "error-app-tag");
        final DataSchemaNode errAppTagSchemaNode = Iterables.getFirst(lsChildDataSchemaNode, null);
        Preconditions.checkState(errAppTagSchemaNode instanceof LeafSchemaNode);
        errNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) errAppTagSchemaNode)
                .withValue(error.getErrorAppTag()).build());
    }/* w  w w .  ja  v a 2  s  .com*/

    lsChildDataSchemaNode = ControllerContext.findInstanceDataChildrenByName((listStreamSchemaNode),
            "error-message");
    final DataSchemaNode errMsgSchemaNode = Iterables.getFirst(lsChildDataSchemaNode, null);
    Preconditions.checkState(errMsgSchemaNode instanceof LeafSchemaNode);
    errNodeValues.withChild(
            Builders.leafBuilder((LeafSchemaNode) errMsgSchemaNode).withValue(error.getErrorMessage()).build());

    if (error.getErrorInfo() != null) {
        // Oddly, error-info is defined as an empty container in the restconf yang. Apparently the
        // intention is for implementors to define their own data content so we'll just treat it as a leaf
        // with string data.
        errNodeValues.withChild(
                ImmutableNodes.leafNode(Draft02.RestConfModule.ERROR_INFO_QNAME, error.getErrorInfo()));
    }

    // TODO : find how could we add possible "error-path"

    return errNodeValues.build();
}