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.jclouds.deltacloud.compute.strategy.DeltacloudComputeServiceAdapter.java

Iterable<Transition> findChainTo(Instance.State desired, Instance.State currentState,
        Multimap<Instance.State, ? extends Transition> states) {
    for (Transition transition : states.get(currentState)) {
        if (currentState.ordinal() >= transition.getTo().ordinal())
            continue;
        if (transition.getTo() == desired)
            return ImmutableSet.<Transition>of(transition);
        Iterable<Transition> transitions = findChainTo(desired, transition.getTo(), states);
        if (Iterables.size(transitions) > 0)
            return Iterables.concat(ImmutableSet.of(transition), transitions);
    }//from  www  . ja v  a2  s.  c  o m
    return ImmutableSet.<Transition>of();
}

From source file:com.google.devtools.build.lib.packages.PackageSerializer.java

/**
 * Adds the serialized version of the specified attribute to the specified message.
 *
 * @param rulePb the message to amend/* w w  w.j a va2  s. com*/
 * @param attr the attribute to add
 * @param values the possible values of the attribute (can be a multi-value list for
 *              configurable attributes)
 * @param location the location of the attribute in the source file
 * @param explicitlySpecified whether the attribute was explicitly specified or not
 * @param includeGlobs add glob expression for attributes that contain them
 */
@SuppressWarnings("unchecked")
public static void addAttributeToProto(Build.Rule.Builder rulePb, Attribute attr, Iterable<Object> values,
        Location location, Boolean explicitlySpecified, boolean includeGlobs) {
    // Get the attribute type.  We need to convert and add appropriately
    com.google.devtools.build.lib.packages.Type<?> type = attr.getType();

    Build.Attribute.Builder attrPb = Build.Attribute.newBuilder();

    // Set the type, name and source
    attrPb.setName(attr.getName());
    attrPb.setType(ProtoUtils.getDiscriminatorFromType(type));

    if (location != null) {
        attrPb.setParseableLocation(serializeLocation(location));
    }

    if (explicitlySpecified != null) {
        attrPb.setExplicitlySpecified(explicitlySpecified);
    }

    // Convenience binding for single-value attributes. Because those attributes can only
    // have a single value, when we encounter configurable versions of them we need to
    // react somehow to having multiple possible values to report. We currently just
    // refrain from setting *any* value in that scenario. This variable is set to null
    // to indicate that.
    //
    // For example, for "linkstatic = select({':foo': 0, ':bar': 1})", "values" will contain [0, 1].
    // Since linkstatic is a single-value string element, its proto field (string_value) can't
    // store both values. Since no use case today actually needs this, we just skip it.
    //
    // TODO(bazel-team): support this properly. This will require syntactic change to build.proto
    // (or reinterpretation of its current fields).
    Object singleAttributeValue = Iterables.size(values) == 1 ? Iterables.getOnlyElement(values) : null;

    /*
     * Set the appropriate type and value.  Since string and string list store
     * values for multiple types, use the toString() method on the objects
     * instead of casting them.  Note that Boolean and TriState attributes have
     * both an integer and string representation.
     */
    if (type == INTEGER) {
        if (singleAttributeValue != null) {
            attrPb.setIntValue((Integer) singleAttributeValue);
        }
    } else if (type == STRING || type == LABEL || type == NODEP_LABEL || type == OUTPUT) {
        if (singleAttributeValue != null) {
            attrPb.setStringValue(singleAttributeValue.toString());
        }
    } else if (type == STRING_LIST || type == LABEL_LIST || type == NODEP_LABEL_LIST || type == OUTPUT_LIST
            || type == DISTRIBUTIONS) {
        for (Object value : values) {
            for (Object entry : (Collection<?>) value) {
                attrPb.addStringListValue(entry.toString());
            }
        }
    } else if (type == INTEGER_LIST) {
        for (Object value : values) {
            for (Integer entry : (Collection<Integer>) value) {
                attrPb.addIntListValue(entry);
            }
        }
    } else if (type == BOOLEAN) {
        if (singleAttributeValue != null) {
            if ((Boolean) singleAttributeValue) {
                attrPb.setStringValue("true");
                attrPb.setBooleanValue(true);
            } else {
                attrPb.setStringValue("false");
                attrPb.setBooleanValue(false);
            }
            // This maintains partial backward compatibility for external users of the
            // protobuf that were expecting an integer field and not a true boolean.
            attrPb.setIntValue((Boolean) singleAttributeValue ? 1 : 0);
        }
    } else if (type == TRISTATE) {
        if (singleAttributeValue != null) {
            switch ((TriState) singleAttributeValue) {
            case AUTO:
                attrPb.setIntValue(-1);
                attrPb.setStringValue("auto");
                attrPb.setTristateValue(Build.Attribute.Tristate.AUTO);
                break;
            case NO:
                attrPb.setIntValue(0);
                attrPb.setStringValue("no");
                attrPb.setTristateValue(Build.Attribute.Tristate.NO);
                break;
            case YES:
                attrPb.setIntValue(1);
                attrPb.setStringValue("yes");
                attrPb.setTristateValue(Build.Attribute.Tristate.YES);
                break;
            default:
                throw new AssertionError("Expected AUTO/NO/YES to cover all possible cases");
            }
        }
    } else if (type == LICENSE) {
        if (singleAttributeValue != null) {
            License license = (License) singleAttributeValue;
            Build.License.Builder licensePb = Build.License.newBuilder();
            for (License.LicenseType licenseType : license.getLicenseTypes()) {
                licensePb.addLicenseType(licenseType.toString());
            }
            for (Label exception : license.getExceptions()) {
                licensePb.addException(exception.toString());
            }
            attrPb.setLicense(licensePb);
        }
    } else if (type == STRING_DICT) {
        // TODO(bazel-team): support better de-duping here and in other dictionaries.
        for (Object value : values) {
            Map<String, String> dict = (Map<String, String>) value;
            for (Map.Entry<String, String> keyValueList : dict.entrySet()) {
                Build.StringDictEntry entry = Build.StringDictEntry.newBuilder().setKey(keyValueList.getKey())
                        .setValue(keyValueList.getValue()).build();
                attrPb.addStringDictValue(entry);
            }
        }
    } else if (type == STRING_DICT_UNARY) {
        for (Object value : values) {
            Map<String, String> dict = (Map<String, String>) value;
            for (Map.Entry<String, String> dictEntry : dict.entrySet()) {
                Build.StringDictUnaryEntry entry = Build.StringDictUnaryEntry.newBuilder()
                        .setKey(dictEntry.getKey()).setValue(dictEntry.getValue()).build();
                attrPb.addStringDictUnaryValue(entry);
            }
        }
    } else if (type == STRING_LIST_DICT) {
        for (Object value : values) {
            Map<String, List<String>> dict = (Map<String, List<String>>) value;
            for (Map.Entry<String, List<String>> dictEntry : dict.entrySet()) {
                Build.StringListDictEntry.Builder entry = Build.StringListDictEntry.newBuilder()
                        .setKey(dictEntry.getKey());
                for (Object dictEntryValue : dictEntry.getValue()) {
                    entry.addValue(dictEntryValue.toString());
                }
                attrPb.addStringListDictValue(entry);
            }
        }
    } else if (type == LABEL_LIST_DICT) {
        for (Object value : values) {
            Map<String, List<Label>> dict = (Map<String, List<Label>>) value;
            for (Map.Entry<String, List<Label>> dictEntry : dict.entrySet()) {
                Build.LabelListDictEntry.Builder entry = Build.LabelListDictEntry.newBuilder()
                        .setKey(dictEntry.getKey());
                for (Object dictEntryValue : dictEntry.getValue()) {
                    entry.addValue(dictEntryValue.toString());
                }
                attrPb.addLabelListDictValue(entry);
            }
        }
    } else if (type == FILESET_ENTRY_LIST) {
        for (Object value : values) {
            List<FilesetEntry> filesetEntries = (List<FilesetEntry>) value;
            for (FilesetEntry filesetEntry : filesetEntries) {
                Build.FilesetEntry.Builder filesetEntryPb = Build.FilesetEntry.newBuilder()
                        .setSource(filesetEntry.getSrcLabel().toString())
                        .setDestinationDirectory(filesetEntry.getDestDir().getPathString())
                        .setSymlinkBehavior(symlinkBehaviorToPb(filesetEntry.getSymlinkBehavior()))
                        .setStripPrefix(filesetEntry.getStripPrefix())
                        .setFilesPresent(filesetEntry.getFiles() != null);

                if (filesetEntry.getFiles() != null) {
                    for (Label file : filesetEntry.getFiles()) {
                        filesetEntryPb.addFile(file.toString());
                    }
                }

                if (filesetEntry.getExcludes() != null) {
                    for (String exclude : filesetEntry.getExcludes()) {
                        filesetEntryPb.addExclude(exclude);
                    }
                }

                attrPb.addFilesetListValue(filesetEntryPb);
            }
        }
    } else {
        throw new AssertionError("Unknown type: " + type);
    }

    if (includeGlobs) {
        for (Object value : values) {
            if (value instanceof GlobList<?>) {
                GlobList<?> globList = (GlobList<?>) value;

                for (GlobCriteria criteria : globList.getCriteria()) {
                    Build.GlobCriteria.Builder criteriaPb = Build.GlobCriteria.newBuilder()
                            .setGlob(criteria.isGlob());
                    for (String include : criteria.getIncludePatterns()) {
                        criteriaPb.addInclude(include);
                    }
                    for (String exclude : criteria.getExcludePatterns()) {
                        criteriaPb.addExclude(exclude);
                    }

                    attrPb.addGlobCriteria(criteriaPb);
                }
            }
        }
    }

    rulePb.addAttribute(attrPb);
}

From source file:org.apache.metron.elasticsearch.client.ElasticsearchClient.java

/**
 * Gets ALL Elasticsearch indices, or null if status code returned is not OK 200.
 *//*from w w w  .  j  av  a  2s  .c  o  m*/
public String[] getIndices() throws IOException {
    Response response = lowLevelClient.performRequest("GET", "/_cat/indices");
    if (response.getStatusLine().getStatusCode() == 200) {
        String responseStr = IOUtils.toString(response.getEntity().getContent());
        List<String> indices = new ArrayList<>();
        for (String line : Splitter.on("\n").split(responseStr)) {
            Iterable<String> splits = Splitter.on(" ").split(line.replaceAll("\\s+", " ").trim());
            if (Iterables.size(splits) > 3) {
                String index = Iterables.get(splits, 2, "");
                if (!StringUtils.isEmpty(index)) {
                    indices.add(index.trim());
                }
            }
        }
        String[] ret = new String[indices.size()];
        ret = indices.toArray(ret);
        return ret;
    }
    return null;
}

From source file:org.onos.yangtools.binding.generator.util.BindingGeneratorUtil.java

/**
 * Creates package name from specified <code>basePackageName</code> (package
 * name for module) and <code>schemaPath</code>.
 *
 * Resulting package name is concatenation of <code>basePackageName</code>
 * and all local names of YANG nodes which are parents of some node for
 * which <code>schemaPath</code> is specified.
 *
 * @param basePackageName/*  w w  w .jav a2  s .  c om*/
 *            string with package name of the module
 * @param schemaPath
 *            list of names of YANG nodes which are parents of some node +
 *            name of this node
 * @return string with valid JAVA package name
 */
public static String packageNameForGeneratedType(final String basePackageName, final SchemaPath schemaPath,
        final boolean isUsesAugment) {
    if (basePackageName == null) {
        throw new IllegalArgumentException("Base Package Name cannot be NULL!");
    }
    if (schemaPath == null) {
        throw new IllegalArgumentException("Schema Path cannot be NULL!");
    }

    final StringBuilder builder = new StringBuilder();
    builder.append(basePackageName);
    final Iterable<QName> iterable = schemaPath.getPathFromRoot();
    final Iterator<QName> iterator = iterable.iterator();
    int size = Iterables.size(iterable);
    final int traversalSteps;
    if (isUsesAugment) {
        traversalSteps = size;
    } else {
        traversalSteps = size - 1;
    }
    for (int i = 0; i < traversalSteps; ++i) {
        builder.append('.');
        String nodeLocalName = iterator.next().getLocalName();
        // FIXME: Collon ":" is invalid in node local name as per RFC6020, identifier statement.
        builder.append(DASH_COLON_MATCHER.replaceFrom(nodeLocalName, '.'));
    }
    return BindingMapping.normalizePackageName(builder.toString());
}

From source file:uk.co.unclealex.executable.generator.ScripterImpl.java

/**
 * Generate all the classes required by the scripting framework.
 * //from w  w  w .ja  v a2  s  .  c o  m
 * @param sourceDirectory
 *          The directory containing the classes to be scanned for
 *          {@link Executable} annotations.
 * @param workDirectory
 *          The directory in which the jar file will be stored.
 * @return A jar file containing all generated sources.
 * @throws IOException
 * @throws ExecutableScanException
 */
protected Path generateCodeJar(Path sourceDirectory, Path workDirectory, Iterable<Path> dependencyJarFiles)
        throws IOException, ExecutableScanException {
    Path targetDirectory = workDirectory.resolve("generated-classes");
    Files.createDirectories(targetDirectory);
    URL[] urls = new URL[Iterables.size(dependencyJarFiles)];
    int idx = 0;
    for (Path dependencyJarFile : dependencyJarFiles) {
        urls[idx++] = dependencyJarFile.toUri().toURL();
    }
    ClassLoader classLoader = new URLClassLoader(urls, getClass().getClassLoader());
    getCodeGenerator().generate(classLoader, sourceDirectory, targetDirectory);
    Path jarFile = workDirectory.resolve("generated.jar");
    getJarService().generateJar(targetDirectory, jarFile);
    return jarFile;
}

From source file:grkvlt.Ec2CleanUp.java

/**
 * Delete all matching {@link SecurityGroup}s.
 *//*w  w  w.j  av a2 s  . co  m*/
public void deleteSecurityGroups(SecurityGroupClient securityGroupApi) throws Exception {
    Set<SecurityGroup> groups = securityGroupApi.describeSecurityGroupsInRegion(region);
    Iterable<String> filtered = Iterables
            .filter(Iterables.transform(groups, new Function<SecurityGroup, String>() {
                @Override
                public String apply(@Nullable SecurityGroup input) {
                    return input.getName();
                }
            }), Predicates.containsPattern("^" + regexp + "$"));
    LOG.info("Found {} matching SecurityGroups", Iterables.size(filtered));
    if (!check) {
        int deleted = 0;
        for (String name : filtered) {
            try {
                securityGroupApi.deleteSecurityGroupInRegion(region, name);
                deleted++;
            } catch (Exception e) {
                if (e.getMessage() != null && e.getMessage().contains("RequestLimitExceeded")) {
                    Thread.sleep(1000l); // Avoid triggering rate-limiter again
                }
                LOG.warn("Error deleting SecurityGroup '{}': {}", name, e.getMessage());
            }
        }
        LOG.info("Deleted {} SecurityGroups", deleted);
    }
}

From source file:net.floodlightcontroller.core.internal.OFConnection.java

/**
 * All write methods chain into this write() to use WriteMessageTask.
 * //from w ww.j a v  a2 s . c o  m
 * Write the list of messages to the switch
 * 
 * @param msgList list of messages to write
 * @return list of failed messages; can only fail if channel disconnected
 */
@Override
public Collection<OFMessage> write(final Iterable<OFMessage> msgList) {
    if (!isConnected()) {
        if (logger.isDebugEnabled())
            logger.debug(this.toString() + " : not connected - dropping {} element msglist {} ",
                    Iterables.size(msgList), String.valueOf(msgList).substring(0, 80));
        return IterableUtils.toCollection(msgList);
    }
    for (OFMessage m : msgList) {
        if (logger.isTraceEnabled()) {
            logger.trace("{}: send {}", this, m);
            counters.updateWriteStats(m);
        }
    }
    this.channel.eventLoop().execute(new WriteMessageTask(msgList));
    return Collections.emptyList();
}

From source file:com.ltln.modules.openflow.controller.manager.OFConnection.java

/**
 * All write methods chain into this write() to use WriteMessageTask.
 * //www.  j  a  v a  2 s.  com
 * Write the list of messages to the switch
 * 
 * @param msgList list of messages to write
 * @return list of failed messages; can only fail if channel disconnected
 */
@Override
public Collection<OFMessage> write(final Iterable<OFMessage> msgList) {
    if (!isConnected()) {
        if (logger.isDebugEnabled())
            logger.debug(this.toString() + " : not connected - dropping {} element msglist {} ",
                    Iterables.size(msgList), String.valueOf(msgList).substring(0, 80));
        return IterableUtils.toCollection(msgList);
    }
    for (OFMessage m : msgList) {
        if (logger.isTraceEnabled()) {
            logger.trace("{}: send {}", this, m);
            //            counters.updateWriteStats(m);
        }
    }
    this.channel.eventLoop().execute(new WriteMessageTask(msgList));
    return Collections.emptyList();
}

From source file:com.facebook.buck.apple.xcode.ProjectGeneratorTestUtils.java

public static <T extends PBXBuildPhase> T getSingletonPhaseByType(PBXTarget target, final Class<T> cls) {
    Iterable<PBXBuildPhase> buildPhases = Iterables.filter(target.getBuildPhases(),
            new Predicate<PBXBuildPhase>() {
                @Override//  w  w w .  j  av a  2  s .com
                public boolean apply(PBXBuildPhase input) {
                    return cls.isInstance(input);
                }
            });
    assertEquals("Build phase should be singleton", 1, Iterables.size(buildPhases));
    @SuppressWarnings("unchecked")
    T element = (T) Iterables.getOnlyElement(buildPhases);
    return element;
}