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.github.radium226.github.maven.GitHubService.java

public Pair<GHRepository, GHTag> findRepositoryAndTag(String groupID, String artifactID, String version)
        throws TransferFailedException {
    try {//w  w  w .j  a  v a2s. c om
        GHRepository repository = findRepository(groupID, artifactID);
        GHTag tag = Iterables.getFirst(Iterables.filter(repository.listTags(), new Predicate<GHTag>() {

            @Override
            public boolean apply(GHTag tag) {
                return tag.getName().equals(version);
            }

        }), null);

        return Pair.of(repository, tag);
    } catch (IOException e) {
        throw new TransferFailedException("Something happened with GitHub", e);
    }
}

From source file:com.google.gerrit.httpd.restapi.ParameterParser.java

private static Set<String> query(HttpServletRequest req) {
    Set<String> params = Sets.newHashSet();
    if (!Strings.isNullOrEmpty(req.getQueryString())) {
        for (String kvPair : Splitter.on('&').split(req.getQueryString())) {
            params.add(Iterables.getFirst(Splitter.on('=').limit(2).split(kvPair), null));
        }//from w  w w.j ava2  s.c om
    }
    return params;
}

From source file:com.arpnetworking.tsdcore.sinks.MonitordSink.java

/**
 * {@inheritDoc}/*www  .  jav a 2 s  . c o  m*/
 */
@Override
protected Collection<byte[]> serialize(final PeriodicData periodicData) {
    final Period period = periodicData.getPeriod();
    final Multimap<String, AggregatedData> indexedData = prepareData(periodicData);
    final Multimap<String, Condition> indexedConditions = prepareConditions(periodicData.getConditions());

    // Serialize
    final List<byte[]> serializedData = Lists.newArrayListWithCapacity(indexedData.size());
    final StringBuilder stringBuilder = new StringBuilder();
    for (final String key : indexedData.keySet()) {
        final Collection<AggregatedData> namedData = indexedData.get(key);
        if (!namedData.isEmpty()) {
            stringBuilder.setLength(0);
            final AggregatedData first = Iterables.getFirst(namedData, null);
            final String name = new StringBuilder().append(first.getFQDSN().getService()).append("_")
                    .append(period.toString(ISOPeriodFormat.standard())).append("_")
                    .append(first.getFQDSN().getMetric()).toString();

            int maxStatus = 0;
            final StringBuilder dataBuilder = new StringBuilder();
            for (final AggregatedData datum : namedData) {
                if (!datum.isSpecified()) {
                    continue;
                }

                dataBuilder.append(datum.getFQDSN().getStatistic().getName()).append("%3D")
                        .append(datum.getValue().getValue()).append("%3B");

                final String conditionKey = datum.getFQDSN().getService() + "_" + datum.getFQDSN().getMetric()
                        + "_" + datum.getFQDSN().getCluster() + "_" + datum.getFQDSN().getStatistic();
                for (final Condition condition : indexedConditions.get(conditionKey)) {
                    dataBuilder.append(datum.getFQDSN().getStatistic().getName()).append("_")
                            .append(condition.getName()).append("%3D")
                            .append(condition.getThreshold().getValue()).append("%3B");

                    if (condition.isTriggered().isPresent() && condition.isTriggered().get()) {
                        // Collect the status of this metric
                        final Object severity = condition.getExtensions().get("severity");
                        int status = _unknownSeverityStatus;
                        if (severity != null && _severityToStatus.containsKey(severity)) {
                            status = _severityToStatus.get(severity);
                        }
                        maxStatus = Math.max(status, maxStatus);
                    }
                }
            }

            // Don't send an empty payload
            if (dataBuilder.length() == 0) {
                continue;
            }

            stringBuilder.append("run_every=").append(period.toStandardSeconds().getSeconds()).append("&path=")
                    .append(first.getFQDSN().getCluster()).append("%2f")
                    .append(periodicData.getDimensions().get("host")).append("&monitor=").append(name)
                    .append("&status=").append(maxStatus).append("&timestamp=")
                    .append((int) Unit.SECOND.convert(periodicData.getStart().getMillis(), Unit.MILLISECOND))
                    .append("&output=").append(name).append("%7C").append(dataBuilder.toString());

            stringBuilder.setLength(stringBuilder.length() - 3);
            serializedData.add(stringBuilder.toString().getBytes(Charset.forName("UTF-8")));
        }
    }

    return serializedData;
}

From source file:org.sonar.batch.scan.filesystem.ProjectFileSystemAdapter.java

@Override
public File getBuildOutputDir() {
    File dir = Iterables.getFirst(target.binaryDirs(), null);
    if (dir == null) {
        // emulate binary dir
        dir = new File(getBuildDir(), "classes");
    }/* w w w .  jav  a 2  s .  c  om*/

    return dir;
}

From source file:org.obm.provisioning.utils.SerializationUtils.java

public static ObmHost getMailHostValue(JsonNode jsonNode, ObmDomain domain) {
    ObmHost mailHost = null;// w  ww  . j  av a2  s.  c o m

    JsonNode serverNode = jsonNode.findValue(MAIL_SERVER.asSpecificationValue());
    JsonNode emailsNode = jsonNode.findValue(MAILS.asSpecificationValue());

    final Collection<String> mails = !isNullOrNullNode(emailsNode) ? getCurrentTokenTextValues(emailsNode)
            : null;
    final Collection<ObmHost> imapServices = domain.getHosts().get(IMAP_SERVICE_PROPERTY);

    if (!isNullOrNullNode(serverNode)) {
        mailHost = findMailHostForUser(serverNode.asText(), imapServices);
    } else if (mails != null && !mails.isEmpty()) {
        mailHost = Iterables.getFirst(imapServices, null);
    }

    return mailHost;
}

From source file:org.sonar.batch.scan.filesystem.DeprecatedFileSystemAdapter.java

public File getBuildOutputDir() {
    File dir = Iterables.getFirst(target.binaryDirs(), null);
    if (dir == null) {
        // emulate binary dir
        dir = new File(getBuildDir(), "classes");
    }/*from ww w .  ja v  a 2 s.c o  m*/

    return dir;
}

From source file:com.b2international.commons.options.HashMapOptions.java

@Override
@SuppressWarnings("unchecked")
public final <T> Collection<T> getCollection(String key, Class<T> type) {
    final Object value = get(key);
    if (type.isInstance(value)) {
        return Collections.singleton(type.cast(value));
    } else {/*from   ww  w  .ja  v a 2  s  .  c o  m*/
        final Collection<Object> collection = get(key, Collection.class);
        final Object first = collection != null ? Iterables.getFirst(collection, null) : null;
        if (first != null) {
            if (type.isInstance(first)) {
                return (Collection<T>) collection;
            }
            throw new IllegalArgumentException(String.format(
                    "The elements (%s) in the collection are not the instance of the given type (%s)",
                    first.getClass(), type));
        }
        return emptySet();
    }
}

From source file:com.eviware.loadui.util.groovy.ParsedGroovyScript.java

/**
 * Returns the value of the given header (or the provided default value if
 * the header does not exist). If the header has multiple values, the first
 * of these will be returned./*from w ww. j ava2s  .  c  o m*/
 * 
 * @param key
 * @param defaultValue
 * @return
 */
@Nullable
public String getHeader(@Nonnull String key, @Nullable String defaultValue) {
    return Iterables.getFirst(headers.get(key), defaultValue);
}

From source file:com.github.nethad.clustermeister.provisioning.ec2.AmazonNode.java

public String getFirstPrivateAddress() {
    return Iterables.getFirst(instanceMetadata.getPrivateAddresses(), null);
}

From source file:org.obm.satellite.client.ConnectionImpl.java

@Override
public void updateMTA() throws SatteliteClientException, ConnectionException {
    ObmHost mtaHost = Iterables.getFirst(domain.getHosts().get(ServiceProperty.SMTP_IN), null);

    if (mtaHost == null) {
        throw new SatteliteClientException(
                String.format("Domain %s doesn't have a linked mail/smtp_in host", domain.getName()));
    }//from  w ww .  j a  va 2s  .c o  m

    post(mtaHost.getName(), mtaHost.getIp(), SATELLITE_MTA_PATH);
}