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

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

Introduction

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

Prototype

public static boolean isEmpty(Iterable<?> iterable) 

Source Link

Document

Determines if the given iterable contains no elements.

Usage

From source file:org.jon.ivmark.graphit.core.graph.traversal.Traversable.java

public boolean isEmpty() {
    return Iterables.isEmpty(iterable);
}

From source file:brooklyn.event.basic.AbstractCollectionConfigKey.java

@SuppressWarnings({ "rawtypes", "unchecked" })
protected Object applyValueToMap(Object value, Map target, boolean isInCollection) {
    if (value instanceof StructuredModification) {
        return ((StructuredModification) value).applyToKeyInMap(this, target);
    } else if ((value instanceof Iterable) && (!isInCollection)) {
        // collections set _here_ (not in subkeys) get added
        boolean isSet = isSet(target);
        if (isSet) {
            String warning = "Discouraged undecorated setting of a collection to in-use StructuredConfigKey "
                    + this + ": use SetModification.{set,add}. "
                    + "Defaulting to 'add'. Look at debug logging for call stack.";
            log.warn(warning);//from www .j a va 2s . c o m
            if (log.isDebugEnabled())
                log.debug("Trace for: " + warning, new Throwable("Trace for: " + warning));
        }
        Iterable<?> valueI = (Iterable<?>) value;
        for (Object v : valueI) {
            // don't continue to recurse into these collections, however
            applyValueToMap(v, target, true);
        }
        if (Iterables.isEmpty(valueI) && !isSet) {
            target.put(this, MutableSet.of());
        }
        return null;
    } else if (value instanceof TaskAdaptable) {
        boolean isSet = isSet(target);
        if (isSet) {
            String warning = "Discouraged undecorated setting of a task to in-use StructuredConfigKey " + this
                    + ": use SetModification.{set,add}. "
                    + "Defaulting to 'add'. Look at debug logging for call stack.";
            log.warn(warning);
            if (log.isDebugEnabled())
                log.debug("Trace for: " + warning, new Throwable("Trace for: " + warning));
        }
        // just add to set, using anonymous key
        target.put(subKey(), value);
        return null;
    } else {
        // just add to set, using anonymous key
        target.put(subKey(), value);
        return null;
    }
}

From source file:com.facebook.buck.jvm.java.ClasspathChecker.java

/**
 * Parses a Java classpath string ("path/to/foo:baz.jar:blech.zip:path/to/*")
 * and checks if at least one entry is valid (exists on disk).
 *
 * From http://docs.oracle.com/javase/8/docs/technotes/tools/windows/classpath.html :
 *
 * Class path entries can contain the basename wildcard character *,
 * which is considered equivalent to specifying a list of all the
 * files in the directory with the extension .jar or .JAR. For
 * example, the class path entry foo/* specifies all JAR files in the
 * directory named foo. A classpath entry consisting simply of *
 * expands to a list of all the jar files in the current directory.
 *//*w ww. ja  va 2s.  c om*/
public boolean validateClasspath(String classpath) {
    for (String entry : Splitter.on(pathSeparator).split(classpath)) {
        // On Windows, Path.endsWith("*") throws an error:
        //
        // java.nio.file.InvalidPathException: Illegal char <*> at index 0
        //
        // So, we split manually.
        List<String> classpathComponents = Splitter.on(separator).splitToList(entry);
        if (classpathComponents.isEmpty()) {
            continue;
        }

        if (Iterables.getLast(classpathComponents).equals("*")) {
            // Trim the * off the path.
            List<String> dirComponents = classpathComponents.subList(0, classpathComponents.size() - 1);
            Path entryDir = toPathFunc.apply(Joiner.on(separator).join(dirComponents));
            if (!Iterables.isEmpty(globberFunc.apply(entryDir, "*.jar"))) {
                return true;
            } else if (!Iterables.isEmpty(globberFunc.apply(entryDir, "*.JAR"))) {
                return true;
            }
        } else {
            Path entryPath = toPathFunc.apply(entry);
            if (isDirectoryFunc.apply(entryPath)) {
                return true;
            } else if (isFileFunc.apply(entryPath) && ALLOWED_EXTENSIONS_SET.contains(
                    com.google.common.io.Files.getFileExtension(entryPath.toString().toLowerCase(Locale.US)))) {
                return true;
            }
        }
    }
    return false;
}

From source file:com.google.devtools.build.lib.rules.objc.ObjcProtoAspect.java

@Override
public ConfiguredAspect create(ConfiguredTarget base, RuleContext ruleContext, AspectParameters parameters)
        throws InterruptedException {
    ConfiguredAspect.Builder aspectBuilder = new ConfiguredAspect.Builder(this, parameters, ruleContext);

    ObjcProtoProvider.Builder aspectObjcProtoProvider = new ObjcProtoProvider.Builder();

    if (ruleContext.attributes().has("deps", BuildType.LABEL_LIST)) {
        Iterable<ObjcProtoProvider> depObjcProtoProviders = ruleContext.getPrerequisites("deps", Mode.TARGET,
                ObjcProtoProvider.class);
        aspectObjcProtoProvider.addTransitive(depObjcProtoProviders);
    }/*from   ww w  . j a  va  2 s  . c  om*/

    ProtoAttributes attributes = new ProtoAttributes(ruleContext);

    // If the rule has the portable_proto_filters or uses_protobuf, it must be an objc_proto_library
    // configured to use the third party protobuf library, in contrast with the PB2 internal
    // library. Only the third party library is enabled to propagate the protos with this aspect.
    // Validation for the correct target attributes is done in ProtoSupport.java.
    if (attributes.requiresProtobuf()) {

        // Gather up all the dependency protos depended by this target.
        Iterable<ProtoSourcesProvider> protoProviders = ruleContext.getPrerequisites("deps", Mode.TARGET,
                ProtoSourcesProvider.class);

        for (ProtoSourcesProvider protoProvider : protoProviders) {
            aspectObjcProtoProvider.addProtoGroup(protoProvider.getTransitiveProtoSources());
        }

        NestedSet<Artifact> portableProtoFilters = PrerequisiteArtifacts.nestedSet(ruleContext,
                ObjcProtoLibraryRule.PORTABLE_PROTO_FILTERS_ATTR, Mode.HOST);

        // If this target does not provide filters but specifies direct proto_library dependencies,
        // generate a filter file only for those proto files.
        if (Iterables.isEmpty(portableProtoFilters) && !Iterables.isEmpty(protoProviders)) {
            Artifact generatedFilter = ProtobufSupport.getGeneratedPortableFilter(ruleContext);
            ProtobufSupport.registerPortableFilterGenerationAction(ruleContext, generatedFilter,
                    protoProviders);
            portableProtoFilters = NestedSetBuilder.create(Order.STABLE_ORDER, generatedFilter);
        }

        aspectObjcProtoProvider.addPortableProtoFilters(portableProtoFilters);

        // Propagate protobuf's headers and search paths so the BinaryLinkingTargetFactory subclasses
        // (i.e. objc_binary) don't have to depend on it.
        ObjcProvider protobufObjcProvider = ruleContext.getPrerequisite(ObjcRuleClasses.PROTO_LIB_ATTR,
                Mode.TARGET, ObjcProvider.class);
        aspectObjcProtoProvider.addProtobufHeaders(protobufObjcProvider.get(ObjcProvider.HEADER));
        aspectObjcProtoProvider.addProtobufHeaderSearchPaths(protobufObjcProvider.get(ObjcProvider.INCLUDE));
    }

    // Only add the provider if it has any values, otherwise skip it.
    if (!aspectObjcProtoProvider.isEmpty()) {
        aspectBuilder.addProvider(aspectObjcProtoProvider.build());
    }
    return aspectBuilder.build();
}

From source file:org.sonar.plugins.pmd.PmdExecutor.java

public void executeRules(PmdTemplate pmdFactory, RuleContext ruleContext, Iterable<File> files,
        String repositoryKey) {// w w w.ja  va 2  s. c  o m
    if (Iterables.isEmpty(files)) {
        // Nothing to analyze
        return;
    }

    RuleSets rulesets = createRulesets(repositoryKey);
    if (rulesets.getAllRules().isEmpty()) {
        // No rule
        return;
    }

    rulesets.start(ruleContext);

    for (File file : files) {
        pmdFactory.process(file, rulesets, ruleContext);
    }

    rulesets.end(ruleContext);
}

From source file:com.caiyunworks.crm.business.service.impl.HolidayServiceImpl.java

@Override
public int update(Holiday record) throws UnsupportedOperationException, RecordNotExistException,
        OutOfDateRecordException, RecordAlreadyExistException {
    Holiday holiday = holidayRepository.findById(record.getId());
    if (null == holiday) {
        if (logger.isWarnEnabled()) {
            logger.warn("try to update holiday {}, but it does not exist in DB.", record.getId());
        }//from w w  w  .ja  va 2 s .  c o m
        throw new RecordNotExistException();
    } else {
        if (!holiday.getVersionNumber().equals(record.getVersionNumber())) {
            if (logger.isWarnEnabled()) {
                logger.warn("holiday record is out of date, version {}, latest version {}",
                        record.getVersionNumber(), holiday.getVersionNumber());
            }
            throw new OutOfDateRecordException();
        }

        Iterable<Holiday> holidays = holidayRepository.findByNameOrDateRange(record.getName(),
                record.getStartDate(), record.getEndDate());
        if (null == holidays || Iterables.isEmpty(holidays)) {
            return holidayRepository.update(record);
        } else {
            if (Iterables.size(holidays) == 1 && Iterables.get(holidays, 0).getId() == record.getId()) {
                return holidayRepository.update(record);
            } else {
                if (logger.isWarnEnabled()) {
                    logger.warn("try to update holiday {}, but it is already exist in DB.", record);
                }
                throw new RecordAlreadyExistException();
            }
        }
    }
}

From source file:org.apache.abdera2.parser.axiom.FOMParser.java

public <T extends Element> Document<T> parse(InputStream in, String base, ParserOptions options)
        throws ParseException {
    if (in == null)
        throw new IllegalArgumentException(Localizer.get("INPUTSTREAM.NOT.NULL"));
    try {/*  w w w  .  j  a va 2s .  co  m*/
        if (options == null)
            options = getDefaultParserOptions();
        if (!Iterables.isEmpty(options.getCompressionCodecs()))
            in = Compression.wrap(in, options.getCompressionCodecs());
        String charset = options.getCharset();
        if (charset == null && options.getAutodetectCharset()) {
            XMLStreamSniffingInputStream sin = (in instanceof XMLStreamSniffingInputStream)
                    ? (XMLStreamSniffingInputStream) in
                    : new XMLStreamSniffingInputStream(in);
            charset = sin.getEncoding();
            if (charset != null)
                options = options.usingCharset(charset);
            in = sin;
        }
        if (options.getFilterRestrictedCharacters()) {
            Reader rdr = (charset == null)
                    ? new XmlRestrictedCharReader(in, options.getFilterRestrictedCharacterReplacement())
                    : new XmlRestrictedCharReader(in, charset,
                            options.getFilterRestrictedCharacterReplacement());
            return parse(StAXUtils.createXMLStreamReader(rdr), base, options);
        } else {
            XMLStreamReader xmlreader = (charset == null) ? createXMLStreamReader(in)
                    : createXMLStreamReader(in, charset);
            return parse(xmlreader, base, options);
        }
    } catch (Exception e) {
        if (!(e instanceof ParseException))
            e = new ParseException(e);
        throw (ParseException) e;
    }
}

From source file:com.textocat.textokit.dictmatcher.TaggedChunkerBuilderResource.java

private DictEntry parseLine(String line, int lineNum) {
    line = line.trim();/*from w w w  .  j a v  a  2s.  c o m*/
    if (line.isEmpty()) {
        return null;
    }
    if (line.startsWith("#")) {
        return null;
    }
    String[] tokTagSplit = line.split(TAG_DELIMITER);
    if (tokTagSplit.length != 2)
        cantParseLine(line);
    String tag = tokTagSplit[1].trim().intern();
    Iterable<String> tokens = TOKEN_SPLITTER.split(tokTagSplit[0]);
    if (Iterables.isEmpty(tokens)) {
        log.warn("Line {} contains empty record!", lineNum);
        return null;
    }
    return new DictEntry(tokens, tag);
}

From source file:iterator.Animator.java

/**
 * Parse the animation configuration file.
 *
 * See the online documentation for more details. The format is generally as shown below:
 *
 * <pre>/*from www .  jav  a2  s. c om*/
 * {@code # comment
 * ifs file
 * save directory
 * frames count
 * delay ms
 * iterations thousands
 * zoom scale centrex centrey
 * segment frames
 *     transform id field start finish
 * end}
 * </pre>
 *
 * @see <a href="http://grkvlt.github.io/iterator/">online documentation</a>
 * @throws IOException
 * @throws IllegalStateException
 * @throws NumberFormatException
 */
public void parse(File config) throws IOException {
    for (String line : Files.readLines(config, Charsets.UTF_8)) {
        Iterable<String> tokens = Splitter.on(' ').omitEmptyStrings().trimResults().split(line);
        if (Iterables.isEmpty(tokens))
            continue;
        String type = Iterables.get(tokens, 0);
        if (type.equalsIgnoreCase("ifs")) {
            // ifs file
            if (Iterables.size(tokens) != 2) {
                throw new IllegalStateException("Parse error at 'ifs': " + line);
            }
            input = new File(Iterables.get(tokens, 1).replace("~", System.getProperty("user.home")));
        } else if (type.equalsIgnoreCase("save")) {
            // save directory
            if (Iterables.size(tokens) != 2) {
                throw new IllegalStateException("Parse error at 'save': " + line);
            }
            output = new File(Iterables.get(tokens, 1).replace("~", System.getProperty("user.home")));
        } else if (type.equalsIgnoreCase("frames")) {
            // frames count
            if (Iterables.size(tokens) != 2) {
                throw new IllegalStateException("Parse error at 'frames': " + line);
            }
            frames = Long.valueOf(Iterables.get(tokens, 1));
        } else if (type.equalsIgnoreCase("delay")) {
            // delay ms
            if (Iterables.size(tokens) != 2) {
                throw new IllegalStateException("Parse error at 'delay': " + line);
            }
            delay = Long.valueOf(Iterables.get(tokens, 1));
        } else if (type.equalsIgnoreCase("iterations")) {
            // iterations thousands
            if (Iterables.size(tokens) != 2) {
                throw new IllegalStateException("Parse error at 'iterations': " + line);
            }
            iterations = Long.valueOf(Iterables.get(tokens, 1));
        } else if (type.equalsIgnoreCase("zoom")) {
            // zoom scale centrex centrey
            if (Iterables.size(tokens) != 4) {
                throw new IllegalStateException("Parse error at 'zoom': " + line);
            }
            scale = Float.valueOf(Iterables.get(tokens, 1));
            centre = new Point2D.Double(Double.valueOf(Iterables.get(tokens, 2)),
                    Double.valueOf(Iterables.get(tokens, 3)));
        } else if (type.equalsIgnoreCase("transform")) {
            // transform id field start finish
            if (Iterables.size(tokens) != 5) {
                throw new IllegalStateException("Parse error at 'transform': " + line);
            }
            Change change = new Change();
            change.transform = Integer.valueOf(Iterables.get(tokens, 1));
            String field = Iterables.get(tokens, 2).toLowerCase();
            if (field.length() == 1 && CharMatcher.anyOf("xywhr").matches(field.charAt(0))) {
                change.field = field.charAt(0);
            } else {
                throw new IllegalStateException("Parse error at 'transform' field: " + line);
            }
            change.start = Double.valueOf(Iterables.get(tokens, 3));
            change.end = Double.valueOf(Iterables.get(tokens, 4));
            list.add(change);
        } else if (type.equalsIgnoreCase("segment")) {
            // segment frames?
            if (Iterables.size(tokens) == 2) {
                segment = Long.valueOf(Iterables.get(tokens, 1));
            } else {
                segment = frames;
            }
            list.clear();
        } else if (type.equalsIgnoreCase("end")) {
            // end
            if (Iterables.size(tokens) != 1) {
                throw new IllegalStateException("Parse error at 'end': " + line);
            }
            segments.put(ImmutableList.copyOf(list), segment);
        } else if (type.startsWith("#")) {
            // # comment
            continue;
        } else {
            throw new IllegalStateException("Parse error: " + line);
        }
    }

    // Deal with single segment case (no 'segment' or 'end' token)
    if (segments.isEmpty() && list.size() > 0) {
        segments.put(ImmutableList.copyOf(list), frames);
    }
}

From source file:org.apache.twill.internal.AbstractTwillController.java

public AbstractTwillController(String appName, RunId runId, ZKClient zkClient, boolean logCollectionEnabled,
        Iterable<LogHandler> logHandlers) {
    super(runId, zkClient);
    this.appName = appName;
    this.runId = runId;
    this.logHandlers = new ConcurrentLinkedQueue<>();

    // When addressing TWILL-147, need to check if the given ZKClient is
    // actually used by the Kafka used for log collection
    if (logCollectionEnabled) {
        this.kafkaClient = new ZKKafkaClientService(
                ZKClients.namespace(zkClient, "/" + runId.getId() + "/kafka"));
        Iterables.addAll(this.logHandlers, logHandlers);
    } else {/*w w  w.j  a  va2s  .  c om*/
        this.kafkaClient = null;
        if (!Iterables.isEmpty(logHandlers)) {
            LOG.warn("Log collection is disabled for application {} with runId {}. "
                    + "Adding log handler won't get any logs.", appName, runId);
        }
    }
}