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:monasca.api.infrastructure.persistence.hibernate.AlarmDefinitionSqlRepoImpl.java

@Override
public AlarmDefinition create(String tenantId, String id, String name, String description, String severity,
        String expression, Map<String, AlarmSubExpression> subExpressions, List<String> matchBy,
        List<String> alarmActions, List<String> okActions, List<String> undeterminedActions) {
    logger.trace(ORM_LOG_MARKER, "create(...) entering...");

    Transaction tx = null;//from   ww w.j  a  v a  2  s .com
    Session session = null;
    try {
        session = sessionFactory.openSession();
        tx = session.beginTransaction();

        final DateTime now = this.getUTCNow();
        final AlarmDefinitionDb alarmDefinition = new AlarmDefinitionDb(id, tenantId, name, description,
                expression, AlarmSeverity.valueOf(severity.toUpperCase()),
                matchBy == null || Iterables.isEmpty(matchBy) ? null : COMMA_JOINER.join(matchBy), true, now,
                now, null);
        session.save(alarmDefinition);

        this.createSubExpressions(session, alarmDefinition, subExpressions);

        // Persist actions
        this.persistActions(session, alarmDefinition, AlarmState.ALARM, alarmActions);
        this.persistActions(session, alarmDefinition, AlarmState.OK, okActions);
        this.persistActions(session, alarmDefinition, AlarmState.UNDETERMINED, undeterminedActions);

        tx.commit();
        tx = null;

        logger.debug(ORM_LOG_MARKER, "AlarmDefinition [ {} ] has been committed to database", alarmDefinition);

        return new AlarmDefinition(id, name, description, severity, expression, matchBy, true,
                alarmActions == null ? Collections.<String>emptyList() : alarmActions,
                okActions == null ? Collections.<String>emptyList() : okActions,
                undeterminedActions == null ? Collections.<String>emptyList() : undeterminedActions);

    } catch (RuntimeException e) {
        this.rollbackIfNotNull(tx);
        throw e;
    } finally {
        if (session != null) {
            session.close();
        }
    }
}

From source file:eu.seaclouds.common.apps.SeaCloudsApp.java

private boolean checkEntity(Entity entity) {
    return entity instanceof SoftwareProcess && Entities.isAncestor(entity, this)
            && Iterables.isEmpty(Iterables.filter(entity.getPolicies(), DataCollectorInstallationPolicy.class));
}

From source file:com.google.devtools.j2objc.util.CaptureInfo.java

public boolean isCapturing(TypeElement type) {
    return !Iterables.isEmpty(Iterables.filter(getCaptures(type), Capture::hasField));
}

From source file:com.vmware.appfactory.common.runner.BackgroundProcessor.java

private void processFeeds() throws DsException, AfNotFoundException, WpException {
    _log.trace("Scanning feeds:");
    FeedDao feedDao = _daoFactory.getFeedDao();
    List<Feed> feeds = feedDao.findAll();

    long rescanPeriodMs = getFeedRescanFrequency();
    boolean retryFailedScan = _config.getBool(ConfigRegistryConstants.FEED_RETRY_FAILED_SCAN);

    for (final Feed feed : feeds) {
        /* Skip if scanning disabled */
        if (!feed.isOkToScan()) {
            continue;
        }//  w w  w.j  a va  2 s.  c o m

        /* Skip if recently scanned */
        if ((AfCalendar.Now() - feed.getLastScan()) < rescanPeriodMs) {
            continue;
        }

        /* Skip if failed */
        if ((null != feed.getFailure()) && !retryFailedScan) {
            continue;
        }

        /* See what active tasks we have for this feed */

        // then conversion tasks
        Iterable<? extends TaskState> activeTasks = _scanningQueue.findActiveTasksForFeed(feed.getId());
        /* Skip if currently active */
        if (!Iterables.isEmpty(activeTasks)) {
            continue;
        }

        /* Feed needs to be scanned */

        AppFactoryTask feedTask = _taskFactory.newFeedScanTask(feed, _conversionsQueue);
        _scanningQueue.addTask(feedTask);
    }
}

From source file:com.google.devtools.build.buildjar.javac.BlazeJavacMain.java

private static void setLocations(JavacFileManager fileManager, BlazeJavacArguments arguments) {
    try {//from w  w  w .  j ava  2 s  . c o m
        fileManager.setLocationFromPaths(StandardLocation.CLASS_PATH, arguments.classPath());
        fileManager.setLocationFromPaths(StandardLocation.CLASS_OUTPUT,
                ImmutableList.of(arguments.classOutput()));
        fileManager.setLocationFromPaths(StandardLocation.SOURCE_PATH, ImmutableList.of());
        // TODO(cushon): require an explicit bootclasspath
        Iterable<Path> bootClassPath = arguments.bootClassPath();
        if (!Iterables.isEmpty(bootClassPath)) {
            fileManager.setLocationFromPaths(StandardLocation.PLATFORM_CLASS_PATH, bootClassPath);
        }
        fileManager.setLocationFromPaths(StandardLocation.ANNOTATION_PROCESSOR_PATH, arguments.processorPath());
        if (arguments.sourceOutput() != null) {
            fileManager.setLocationFromPaths(StandardLocation.SOURCE_OUTPUT,
                    ImmutableList.of(arguments.sourceOutput()));
        }
    } catch (IOException e) {
        throw new IOError(e);
    }
}

From source file:com.twitter.common.zookeeper.CandidateImpl.java

@Override
public Supplier<Boolean> offerLeadership(final Leader leader)
        throws JoinException, WatchException, InterruptedException {

    final Membership membership = group.join(dataSupplier, new Command() {
        @Override//from   www  .j a  v  a  2s.c  o m
        public void execute() {
            leader.onDefeated();
        }
    });

    final AtomicBoolean elected = new AtomicBoolean(false);
    final AtomicBoolean abdicated = new AtomicBoolean(false);
    group.watch(new GroupChangeListener() {
        @Override
        public void onGroupChange(Iterable<String> memberIds) {
            boolean noCandidates = Iterables.isEmpty(memberIds);
            String memberId = membership.getMemberId();

            if (noCandidates) {
                LOG.warning("All candidates have temporarily left the group: " + group);
            } else if (!Iterables.contains(memberIds, memberId)) {
                LOG.severe(
                        String.format("Current member ID %s is not a candidate for leader, current voting: %s",
                                memberId, memberIds));
            } else {
                boolean electedLeader = memberId.equals(getLeader(memberIds));
                boolean previouslyElected = elected.getAndSet(electedLeader);

                if (!previouslyElected && electedLeader) {
                    LOG.info(String.format("Candidate %s is now leader of group: %s",
                            membership.getMemberPath(), memberIds));

                    leader.onElected(new ExceptionalCommand<JoinException>() {
                        @Override
                        public void execute() throws JoinException {
                            membership.cancel();
                            abdicated.set(true);
                        }
                    });
                } else if (!electedLeader) {
                    if (previouslyElected) {
                        leader.onDefeated();
                    }
                    LOG.info(String.format(
                            "Candidate %s waiting for the next leader election, current voting: %s",
                            membership.getMemberPath(), memberIds));
                }
            }
        }
    });

    return new Supplier<Boolean>() {
        @Override
        public Boolean get() {
            return !abdicated.get() && elected.get();
        }
    };
}

From source file:com.google.devtools.build.lib.actions.MiddlemanFactory.java

/**
 * Creates a {@link MiddlemanType#ERROR_PROPAGATING_MIDDLEMAN error-propagating} middleman.
 *
 * @param owner the owner of the action that will be created. May not be null.
 * @param middlemanName a unique file name for the middleman artifact in the {@code middlemanDir};
 *        in practice this is usually the owning rule's label (so it gets escaped as such)
 * @param purpose the purpose for which this middleman is created. This should be a string which
 *        is suitable for use as a filename. A single rule may have many middlemen with distinct
 *        purposes.//from   w w  w .ja v  a2s .  c om
 * @param inputs the set of artifacts for which the created artifact is to be the middleman; must
 *        not be null or empty
 * @param middlemanDir the directory in which to place the middleman.
 * @return a middleman that enforces scheduling order (just like a scheduling middleman) and
 *         propagates errors, but is ignored by the dependency checker
 * @throws IllegalArgumentException if {@code inputs} is null or empty
 */
public Artifact createErrorPropagatingMiddleman(ActionOwner owner, String middlemanName, String purpose,
        Iterable<Artifact> inputs, Root middlemanDir) {
    Preconditions.checkArgument(inputs != null);
    Preconditions.checkArgument(!Iterables.isEmpty(inputs));
    // We must always create this middleman even if there is only one input.
    return createMiddleman(owner, middlemanName, purpose, inputs, middlemanDir,
            MiddlemanType.ERROR_PROPAGATING_MIDDLEMAN).getFirst();
}

From source file:org.jboss.as.console.client.administration.accesscontrol.ui.Templates.java

static SafeHtml roleMembers(final Role role, final Iterable<Principal> excludes,
        final Iterable<Principal> includes) {
    SafeHtmlBuilder members = new SafeHtmlBuilder();
    if (role.isIncludeAll()) {
        members.appendHtmlConstant("<p>")
                .appendEscaped("All authenticated users are automatically assigned to this role.")
                .appendHtmlConstant("</p>");

    } else if (Iterables.isEmpty(excludes) && Iterables.isEmpty(includes)) {
        members.appendHtmlConstant("<p>").appendEscaped("No users or groups are assigned to this role.")
                .appendHtmlConstant("</p>");

    } else {/*ww w  .ja v  a  2  s.  c o m*/
        if (!Iterables.isEmpty(excludes)) {
            String names = Joiner.on(", ").join(Iterables.transform(excludes, Principal::getNameAndRealm));
            members.appendHtmlConstant("<p><b>").appendEscaped("Excludes").appendHtmlConstant("</b><br/>")
                    .appendEscaped(names).appendHtmlConstant("</p>");
        }

        if (!Iterables.isEmpty(includes)) {
            String names = Joiner.on(", ").join(Iterables.transform(includes, Principal::getNameAndRealm));
            members.appendHtmlConstant("<p><b>").appendEscaped("Includes").appendHtmlConstant("</b><br/>")
                    .appendEscaped(names).appendHtmlConstant("</p>");
        }
    }
    return members.toSafeHtml();
}

From source file:msi.gaml.descriptions.ModelDescription.java

@Override
public String getDocumentationWithoutMeta() {
    final StringBuilder sb = new StringBuilder(200);
    final String parentName = getParent() == null ? "nil" : getParent().getName();
    if (!parentName.equals(IKeyword.MODEL)) {
        sb.append("<b>Subspecies of:</b> ").append(parentName).append("<br>");
    }//from   ww  w  . j  a  v  a 2 s . c  o m
    final Iterable<String> skills = getSkillsNames();
    if (!Iterables.isEmpty(skills)) {
        sb.append("<b>Skills:</b> ").append(skills).append("<br>");
    }
    sb.append("<br>").append(
            "The following attributes and actions will be accessible using 'world' (in the model) and 'simulation' (in an experiment)")
            .append("<br>");
    sb.append(getAttributeDocumentation());
    sb.append("<br/>");
    sb.append(getActionDocumentation());
    sb.append("<br/>");
    return sb.toString();
}

From source file:org.eclipse.sirius.diagram.sequence.business.internal.operation.SynchronizeInstanceRoleSemanticOrderingOperation.java

private List<EObject> getSemanticInstanceRolesByGraphicalOrder() {
    Iterable<Diagram> diagramViews = Iterables.filter(
            ISequenceElementAccessor.getViewsForSemanticElement(sequenceDiagram, sequenceDiagram.getTarget()),
            Diagram.class);
    if (!Iterables.isEmpty(diagramViews)) {
        Option<SequenceDiagram> seqDiag = ISequenceElementAccessor
                .getSequenceDiagram(diagramViews.iterator().next());
        if (seqDiag.some()) {
            return Lists.newArrayList(Iterables.transform(seqDiag.get().getSortedInstanceRole(),
                    ISequenceElement.SEMANTIC_TARGET));
        }/*from  w  w  w . ja  v a 2 s . com*/
    }
    return Collections.emptyList();
}