Example usage for com.google.common.collect Iterables size

List of usage examples for com.google.common.collect Iterables size

Introduction

In this page you can find the example usage for com.google.common.collect Iterables size.

Prototype

public static int size(Iterable<?> iterable) 

Source Link

Document

Returns the number of elements in iterable .

Usage

From source file:org.gradle.api.internal.plugins.StartScriptTemplateBindingFactory.java

private String createJoinedDefaultJvmOpts(Iterable<String> defaultJvmOpts) {
    if (windows) {
        if (defaultJvmOpts == null) {
            return "";
        }/*from   w  ww .jav a  2s.c  o  m*/

        Iterable<String> quotedDefaultJvmOpts = Iterables
                .transform(CollectionUtils.toStringList(defaultJvmOpts), new Function<String, String>() {
                    public String apply(String jvmOpt) {
                        return "\"" + escapeWindowsJvmOpt(jvmOpt) + "\"";
                    }
                });

        Joiner spaceJoiner = Joiner.on(" ");
        return spaceJoiner.join(quotedDefaultJvmOpts);
    } else {
        if (defaultJvmOpts == null) {
            return "";
        }

        Iterable<String> quotedDefaultJvmOpts = Iterables
                .transform(CollectionUtils.toStringList(defaultJvmOpts), new Function<String, String>() {
                    public String apply(String jvmOpt) {
                        //quote ', ", \, $. Probably not perfect. TODO: identify non-working cases, fail-fast on them
                        jvmOpt = jvmOpt.replace("\\", "\\\\");
                        jvmOpt = jvmOpt.replace("\"", "\\\"");
                        jvmOpt = jvmOpt.replace("'", "'\"'\"'");
                        jvmOpt = jvmOpt.replace("`", "'\"`\"'");
                        jvmOpt = jvmOpt.replace("$", "\\$");
                        return "\"" + jvmOpt + "\"";
                    }
                });

        //put the whole arguments string in single quotes, unless defaultJvmOpts was empty,
        // in which case we output "" to stay compatible with existing builds that scan the script for it
        Joiner spaceJoiner = Joiner.on(" ");
        if (Iterables.size(quotedDefaultJvmOpts) > 0) {
            return "'" + spaceJoiner.join(quotedDefaultJvmOpts) + "'";
        }

        return "\"\"";
    }
}

From source file:org.onos.yangtools.yang.data.impl.schema.transform.base.parser.BaseDispatcherParser.java

/**
 * can return null only if you override ParsingStrategy and explicitely return null
 * @param elements/*from   w w w .  ja  v  a2  s.  c o m*/
 * @param schema
 * @return
 */
@Nullable
@Override
public N parse(final Iterable<E> elements, final S schema) {

    checkAtLeastOneNode(schema, elements);

    DataContainerNodeBuilder<P, N> containerBuilder = getBuilder(schema);

    // Map child nodes to QName
    LinkedListMultimap<QName, E> mappedChildElements = mapChildElements(elements);

    // Map child nodes from Augments
    Map<QName, AugmentationSchema> mappedAugmentChildNodes = mapChildElementsFromAugments(schema);
    LinkedListMultimap<AugmentationSchema, E> augmentsToElements = LinkedListMultimap.create();

    // Map child nodes from choices
    Map<QName, ChoiceSchemaNode> mappedChoiceChildNodes = mapChildElementsFromChoices(schema);
    LinkedListMultimap<ChoiceSchemaNode, E> choicesToElements = LinkedListMultimap.create();

    Map<QName, String> attributes = getAttributes(elements.iterator().next());
    if (containerBuilder instanceof AttributesBuilder) {
        final int size = Iterables.size(elements);
        Preconditions.checkArgument(size == 1, "Unexpected number of elements: %s, should be 1 for: %s", size,
                schema);
        ((AttributesBuilder<?>) containerBuilder).withAttributes(attributes);
    }

    //parse keys first
    if (schema instanceof ListSchemaNode) {
        for (QName qname : ((ListSchemaNode) schema).getKeyDefinition()) {
            if (mappedChildElements.get(qname.withoutRevision()).isEmpty()) {
                continue;
            }

            DataSchemaNode childSchema = getSchemaForChild(schema, qname);
            List<E> childrenForQName = mappedChildElements.removeAll(qname.withoutRevision());

            DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> optionalChildNode = getDispatcher()
                    .dispatchChildElement(childSchema, childrenForQName);
            if (optionalChildNode != null) {
                containerBuilder.withChild(optionalChildNode);
            }
        }
    }

    //stage attribues for strategy before going deeper in the recursion
    buildingStrategy.prepareAttributes(attributes, containerBuilder);

    // process Child nodes
    for (QName childPartialQName : mappedChildElements.keySet()) {
        DataSchemaNode childSchema = getSchemaForChild(schema, childPartialQName);
        //with strict parsing an exception would be already thrown, with nonstrict we want to ignore this node
        if (childSchema == null) {
            continue;
        }
        List<E> childrenForQName = mappedChildElements.get(childPartialQName);

        // Augment
        if (isMarkedAs(mappedAugmentChildNodes, childSchema.getQName())) {
            AugmentationSchema augmentationSchema = mappedAugmentChildNodes.get(childSchema.getQName());
            augmentsToElements.putAll(augmentationSchema, childrenForQName);
            // Choices
        } else if (isMarkedAs(mappedChoiceChildNodes, childSchema.getQName())) {
            ChoiceSchemaNode choiceSchema = mappedChoiceChildNodes.get(childSchema.getQName());
            choicesToElements.putAll(choiceSchema, childrenForQName);
            // Regular child nodes
        } else {
            DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> optionalChildNode = getDispatcher()
                    .dispatchChildElement(childSchema, childrenForQName);
            if (optionalChildNode != null) {
                containerBuilder.withChild(optionalChildNode);
            }
        }
    }

    // TODO ordering is not preserved for choice and augment elements
    for (ChoiceSchemaNode choiceSchema : choicesToElements.keySet()) {
        DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> optionalChild = getDispatcher()
                .dispatchChildElement(choiceSchema, choicesToElements.get(choiceSchema));
        if (optionalChild != null) {
            containerBuilder.withChild(optionalChild);
        }
    }

    for (AugmentationSchema augmentSchema : augmentsToElements.keySet()) {
        Set<DataSchemaNode> realChildSchemas = getRealSchemasForAugment(schema, augmentSchema);
        EffectiveAugmentationSchema augSchemaProxy = new EffectiveAugmentationSchema(augmentSchema,
                realChildSchemas);
        DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> optionalChild = getDispatcher()
                .dispatchChildElement(augSchemaProxy, augmentsToElements.get(augmentSchema));
        if (optionalChild != null) {
            containerBuilder.withChild(optionalChild);
        }
    }

    return buildingStrategy.build(containerBuilder);
}

From source file:org.obiba.magma.type.PolygonType.java

@Override
@SuppressWarnings({ "unchecked", "PMD.NcssMethodCount" })
public int compare(Value o1, Value o2) {
    if (o1.isNull() && o2.isNull())
        return 0;
    if (o1.isNull())
        return -1;
    if (o2.isNull())
        return 1;

    Iterable<List<Coordinate>> list1 = (Iterable<List<Coordinate>>) o1.getValue();
    Iterable<List<Coordinate>> list2 = (Iterable<List<Coordinate>>) o2.getValue();

    if (list1 == list2)
        return 0;
    int size1 = Iterables.size(list1);
    int size2 = Iterables.size(list2);
    if (size1 == size2) {
        for (List<Coordinate> l : list1) {
            if (!Iterables.contains(list2, l))
                return -1;
        }/*from  w  w  w.j  av a  2s.  c om*/
        return 0;
    }
    return size1 < size2 ? -1 : 1;
}

From source file:org.eclipse.elk.layered.p5edges.splines.SplinesMath.java

/**
 * Converts all given KVectors to a readable string with rounded results.
 * @param list The list of KVectors to create the string for.
 * @return The readable string.//from  w  ww .  j a  v  a  2 s  .  co  m
 */
public static String convertKVectorToString(final Iterable<KVector> list) {
    if (list == null || Iterables.size(list) == 0) {
        return NULL_STRING;
    }
    final StringBuilder retVal = new StringBuilder();

    for (final KVector vector : list) {
        retVal.append(convertKVectorToString(vector)).append(", ");
    }

    return retVal.substring(0, retVal.length() - 2);
}

From source file:se.softhouse.jargo.CommandLineParserInstance.java

CommandLineParserInstance(Iterable<Argument<?>> argumentDefinitions, ProgramInformation information,
        Locale locale, boolean isCommandParser) {
    int nrOfArgumentsToHandle = Iterables.size(argumentDefinitions);
    this.indexedArguments = newArrayListWithCapacity(nrOfArgumentsToHandle);
    this.namedArguments = new NamedArguments(nrOfArgumentsToHandle);
    this.specialArguments = new SpecialArguments();
    this.helpArguments = newHashMap();
    this.allArguments = newLinkedHashSetWithExpectedSize(nrOfArgumentsToHandle);

    this.programInformation = information;
    this.locale = locale;
    this.isCommandParser = isCommandParser;
    for (Argument<?> definition : argumentDefinitions) {
        addArgumentDefinition(definition);
    }/*from  w ww  . j a v a 2 s. c  o m*/
    verifyThatIndexedAndRequiredArgumentsWasGivenBeforeAnyOptionalArguments();
    verifyUniqueMetasForRequiredAndIndexedArguments();
    verifyThatOnlyOneArgumentIsOfVariableArity();
}

From source file:org.apache.cassandra.streaming.SessionInfo.java

private long getTotalFilesCompleted(Collection<ProgressInfo> files) {
    Iterable<ProgressInfo> completed = Iterables.filter(files, new Predicate<ProgressInfo>() {
        public boolean apply(ProgressInfo input) {
            return input.isCompleted();
        }//  w  w  w .  ja v  a  2 s .  c  o m
    });
    return Iterables.size(completed);
}

From source file:org.rassee.omniture.pig.OmnitureDataLoader.java

@Override
public Tuple getNext() throws IOException {
    Tuple tuple;//from w w  w  . j av  a2  s. c  om
    Text value;
    Iterable<String> valueIterable;
    Iterator<String> valueIterator;
    int numberOfTabs;

    try {
        // Read the next key-value pair from the record reader.  If it's
        // finished, return null
        if (!reader.nextKeyValue())
            return null;

        value = reader.getCurrentValue();

        valueIterable = Splitter.on('\t').split(value.toString());
        numberOfTabs = Iterables.size(valueIterable);
        valueIterator = valueIterable.iterator();
    } catch (InterruptedException ie) {
        throw new IOException(ie);
    }

    // Create a new Tuple optimized for the number of fields that we know we'll need
    tuple = tupleFactory.newTuple(numberOfTabs + 1);

    if (numberOfTabs != fields.length) {
        LOGGER.error("skipping row - did not find expected tabs in row - expected {}, found {}", fields.length,
                numberOfTabs);
    } else {
        int fieldIndex = 0;
        while (valueIterator.hasNext()) {
            String val = valueIterator.next().trim();
            ResourceFieldSchema field = fields[fieldIndex];

            //field name starts with prop then
            //
            switch (field.getType()) {
            case DataType.INTEGER:
                if (StringUtils.isBlank(val)) {
                    tuple.set(fieldIndex, null);
                } else {
                    try {
                        tuple.set(fieldIndex, Integer.parseInt(val));
                    } catch (NumberFormatException nfe1) {
                        // Throw a more descriptive message
                        throw new NumberFormatException("Error while trying to parse " + val
                                + " into an Integer for field [fieldindex= " + fieldIndex + "] "
                                + field.getName() + "\n" + value.toString());
                    }
                }
                break;
            case DataType.DATETIME:
                if (StringUtils.isBlank(val)) {
                    tuple.set(fieldIndex, null);
                } else {
                    DATE_TIME_FORMATTER.parseDateTime(val);
                }
                break;
            case DataType.CHARARRAY:
                tuple.set(fieldIndex, val);
                break;
            case DataType.LONG:
                if (StringUtils.isBlank(val)) {
                    tuple.set(fieldIndex, null);
                } else {
                    try {
                        tuple.set(fieldIndex, Long.parseLong(val));
                    } catch (NumberFormatException nfe2) {
                        throw new NumberFormatException("Error while trying to parse " + val
                                + " into a Long for field " + field.getName() + "\n" + value.toString());
                    }
                }
                break;
            case DataType.BIGDECIMAL:
                if (StringUtils.isBlank(val)) {
                    tuple.set(fieldIndex, null);
                } else {
                    try {
                        tuple.set(fieldIndex, new BigDecimal(val));
                    } catch (NumberFormatException nfe2) {
                        throw new NumberFormatException("Error while trying to parse " + val
                                + " into a BigDecimal for field " + field.getName() + "\n" + value.toString());
                    }
                }
                break;
            case DataType.BAG:
                if ("event_list".equals(field.getName())) {
                    DataBag bag = bagFactory.newDefaultBag();
                    String[] events = val.split(",");

                    if (events == null) {
                        tuple.set(fieldIndex, null);
                    } else {
                        for (int j = 0; j < events.length; j++) {
                            Tuple t = tupleFactory.newTuple(1);
                            if (events[j] == "") {
                                t.set(0, null);
                            } else {
                                t.set(0, events[j]);
                            }
                            bag.add(t);
                        }
                        tuple.set(fieldIndex, bag);
                    }
                } else {
                    throw new IOException("Can not process bags for the field " + field.getName()
                            + ". Can only process for the event_list field.");
                }
                break;
            default:
                throw new IOException(
                        "Unexpected or unknown type in input schema (Omniture fields should be int, chararray or long): "
                                + field.getType());
            }

            fieldIndex++;
        }
    }

    return tuple;
}

From source file:edu.illinois.keshmesh.detector.Main.java

private static void reportEntryPointStatistics(Reporter reporter, Iterable<Entrypoint> entryPoints) {
    reporter.report(new KeyValuePair("NUMBER_OF_ENTRY_POINTS", String.valueOf(Iterables.size(entryPoints))));
}

From source file:org.lealone.cluster.streaming.SessionInfo.java

private long getTotalFilesCompleted(Collection<ProgressInfo> files) {
    Iterable<ProgressInfo> completed = Iterables.filter(files, new Predicate<ProgressInfo>() {
        @Override/*  w  ww.j  av  a  2s  .  c  om*/
        public boolean apply(ProgressInfo input) {
            return input.isCompleted();
        }
    });
    return Iterables.size(completed);
}

From source file:org.geosdi.geoplatform.experimental.el.dao.AbstractElasticSearchDAO.java

/**
 * @param ids/*w  w w . j ava2s. c o m*/
 * @return {@link List <D>}
 * @throws Exception
 */
@Override
public List<D> findByIDS(Iterable<String> ids, PredicateCondition<D> condition) throws Exception {
    checkArgument((ids != null) && (Iterables.size(ids) > 0));
    MultiGetResponse multiGetResponses = this.elastichSearchClient.prepareMultiGet().setRealtime(TRUE)
            .add(getIndexName(), getIndexType(), ids).get();

    return Arrays.stream(multiGetResponses.getResponses()).filter(response -> !response.isFailed())
            .map(r -> readGetResponse(r.getResponse()))
            .filter(d -> ((condition != null) ? ((d != null) && (condition.test(d))) : d != null))
            .collect(Collectors.toList());
}