Example usage for com.google.common.collect Iterators getLast

List of usage examples for com.google.common.collect Iterators getLast

Introduction

In this page you can find the example usage for com.google.common.collect Iterators getLast.

Prototype

public static <T> T getLast(Iterator<T> iterator) 

Source Link

Document

Advances iterator to the end, returning the last element.

Usage

From source file:org.gradle.api.internal.artifacts.ivyservice.resolveengine.graph.builder.MessageBuilderHelper.java

static Collection<String> pathTo(EdgeState edge, boolean includeLast) {
    List<List<EdgeState>> acc = Lists.newArrayListWithExpectedSize(1);
    pathTo(edge, Lists.<EdgeState>newArrayList(), acc, Sets.<NodeState>newHashSet());
    List<String> result = Lists.newArrayListWithCapacity(acc.size());
    for (List<EdgeState> path : acc) {
        EdgeState target = Iterators.getLast(path.iterator());
        StringBuilder sb = new StringBuilder();
        if (target.getSelector().getDependencyMetadata().isConstraint()) {
            sb.append("Constraint path ");
        } else {/*from ww  w .  j  a va2s. co m*/
            sb.append("Dependency path ");
        }
        boolean first = true;
        for (EdgeState e : path) {
            if (!first) {
                sb.append(" --> ");
            }
            first = false;
            ModuleVersionIdentifier id = e.getFrom().getResolvedConfigurationId().getId();
            sb.append('\'').append(id).append('\'');
        }
        if (includeLast) {
            sb.append(" --> ");
            ModuleIdentifier moduleId = edge.getSelector().getTargetModule().getId();
            sb.append('\'').append(moduleId.getGroup()).append(':').append(moduleId.getName()).append('\'');
        }
        result.add(sb.toString());
    }
    return result;
}

From source file:me.j360.dubbo.modules.util.collection.CollectionUtil.java

/**
 * ?Collection?collectionnull.//from  ww w . jav a  2  s.  c  o m
 */
public static <T> T getLast(Collection<T> collection) {
    if (isEmpty(collection)) {
        return null;
    }

    // List??.
    if (collection instanceof List) {
        List<T> list = (List<T>) collection;
        return list.get(list.size() - 1);
    }

    return Iterators.getLast(collection.iterator());
}

From source file:com.adobe.acs.commons.wcm.comparisons.impl.VersionServiceImpl.java

@Override
public Version lastVersion(Resource resource) {
    try {/*from  www .  j  a v a 2s  .  c om*/
        Resource versionableResource = resource.isResourceType(NameConstants.NT_PAGE)
                ? resource.getChild(NameConstants.NN_CONTENT)
                : resource;
        VersionManager versionManager = versionableResource.getResourceResolver().adaptTo(Session.class)
                .getWorkspace().getVersionManager();
        final Iterator<Version> allVersions = versionManager.getVersionHistory(versionableResource.getPath())
                .getAllVersions();
        return Iterators.getLast(allVersions);
    } catch (RepositoryException e) {
        log.error("Error receiving last version of resource [ {} ]", resource.getName());
    }
    return null;
}

From source file:com.flowlogix.security.PassThruAuthenticationFilter.java

@Override
protected void redirectToLogin(ServletRequest request, ServletResponse response) throws IOException {
    boolean isGetRequest = HttpMethod.GET.equalsIgnoreCase(WebUtils.toHttp(request).getMethod());
    String sessionExpired = Iterators
            .getLast(Splitter.on('.').split(AttributeKeys.SESSION_EXPIRED_KEY).iterator());
    Servlets.facesRedirect(WebUtils.toHttp(request), WebUtils.toHttp(response),
            Servlets.getRequestBaseURL(WebUtils.toHttp(request)) + getLoginUrl().replaceFirst("^/", "")
                    + (isGetRequest ? "" : "?%s=true"),
            sessionExpired);/*from   w  ww .  j a va 2  s  . com*/
}

From source file:com.github.jeluard.stone.spi.Storage.java

/**
 * Default implementation relying on {@link #all()}: it iterates over {@link #all()} elements to access the last one.
 *
 * @return //from w ww.  java 2  s  .c o  m
 * @see Iterables#getLast(java.lang.Iterable)
 */
@Override
public Optional<Long> end() throws IOException {
    try {
        final Iterator<Pair<Long, int[]>> consolidates = all().iterator();
        return Optional.of(Iterators.getLast(consolidates).first);
    } catch (NoSuchElementException e) {
        return Optional.absent();
    }
}

From source file:com.devcexx.libtrails.examples.skin.SkinDownloader.java

public String getSkinUrl(GameProfile prof) throws ParseException {
    Collection<Property> ps = prof.getProperties().get("textures");

    if (ps == null || ps.isEmpty()) {
        return null;
    } else {/*from  ww  w.  ja  v a 2s.  c  o m*/
        Property p = Iterators.getLast(ps.iterator());

        JSONObject obj = (JSONObject) new JSONParser()
                .parse(new String(Base64.getDecoder().decode(p.getValue())));

        obj = ((JSONObject) obj.get("textures"));
        obj = ((JSONObject) obj.get("SKIN"));
        return (String) obj.get("url");
    }
}

From source file:org.sonar.server.issue.index.IssueResultSetIterator.java

private static String extractModule(String moduleUuidPath) {
    return Iterators.getLast(MODULE_PATH_SPLITTER.split(moduleUuidPath).iterator());
}

From source file:com.ansorgit.plugins.bash.lang.psi.util.BashAbstractProcessor.java

/**
 * Returns the best results. It takes all the elements which have been rated the best
 * and returns the first / last, depending on the parameter.
 *
 * @param results          The results to check
 * @param firstResult      If the first element of the best element list should be returned.
 * @param referenceElement//from   w  w w.ja  v  a 2s  .com
 * @return The result
 */
private PsiElement findBestResult(Multimap<Integer, PsiElement> results, boolean firstResult,
        PsiElement referenceElement) {
    if (!hasResults()) {
        return null;
    }

    if (firstResult) {
        return Iterators.get(results.values().iterator(), 0);
    }

    //if the first should not be used return the best element
    int referenceLevel = preferNeigbourhood && (referenceElement != null)
            ? BashPsiUtils.blockNestingLevel(referenceElement)
            : 0;

    // find the best suitable result rating
    // The best one is as close as possible to the given referenceElement
    int bestRating = Integer.MAX_VALUE;
    int bestDelta = Integer.MAX_VALUE;
    for (int rating : results.keySet()) {
        final int delta = Math.abs(referenceLevel - rating);
        if (delta < bestDelta) {
            bestDelta = delta;
            bestRating = rating;
        }
    }

    // now get the best result
    // if there are equal definitions on the same level we prefer the first if the neighbourhood is not preferred
    if (preferNeigbourhood) {
        return Iterators.getLast(results.get(bestRating).iterator());
    } else {
        //return the element which has the lowest textOffset
        long smallestOffset = Integer.MAX_VALUE;
        PsiElement bestElement = null;

        for (PsiElement e : results.get(bestRating)) {
            //if the element is injected compute the text offset in the real file
            int textOffset = e.getTextOffset();
            if (BashPsiUtils.isInjectedElement(e)) {
                //fixme optimize this
                PsiLanguageInjectionHost injectionHost = InjectedLanguageManager.getInstance(e.getProject())
                        .getInjectionHost(e);
                if (injectionHost != null) {
                    textOffset = textOffset + injectionHost.getTextOffset();
                }
            }

            if (textOffset < smallestOffset) {
                smallestOffset = textOffset;
                bestElement = e;
            }
        }

        return bestElement;
    }
}

From source file:com.lyndir.lhunath.snaplog.data.object.media.TimeFrame.java

@Override
public String getLocalizedInstance() {

    String s = getFormatter().print(offset);
    logger.dbg("frame: %s, starts with: %s, ends with: %s - desc: %s", this, media.iterator().next(),
            Iterators.getLast(media.iterator()), s);
    return s;// w  ww  .jav  a 2s  . c om
}

From source file:io.mandrel.blob.impl.MongoBlobStore.java

@Override
public Blob getBlob(Uri uri) {
    String id = Iterators.getLast(Splitter.on('/').split(uri.getPath()).iterator());
    GridFSDownloadStream stream = bucket.openDownloadStream(new ObjectId(id));
    return fromFile.apply(stream);
}