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.apache.provisionr.amazon.core.ImageTable.java

static Iterable<String> extractHeaders(List<String> lines) {
    String headerLine = Iterables.getFirst(lines, "");
    checkArgument(!headerLine.isEmpty(), "Found an empty header line");

    return COMMA.split(headerLine);
}

From source file:com.google.devtools.build.lib.util.GroupedList.java

/**
 * Appends the list constructed in {@code helper} to this list. Returns the elements of {@code
 * helper}, uniquified./*from   w  w w  . java2  s.  co  m*/
 */
@SuppressWarnings("unchecked") // Cast to T and List<T>.
public Set<T> append(GroupedListHelper<T> helper) {
    Preconditions.checkState(helper.currentGroup == null, "%s %s", this, helper);
    // Do a check to make sure we don't have lists here. Note that if helper.elements is empty,
    // Iterables.getFirst will return null, and null is not instanceof List.
    Preconditions.checkState(!(Iterables.getFirst(helper.elements, null) instanceof List),
            "Cannot make grouped list of lists: %s", helper);
    Set<T> uniquifier = CompactHashSet.createWithExpectedSize(helper.elements.size());
    for (Object item : helper.groupedList) {
        if (item instanceof List) {
            // Optimize for the case that elements in this list are unique.
            ImmutableList.Builder<T> dedupedList = null;
            List<T> list = (List<T>) item;
            Preconditions.checkState(list.size() > 1, "Helper should have compressed small list %s properly",
                    list);
            for (int i = 0; i < list.size(); i++) {
                T elt = list.get(i);
                if (!uniquifier.add(elt)) {
                    if (dedupedList == null) {
                        dedupedList = ImmutableList.builder();
                        dedupedList.addAll(list.subList(0, i));
                    }
                } else if (dedupedList != null) {
                    dedupedList.add(elt);
                }
            }
            if (dedupedList == null) {
                elements.add(list);
            } else {
                List<T> filteredList = dedupedList.build();
                addItem(filteredList, elements);
            }
        } else if (uniquifier.add((T) item)) {
            elements.add(item);
        }
    }
    size += uniquifier.size();
    return uniquifier;
}

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

/**
 * {@inheritDoc}/*from   w w w  .j  a va2s  .  co  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;
            boolean hasAlert = false;
            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)) {
                    hasAlert = true;
                    maxStatus = serializeCondition(maxStatus, dataBuilder, datum, condition);
                }
            }

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

            stringBuilder.append("run_every=").append(period.toStandardSeconds().getSeconds())
                    .append("&has_alert=").append(hasAlert).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:com.github.blacklocus.rdsecho.utl.RdsFind.java

public Optional<Tag> instanceTag(String instanceArn, Predicate<Tag> predicate) {
    return Optional.fromNullable(Iterables.getFirst(instanceTags(instanceArn, predicate), null));
}

From source file:org.obm.provisioning.processing.impl.AbstractOperationProcessor.java

protected LdapManager buildLdapManager(ObmDomain domain) {
    LdapConnectionConfig connectionConfig = new LdapConnectionConfig();
    ObmHost ldapHost = Iterables.getFirst(domain.getHosts().get(ServiceProperty.LDAP), null);

    if (ldapHost == null) {
        throw new ProcessingException(
                String.format("Domain %s has no linked %s host.", domain.getName(), ServiceProperty.LDAP));
    }/*from w  ww.  j ava2  s .c  om*/

    connectionConfig.setLdapHost(ldapHost.getIp());
    connectionConfig.setLdapPort(LdapConnectionConfig.DEFAULT_LDAP_PORT);

    return ldapService.buildManager(connectionConfig);
}

From source file:com.jcwhatever.phantom.nms.v1_8_R3.Lights_v1_8_R3.java

public void setLightSource(Location location, int intensity, boolean updateChunks) {

    WorldServer world = ((CraftWorld) location.getWorld()).getHandle();

    BlockPosition position = new BlockPosition(location.getBlockX(), location.getBlockY(),
            location.getBlockZ());/* w  w w. j a  va2s .  c  om*/

    if (intensity > 0) {
        // set light source
        world.a(EnumSkyBlock.BLOCK, position, intensity);

        Block block = location.getBlock();
        Block trans = BlockUtils.getFirstAdjacent(block, MaterialProperty.TRANSPARENT);
        if (trans == null)
            trans = block;

        position = new BlockPosition(trans.getX(), trans.getY(), trans.getZ());
    }

    // recalculate lighting
    world.c(EnumSkyBlock.BLOCK, position);

    if (updateChunks) {
        Collection<IChunkCoords> localChunks = ChunkUtils.getChunksInRadius(location, 8);
        if (localChunks.size() == 1) {
            updateChunk(location.getWorld(), Iterables.getFirst(localChunks, null));
        } else {
            updateChunks(location.getWorld(), localChunks);
        }
    }
}

From source file:semRewrite.substitutor.LocationSubstitutor.java

/** **************************************************************
 *//*www  . ja  v  a2 s  . c om*/
private semRewrite.substitutor.CoreLabelSequence closestLocation(List<CoreLabel> labels, int therePosition) {

    ListIterator<CoreLabel> rit = labels.listIterator(therePosition);
    LinkedList<CoreLabel> location = Lists.newLinkedList();
    while (rit.hasPrevious()) {
        CoreLabel label = rit.previous();
        if ("LOCATION".equals(label.ner()) || "ORGANIZATION".equals(label.ner())) {
            if (Iterables.getFirst(location, label).ner().equals(label.ner())) {
                location.addFirst(label);
            }
        } else if (!location.isEmpty()) {
            if ("IN".equals(label.tag())) {
                location.addFirst(label);
            }
            break;
        }
    }

    return CoreLabelSequence.from(location.toArray(new CoreLabel[0]));
}

From source file:com.netflix.ndbench.core.config.CompositeConfigSource.java

@Override
public void set(final String key, final String value) {
    Preconditions.checkNotNull(value, "Value can not be null for configurations.");
    final IConfigSource firstSource = Iterables.getFirst(sources, null);
    // firstSource shouldn't be null because the collection is immutable, and the collection is non empty.
    Preconditions.checkState(firstSource != null, "There was no IConfigSource found at the first location?");
    firstSource.set(key, value);/*w w  w  .  j ava2 s .c om*/
}

From source file:com.facebook.presto.block.BlockIterables.java

public static Optional<Integer> getPositionCount(Iterable<? extends BlockIterable> blockIterables) {
    for (BlockIterable blocks : blockIterables) {
        if (!blocks.getDataSize().isPresent()) {
            return Optional.absent();
        }/*from  www  .j  a  v a 2s . com*/
    }

    return Iterables.getFirst(blockIterables, null).getPositionCount();
}

From source file:com.google.template.soy.passes.CheckCallsVisitor.java

@Override
protected void visitCallNode(CallNode node) {

    // Recurse.//  w  w w  .j ava 2  s  .c  o  m
    visitChildren(node);

    // If all the data keys being passed are listed using 'param' commands, then check that all
    // required params of the callee are included.
    if (!node.dataAttribute().isPassingData()) {

        // Get the callee node (basic or delegate).
        TemplateNode callee = null;
        if (node instanceof CallBasicNode) {
            callee = templateRegistry.getBasicTemplate(((CallBasicNode) node).getCalleeName());
        } else {
            String delTemplateName = ((CallDelegateNode) node).getDelCalleeName();
            ImmutableSet<DelegateTemplateDivision> divisions = templateRegistry
                    .getDelTemplateDivisionsForAllVariants(delTemplateName);
            if (!divisions.isEmpty()) {
                callee = Iterables
                        .get(Iterables.getFirst(divisions, null).delPackageNameToDelTemplateMap.values(), 0);
            }
        }

        // Do the check if the callee node has declared params.
        if (callee != null && callee.getParams() != null) {
            // Get param keys passed by caller.
            Set<String> callerParamKeys = Sets.newHashSet();
            for (CallParamNode callerParam : node.getChildren()) {
                callerParamKeys.add(callerParam.getKey());
            }
            // Check param keys required by callee.
            List<String> missingParamKeys = Lists.newArrayListWithCapacity(2);
            for (TemplateParam calleeParam : callee.getParams()) {
                if (calleeParam.isRequired() && !callerParamKeys.contains(calleeParam.name())) {
                    missingParamKeys.add(calleeParam.name());
                }
            }
            // Report errors.
            if (!missingParamKeys.isEmpty()) {
                String errorMsgEnd = (missingParamKeys.size() == 1) ? "param '" + missingParamKeys.get(0) + "'"
                        : "params " + missingParamKeys;
                errorReporter.report(node.getSourceLocation(), MISSING_PARAM, errorMsgEnd);
            }
        }
    }
}