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

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

Introduction

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

Prototype

public static <T> boolean all(Iterable<T> iterable, Predicate<? super T> predicate) 

Source Link

Document

Returns true if every element in iterable satisfies the predicate.

Usage

From source file:com.analog.lyric.dimple.solvers.sumproduct.customFactors.MultivariateGaussianFactorBase.java

/**
 * Asserts that factor has only unbounded RealJoint variables.
 * <p>//  w ww  .j  a  v a 2s  . c  om
 * For use in subclass constructors.
 * <p>
 * @throws SolverFactorCreationException if assertion fails.
 * @since 0.08
 */
protected void assertUnboundedRealJoint(Factor factor) {
    if (!Iterables.all(factor.getSiblings(), VariablePredicates.isUnboundedRealJoint())) {
        throw new SolverFactorCreationException(
                "Cannot use %s with %s: not all variables are unbounded RealJoint", getClass().getSimpleName(),
                factor);
    }
}

From source file:org.opennms.netmgt.bsm.service.model.functions.reduce.ExponentialPropagation.java

@Override
public Optional<StatusWithIndices> reduce(List<StatusWithIndex> statuses) {
    // Exit early for no incoming statuses
    if (statuses.isEmpty()) {
        return Optional.empty();
    }//  w w w  .  ja  va 2 s. c  o  m

    // Unfortunately, our computation will result in a normal severity when all input statuses are
    // indeterminate. So, we have to handle this case explicitly here...
    if (Iterables.all(statuses, si -> si.getStatus() == Status.INDETERMINATE)) {
        return Optional.empty();
    }

    // Get the exponential sum of all child states
    final double sum = statuses.stream().filter(si -> si.getStatus().ordinal() >= Status.WARNING.ordinal()) // Ignore normal and indeterminate
            .mapToDouble(si -> Math.pow(this.base, si.getStatus().ordinal() - Status.WARNING.ordinal())) // Offset to warning = n^0
            .sum();

    // Grab the indices from all the statuses that contributed to the sum
    // since these contribute to the cause
    final List<Integer> contributingIndices = statuses.stream()
            .filter(si -> si.getStatus().ordinal() >= Status.WARNING.ordinal()).map(si -> si.getIndex())
            .distinct().sorted().collect(Collectors.toList());

    // Get the log n of the sum
    final int res = (int) Math.floor(Math.log(sum) / Math.log(this.base)) + Status.WARNING.ordinal(); // Revert offset from above

    // Find the resulting status and treat values lower than NORMAL.ordinal() as NORMAL.ordinal() and
    // all values higher than CRITICAL.ordinal() as CRITICAL.ordinal()
    final Status effectiveStatus = Status
            .get(Math.max(Math.min(res, Status.CRITICAL.ordinal()), Status.NORMAL.ordinal()));
    return Optional.of(new StatusWithIndices(effectiveStatus, contributingIndices));
}

From source file:de.cosmocode.palava.ipc.json.rpc.JsonRpc2BatchProtocol.java

@Override
public boolean supports(List<?> request) {
    return Iterables.all(request, supports);
}

From source file:hudson.plugins.emailext.plugins.recipients.CulpritsRecipientProvider.java

@Override
public void addRecipients(final ExtendedEmailPublisherContext context, EnvVars env, Set<InternetAddress> to,
        Set<InternetAddress> cc, Set<InternetAddress> bcc) {
    final class Debug implements RecipientProviderUtilities.IDebug {
        private final ExtendedEmailPublisherDescriptor descriptor = Jenkins.getActiveInstance()
                .getDescriptorByType(ExtendedEmailPublisherDescriptor.class);

        private final PrintStream logger = context.getListener().getLogger();

        public void send(final String format, final Object... args) {
            descriptor.debug(logger, format, args);
        }/* w w  w.  j  a v  a  2 s  . c  o m*/
    }
    final Debug debug = new Debug();
    Run<?, ?> run = context.getRun();

    boolean runHasGetCulprits = false;

    // TODO: core 2.60+, workflow-job 2.12+: Switch to checking if run is RunWithSCM and make catch an else block
    try {
        Method getCulprits = run.getClass().getMethod("getCulprits");
        runHasGetCulprits = true;
        if (Set.class.isAssignableFrom(getCulprits.getReturnType())) {
            @SuppressWarnings("unchecked")
            Set<User> users = (Set<User>) getCulprits.invoke(run);
            if (Iterables.all(users, Predicates.instanceOf(User.class))) {
                RecipientProviderUtilities.addUsers(users, context, env, to, cc, bcc, debug);
            }
        }
    } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
        // Only log a debug message if the exception is not due to an older WorkflowRun without getCulprits...
        if (!(run instanceof WorkflowRun && !runHasGetCulprits)) {
            debug.send("Exception getting culprits for %s: %s", run, e);
        }
        List<Run<?, ?>> builds = new ArrayList<>();
        Run<?, ?> build = run;
        builds.add(build);
        build = build.getPreviousCompletedBuild();
        while (build != null) {
            final Result buildResult = build.getResult();
            if (buildResult != null) {
                if (buildResult.isWorseThan(Result.SUCCESS)) {
                    debug.send("Including build %s with status %s", build.getId(), buildResult);
                    builds.add(build);
                } else {
                    break;
                }
            }
            build = build.getPreviousCompletedBuild();
        }
        Set<User> users = RecipientProviderUtilities.getChangeSetAuthors(builds, debug);
        RecipientProviderUtilities.addUsers(users, context, env, to, cc, bcc, debug);
    }
}

From source file:com.qcadoo.mes.workPlans.hooks.WorkPlansListHooks.java

public void setGridGenerateButtonState(final WorkPlansListView view) {
    List<Entity> selectedWorkPlans = view.getSelectedWorkPlans();
    if (selectedWorkPlans.isEmpty()) {
        view.setUpDeleteButton(false, null);
    } else {// w ww  . j a  v a  2s. co  m
        boolean selectedWorkPlansCanBeDeleted = Iterables.all(selectedWorkPlans, WORK_PLAN_CAN_BE_DELETED);
        String message = getDeleteButtonDescription(selectedWorkPlansCanBeDeleted);
        view.setUpDeleteButton(selectedWorkPlansCanBeDeleted, message);
    }
}

From source file:com.analog.lyric.dimple.solvers.sumproduct.customFactors.CustomGaussianProduct.java

/**
 * Utility to indicate whether or not a factor is compatible with the requirements of this custom factor
 * @deprecated as of release 0.08/*  w w  w  .j ava  2  s . c  o m*/
 */
@Deprecated
public static boolean isFactorCompatible(Factor factor) {
    // Must be of the form form a = b*c where either b or c is a constant.
    if (factor.getSiblingCount() != 2)
        return false;

    // Must have exactly one constant
    if (factor.getConstantCount() != 1)
        return false;

    // Variables must be real and univariate
    if (!Iterables.all(factor.getSiblings(), VariablePredicates.isUnboundedReal()))
        return false;

    // Constant must be non-zero
    double constant = factor.getConstantValues().get(0).getDouble();
    if (constant == 0)
        return false;

    return true;
}

From source file:com.facebook.presto.util.IterableTransformer.java

public boolean all(Predicate<E> predicate) {
    return Iterables.all(iterable, predicate);
}

From source file:gobblin.util.PublisherUtils.java

/**
 * Given a {@link Multimap} of {@link Extract}s to {@link WorkUnitState}s, filter out any {@link Extract}s where all
 * of the corresponding {@link WorkUnitState}s do not meet the given {@link Predicate}.
 * <ul>//from w ww.  ja  v a 2s.co  m
 *  <li> The filtered {@link Extract}s will be available in {@link SplitExtractsResult#getFiltered()}</li>
 *  <li> The {@link Extract}s satisfying the predicated will be available in {@link SplitExtractsResult#getRetained()}</li>
 * </ul>
 *
 */
public static SplitExtractsResult splitExtractsByPredicate(
        Multimap<Extract, WorkUnitState> extractToWorkUnitStateMap, Predicate<WorkUnitState> predicate) {
    Multimap<Extract, WorkUnitState> retained = ArrayListMultimap.create();
    Multimap<Extract, WorkUnitState> filtered = ArrayListMultimap.create();
    for (Map.Entry<Extract, Collection<WorkUnitState>> entry : extractToWorkUnitStateMap.asMap().entrySet()) {
        if (Iterables.all(entry.getValue(), predicate)) {
            retained.putAll(entry.getKey(), entry.getValue());
        } else {
            filtered.putAll(entry.getKey(), entry.getValue());
        }
    }
    return new SplitExtractsResult(retained, filtered);
}

From source file:com.axemblr.provisionr.amazon.activities.AllInstancesMatchPredicate.java

@Override
public void execute(AmazonEC2 client, Pool pool, DelegateExecution execution) throws Exception {
    @SuppressWarnings("unchecked")
    List<String> instanceIds = (List<String>) execution.getVariable(ProcessVariables.INSTANCE_IDS);
    checkNotNull(instanceIds, "process variable '{}' not found", ProcessVariables.INSTANCE_IDS);

    try {/*from  w  w w.  jav a 2 s .  c  o  m*/
        DescribeInstancesResult result = client
                .describeInstances(new DescribeInstancesRequest().withInstanceIds(instanceIds));
        checkState(result.getReservations().size() == 1, "the instance ids are part of multiple reservations");

        List<Instance> instances = result.getReservations().get(0).getInstances();
        if (Iterables.all(instances, predicate)) {
            LOG.info(">> All {} instances match predicate {} ", instanceIds, predicate);
            execution.setVariable(resultVariable, true);

        } else {
            LOG.info("<< Not all instances {} match predicate {}", instanceIds, predicate);
            execution.setVariable(resultVariable, false);
        }
    } catch (AmazonServiceException exception) {
        if (exception.getErrorCode().equalsIgnoreCase("InvalidInstanceID.NotFound")) {
            LOG.warn("<< Got error InvalidInstanceID.NotFound. Assuming predicate {} is false", predicate);
            execution.setVariable(resultVariable, false);
        } else {
            throw Throwables.propagate(exception);
        }
    }
}

From source file:com.google.devtools.build.lib.skyframe.SkylarkModuleCycleReporter.java

@Override
public boolean maybeReportCycle(SkyKey topLevelKey, CycleInfo cycleInfo, boolean alreadyReported,
        EventHandler eventHandler) {
    ImmutableList<SkyKey> pathToCycle = cycleInfo.getPathToCycle();
    ImmutableList<SkyKey> cycle = cycleInfo.getCycle();
    if (pathToCycle.isEmpty()) {
        return false;
    }/*w w  w.  j av  a2  s  . co  m*/
    SkyKey lastPathElement = pathToCycle.get(pathToCycle.size() - 1);
    if (alreadyReported) {
        return true;
    } else if (Iterables.all(cycle, IS_SKYLARK_MODULE_SKY_KEY)
            // The last element before the cycle has to be a PackageFunction or SkylarkModule.
            && (IS_PACKAGE_SKY_KEY.apply(lastPathElement)
                    || IS_SKYLARK_MODULE_SKY_KEY.apply(lastPathElement))) {

        Function printer = new Function<SkyKey, String>() {
            @Override
            public String apply(SkyKey input) {
                if (input.argument() instanceof SkylarkImportLookupValue.SkylarkImportLookupKey) {
                    return ((SkylarkImportLookupValue.SkylarkImportLookupKey) input.argument()).importLabel
                            .toString();
                } else if (input.argument() instanceof PackageIdentifier) {
                    return ((PackageIdentifier) input.argument()) + "/BUILD";
                } else {
                    throw new UnsupportedOperationException();
                }
            }
        };

        StringBuilder cycleMessage = new StringBuilder().append("cycle detected in extension files: ")
                .append("\n    ").append(printer.apply(lastPathElement));

        AbstractLabelCycleReporter.printCycle(cycleInfo.getCycle(), cycleMessage, printer);
        // TODO(bazel-team): it would be nice to pass the Location of the load Statement in the
        // BUILD file.
        eventHandler.handle(Event.error(null, cycleMessage.toString()));
        return true;
    } else if (Iterables.any(cycle, IS_PACKAGE_LOOKUP) && Iterables.any(cycle, IS_WORKSPACE_FILE)
            && (IS_REPOSITORY_DIRECTORY.apply(lastPathElement) || IS_PACKAGE_SKY_KEY.apply(lastPathElement)
                    || IS_EXTERNAL_PACKAGE.apply(lastPathElement))) {
        // We have a cycle in the workspace file, report as such.
        Label fileLabel = (Label) Iterables.getLast(Iterables.filter(cycle, IS_AST_FILE_LOOKUP)).argument();
        String repositoryName = fileLabel.getPackageIdentifier().getRepository().strippedName();
        eventHandler.handle(Event.error(null, "Failed to load Skylark extension '" + fileLabel.toString()
                + "'.\n" + "It usually happens when the repository is not defined prior to being used.\n"
                + "Maybe repository '" + repositoryName + "' was defined later in your WORKSPACE file?"));
        return true;
    }
    return false;
}