Example usage for com.google.common.base Predicates and

List of usage examples for com.google.common.base Predicates and

Introduction

In this page you can find the example usage for com.google.common.base Predicates and.

Prototype

public static <T> Predicate<T> and(Predicate<? super T> first, Predicate<? super T> second) 

Source Link

Document

Returns a predicate that evaluates to true if both of its components evaluate to true .

Usage

From source file:com.facebook.litho.testing.viewtree.ViewPredicates.java

public static Predicate<View> hasVisibleDrawable(final Drawable drawable) {
    return Predicates.and(isVisible(), hasDrawable(drawable));
}

From source file:brooklyn.entity.container.docker.DockerInfrastructureImpl.java

@Override
public void init() {
    LOG.info("Starting Docker infrastructure id {}", getId());
    registerLocationResolver();//from w w  w  . j a  v  a  2s. c  o  m
    super.init();

    setAttribute(DOCKER_HOST_COUNTER, new AtomicInteger(0));
    setAttribute(DOCKER_CONTAINER_COUNTER, new AtomicInteger(0));

    int initialSize = config().get(DOCKER_HOST_CLUSTER_MIN_SIZE);
    EntitySpec<?> dockerHostSpec = EntitySpec.create(config().get(DOCKER_HOST_SPEC))
            .configure(DockerHost.DOCKER_INFRASTRUCTURE, this)
            .configure(DockerHost.RUNTIME_FILES,
                    ImmutableMap.of(config().get(DOCKER_CERTIFICATE_PATH), "cert.pem",
                            config().get(DOCKER_KEY_PATH), "key.pem"))
            .configure(SoftwareProcess.CHILDREN_STARTABLE_MODE, ChildStartableMode.BACKGROUND_LATE);
    String dockerVersion = config().get(DOCKER_VERSION);
    if (Strings.isNonBlank(dockerVersion)) {
        dockerHostSpec.configure(SoftwareProcess.SUGGESTED_VERSION, dockerVersion);
    }
    if (Boolean.TRUE.equals(config().get(SdnAttributes.SDN_DEBUG))) {
        dockerHostSpec.configure(DockerAttributes.DOCKERFILE_URL, DockerUtils.UBUNTU_NETWORKING_DOCKERFILE);
    }

    DynamicCluster hosts = addChild(
            EntitySpec.create(DynamicCluster.class).configure(Cluster.INITIAL_SIZE, initialSize)
                    .configure(DynamicCluster.QUARANTINE_FAILED_ENTITIES, true)
                    .configure(DynamicCluster.MEMBER_SPEC, dockerHostSpec)
                    .configure(DynamicCluster.RUNNING_QUORUM_CHECK, QuorumChecks.atLeastOneUnlessEmpty())
                    .configure(DynamicCluster.UP_QUORUM_CHECK, QuorumChecks.atLeastOneUnlessEmpty())
                    .displayName("Docker Hosts"));

    DynamicGroup fabric = addChild(EntitySpec.create(DynamicGroup.class)
            .configure(DynamicGroup.ENTITY_FILTER,
                    Predicates.and(Predicates.instanceOf(DockerContainer.class),
                            EntityPredicates.attributeEqualTo(DockerContainer.DOCKER_INFRASTRUCTURE, this)))
            .configure(DynamicGroup.MEMBER_DELEGATE_CHILDREN, true).displayName("All Docker Containers"));

    DynamicMultiGroup buckets = addChild(EntitySpec.create(DynamicMultiGroup.class)
            .configure(DynamicMultiGroup.ENTITY_FILTER, DockerUtils.sameInfrastructure(this))
            .configure(DynamicMultiGroup.RESCAN_INTERVAL, 15L)
            .configure(DynamicMultiGroup.BUCKET_FUNCTION, new Function<Entity, String>() {
                @Override
                public String apply(@Nullable Entity input) {
                    return input.getApplication().getDisplayName() + ":" + input.getApplicationId();
                }
            })
            .configure(DynamicMultiGroup.BUCKET_SPEC,
                    EntitySpec.create(BasicGroup.class).configure(BasicGroup.MEMBER_DELEGATE_CHILDREN, true))
            .displayName("Docker Applications"));

    if (config().get(SDN_ENABLE) && config().get(SDN_PROVIDER_SPEC) != null) {
        Entity sdn = addChild(EntitySpec.create(config().get(SDN_PROVIDER_SPEC))
                .configure(DockerAttributes.DOCKER_INFRASTRUCTURE, this));
        setAttribute(SDN_PROVIDER, sdn);

        if (Entities.isManaged(this)) {
            Entities.manage(sdn);
        }
    }

    if (Entities.isManaged(this)) {
        Entities.manage(hosts);
        Entities.manage(fabric);
        Entities.manage(buckets);
    }

    setAttribute(DOCKER_HOST_CLUSTER, hosts);
    setAttribute(DOCKER_CONTAINER_FABRIC, fabric);
    setAttribute(DOCKER_APPLICATIONS, buckets);

    hosts.addEnricher(Enrichers.builder().aggregating(DockerHost.CPU_USAGE).computingAverage().fromMembers()
            .publishing(MachineAttributes.AVERAGE_CPU_USAGE).valueToReportIfNoSensors(0d).build());
    hosts.addEnricher(Enrichers.builder().aggregating(DOCKER_CONTAINER_COUNT).computingSum().fromMembers()
            .publishing(DOCKER_CONTAINER_COUNT).build());

    addEnricher(Enrichers.builder().propagating(DOCKER_CONTAINER_COUNT, MachineAttributes.AVERAGE_CPU_USAGE)
            .from(hosts).build());
    addEnricher(Enrichers.builder().propagating(ImmutableMap.of(DynamicCluster.GROUP_SIZE, DOCKER_HOST_COUNT))
            .from(hosts).build());

    Integer headroom = config().get(ContainerHeadroomEnricher.CONTAINER_HEADROOM);
    Double headroomPercent = config().get(ContainerHeadroomEnricher.CONTAINER_HEADROOM_PERCENTAGE);
    if ((headroom != null && headroom > 0) || (headroomPercent != null && headroomPercent > 0d)) {
        addEnricher(EnricherSpec.create(ContainerHeadroomEnricher.class)
                .configure(ContainerHeadroomEnricher.CONTAINER_HEADROOM, headroom)
                .configure(ContainerHeadroomEnricher.CONTAINER_HEADROOM_PERCENTAGE, headroomPercent));
        hosts.addEnricher(Enrichers.builder()
                .propagating(ContainerHeadroomEnricher.DOCKER_CONTAINER_CLUSTER_COLD,
                        ContainerHeadroomEnricher.DOCKER_CONTAINER_CLUSTER_HOT,
                        ContainerHeadroomEnricher.DOCKER_CONTAINER_CLUSTER_OK)
                .from(this).build());
        hosts.addPolicy(PolicySpec.create(AutoScalerPolicy.class)
                .configure(AutoScalerPolicy.POOL_COLD_SENSOR,
                        ContainerHeadroomEnricher.DOCKER_CONTAINER_CLUSTER_COLD)
                .configure(AutoScalerPolicy.POOL_HOT_SENSOR,
                        ContainerHeadroomEnricher.DOCKER_CONTAINER_CLUSTER_HOT)
                .configure(AutoScalerPolicy.POOL_OK_SENSOR,
                        ContainerHeadroomEnricher.DOCKER_CONTAINER_CLUSTER_OK)
                .configure(AutoScalerPolicy.MIN_POOL_SIZE, initialSize)
                .configure(AutoScalerPolicy.RESIZE_UP_STABILIZATION_DELAY, Duration.THIRTY_SECONDS)
                .configure(AutoScalerPolicy.RESIZE_DOWN_STABILIZATION_DELAY, Duration.FIVE_MINUTES));
    }

    setAttribute(Attributes.MAIN_URI, URI.create("/clocker"));
}

From source file:clocker.mesos.entity.MesosClusterImpl.java

@Override
public void init() {
    LOG.info("Starting Mesos cluster id {}", getId());
    registerLocationResolver();// w w w  .  ja  v  a 2s  .co  m
    super.init();

    Group slaves = addChild(EntitySpec.create(BasicGroup.class).displayName("Mesos Slaves"));

    Group frameworks = addChild(EntitySpec.create(BasicGroup.class).displayName("Mesos Frameworks"));

    DynamicGroup tasks = addChild(EntitySpec.create(DynamicGroup.class)
            .configure(DynamicGroup.ENTITY_FILTER,
                    Predicates.and(Predicates.instanceOf(MesosTask.class),
                            EntityPredicates.attributeEqualTo(MesosAttributes.MESOS_CLUSTER, this)))
            .displayName("Mesos Tasks"));

    DynamicMultiGroup applications = addChild(EntitySpec.create(DynamicMultiGroup.class)
            .configure(DynamicMultiGroup.ENTITY_FILTER,
                    Predicates.and(MesosUtils.sameCluster(this),
                            Predicates.not(EntityPredicates.applicationIdEqualTo(getApplicationId()))))
            .configure(DynamicMultiGroup.RESCAN_INTERVAL, 15L)
            .configure(DynamicMultiGroup.BUCKET_FUNCTION, new Function<Entity, String>() {
                @Override
                public String apply(@Nullable Entity input) {
                    return input.getApplication().getDisplayName() + ":" + input.getApplicationId();
                }
            }).configure(DynamicMultiGroup.BUCKET_SPEC, EntitySpec.create(BasicGroup.class))
            .displayName("Mesos Applications"));

    if (config().get(SDN_ENABLE) && config().get(SDN_PROVIDER_SPEC) != null) {
        EntitySpec entitySpec = EntitySpec.create(config().get(SDN_PROVIDER_SPEC));
        entitySpec.configure(MesosAttributes.MESOS_CLUSTER, this);
        Entity sdn = addChild(entitySpec);
        sensors().set(SDN_PROVIDER, sdn);
    }

    sensors().set(MESOS_SLAVES, slaves);
    sensors().set(MESOS_FRAMEWORKS, frameworks);
    sensors().set(MESOS_TASKS, tasks);
    sensors().set(MESOS_APPLICATIONS, applications);

    // Override the health-check: just interested in the slaves, frameworks and sdn (rather than 
    // the groups that show the tasks or apps).
    Entity sdn = sensors().get(SDN_PROVIDER);
    enrichers().add(EnricherSpec.create(ComputeServiceIndicatorsFromChildrenAndMembers.class)
            .uniqueTag(ComputeServiceIndicatorsFromChildrenAndMembers.DEFAULT_UNIQUE_TAG)
            .configure(ComputeServiceIndicatorsFromChildrenAndMembers.FROM_CHILDREN, true)
            .configure(ComputeServiceIndicatorsFromChildrenAndMembers.ENTITY_FILTER,
                    Predicates.or(ImmutableList.of(Predicates.<Entity>equalTo(slaves),
                            Predicates.<Entity>equalTo(frameworks),
                            (sdn == null ? Predicates.<Entity>alwaysFalse() : Predicates.equalTo(sdn))))));
}

From source file:com.vmware.appfactory.notification.controller.NotificationApiController.java

/**
 * Get a consolidated status of all conversison's progress and a list of
 * alert actions./* w  w  w .ja v  a2 s. c  om*/
 *
 * @return
 */
@RequestMapping(value = "/notify/alertAndProgress", method = RequestMethod.GET)
public @ResponseBody CaptureTaskSummary getCaptureAndAlertSummary() {
    long progressTotal = 0;
    int taskCount = 0;
    Iterable<TaskState> taskList = _conversionsQueue.getTasks(MetaStatusPredicate.NOT_FINISHED);
    Iterable<TaskState> captureStates = Iterables.filter(taskList,
            Predicates.instanceOf(AbstractCaptureState.class));
    for (TaskState state : captureStates) {
        progressTotal += state.getProgress();
        taskCount++;
    }
    Iterable<TaskState> runningTasks = Iterables.filter(taskList,
            Predicates.and(MetaStatusPredicate.RUNNING, Predicates.instanceOf(AbstractCaptureState.class)));

    // Compute the average progress
    if (taskCount != 0) {
        progressTotal /= taskCount;
    }

    // Create the dto and set the computed values and queued up capture tasks
    CaptureTaskSummary summary = new CaptureTaskSummary(Iterables.size(runningTasks), (int) progressTotal,
            getWaitingCaptureTaskCount());

    // Set the number of failed and wait-on-user alerts.
    List<ActionAlert> aaList = getWorkpoolAndImageFailedAlerts();
    aaList.addAll(getUserWaitAndFailedAlerts());
    aaList.addAll(getFeedFailedAlerts());
    aaList.addAll(getLowDiskSpaceAlerts());

    // Add the list of action alerts with the latest alert event appearing on top.
    Collections.sort(aaList);
    summary.setActionList(aaList);

    // Return the summary info for display.
    return summary;
}

From source file:brooklyn.entity.nosql.etcd.EtcdClusterImpl.java

protected void onServerPoolMemberChanged(Entity member) {
    synchronized (mutex) {
        log.debug("For {}, considering membership of {} which is in locations {}",
                new Object[] { this, member, member.getLocations() });

        Map<Entity, String> nodes = getAttribute(ETCD_CLUSTER_NODES);
        if (belongsInServerPool(member)) {
            if (nodes == null) {
                nodes = Maps.newLinkedHashMap();
            }/* w ww.  j  a v  a2s.c  om*/
            String name = Preconditions.checkNotNull(getNodeName(member));

            // Wait until node has been installed
            DynamicTasks
                    .queueIfPossible(
                            DependentConfiguration.attributeWhenReady(member, EtcdNode.ETCD_NODE_INSTALLED))
                    .orSubmitAndBlock(this).andWaitForSuccess();

            // Check for first node in the cluster.
            Entity firstNode = getAttribute(DynamicCluster.FIRST);
            if (member.equals(firstNode)) {
                nodes.put(member, name);
                recalculateClusterAddresses(nodes);
                log.info("Adding first node {}: {}; {} to cluster", new Object[] { this, member, name });
                ((EntityInternal) member).setAttribute(EtcdNode.ETCD_NODE_HAS_JOINED_CLUSTER, Boolean.TRUE);
            } else {
                int retry = 3; // TODO use a configurable Repeater instead?
                while (retry-- > 0 && member.getAttribute(EtcdNode.ETCD_NODE_HAS_JOINED_CLUSTER) == null
                        && !nodes.containsKey(member)) {
                    Optional<Entity> anyNodeInCluster = Iterables.tryFind(nodes.keySet(),
                            Predicates.and(Predicates.instanceOf(EtcdNode.class), EntityPredicates
                                    .attributeEqualTo(EtcdNode.ETCD_NODE_HAS_JOINED_CLUSTER, Boolean.TRUE)));
                    if (anyNodeInCluster.isPresent()) {
                        DynamicTasks
                                .queueIfPossible(DependentConfiguration
                                        .attributeWhenReady(anyNodeInCluster.get(), Startable.SERVICE_UP))
                                .orSubmitAndBlock(this).andWaitForSuccess();
                        Entities.invokeEffectorWithArgs(this, anyNodeInCluster.get(),
                                EtcdNode.JOIN_ETCD_CLUSTER, name, getNodeAddress(member)).blockUntilEnded();
                        nodes.put(member, name);
                        recalculateClusterAddresses(nodes);
                        log.info("Adding node {}: {}; {} to cluster", new Object[] { this, member, name });
                        ((EntityInternal) member).setAttribute(EtcdNode.ETCD_NODE_HAS_JOINED_CLUSTER,
                                Boolean.TRUE);
                    } else {
                        log.info("Waiting for first node in cluster {}", this);
                        Time.sleep(Duration.seconds(15));
                    }
                }
            }
        } else {
            if (nodes != null && nodes.containsKey(member)) {
                Optional<Entity> anyNodeInCluster = Iterables.tryFind(nodes.keySet(),
                        Predicates.and(
                                Predicates.instanceOf(EtcdNode.class), EntityPredicates
                                        .attributeEqualTo(EtcdNode.ETCD_NODE_HAS_JOINED_CLUSTER, Boolean.TRUE),
                                Predicates.not(Predicates.equalTo(member))));
                if (anyNodeInCluster.isPresent()) {
                    Entities.invokeEffectorWithArgs(this, anyNodeInCluster.get(), EtcdNode.LEAVE_ETCD_CLUSTER,
                            getNodeName(member)).blockUntilEnded();
                }
                nodes.remove(member);
                recalculateClusterAddresses(nodes);
                log.info("Removing node {}: {}; {} from cluster",
                        new Object[] { this, member, getNodeName(member) });
                ((EntityInternal) member).setAttribute(EtcdNode.ETCD_NODE_HAS_JOINED_CLUSTER, Boolean.FALSE);
            }
        }

        ServiceNotUpLogic.updateNotUpIndicatorRequiringNonEmptyMap(this, ETCD_CLUSTER_NODES);
        log.debug("Done {} checkEntity {}", this, member);
    }
}

From source file:com.facebook.litho.testing.viewtree.ViewPredicates.java

/** @return A Predicate which is true if the view is visible and has the given id. */
public static Predicate<View> hasVisibleId(final int viewId) {
    return Predicates.and(isVisible(), hasId(viewId));
}

From source file:com.twitter.aurora.GuiceUtils.java

/**
 * Binds an exception trap on all interface methods of all classes bound against an interface.
 * Individual methods may opt out of trapping by annotating with {@link AllowUnchecked}.
 * Only void methods are allowed, any non-void interface methods must explicitly opt out.
 *
 * @param binder The binder to register an interceptor with.
 * @param wrapInterface Interface whose methods should be wrapped.
 * @throws IllegalArgumentException If any of the non-whitelisted interface methods are non-void.
 *///from  w  w w. j  ava  2 s. c o m
public static void bindExceptionTrap(Binder binder, Class<?> wrapInterface) throws IllegalArgumentException {

    Set<Method> disallowed = ImmutableSet
            .copyOf(Iterables.filter(ImmutableList.copyOf(wrapInterface.getMethods()),
                    Predicates.and(Predicates.not(IS_WHITELISTED), Predicates.not(VOID_METHOD))));
    Preconditions.checkArgument(disallowed.isEmpty(),
            "Non-void methods must be explicitly whitelisted with @AllowUnchecked: " + disallowed);

    Matcher<Method> matcher = Matchers.<Method>not(WHITELIST_MATCHER)
            .and(interfaceMatcher(wrapInterface, false));
    binder.bindInterceptor(Matchers.subclassesOf(wrapInterface), matcher, new MethodInterceptor() {
        @Override
        public Object invoke(MethodInvocation invocation) throws Throwable {
            try {
                return invocation.proceed();
            } catch (RuntimeException e) {
                LOG.log(Level.WARNING, "Trapped uncaught exception: " + e, e);
                return null;
            }
        }
    });
}

From source file:forge.quest.BoosterUtils.java

private static void populateRandomFilters(final List<Predicate<CardRules>> colorFilters) {

    for (int i = 0; i < MAX_BIAS; i++) {
        Predicate<CardRules> predicate;
        byte color = possibleColors.get((int) (Math.random() * 6));
        if (Math.random() < 0.6) {
            predicate = CardRulesPredicates.isMonoColor(color);
        } else {/*ww  w.j a v a2 s.  c  o m*/
            predicate = CardRulesPredicates.hasColor(color);
        }
        if (Math.random() < 0.1) {
            predicate = Predicates.and(predicate, CardRulesPredicates.Presets.IS_MULTICOLOR);
        }
        colorFilters.add(predicate);
    }

}

From source file:org.dasein.cloud.jclouds.vcloud.director.compute.VAppTemplateSupport.java

@Override
public @Nullable MachineImage getMachineImage(@Nonnull String machineImageId)
        throws CloudException, InternalException {
    RestContext<VCloudDirectorAdminClient, VCloudDirectorAdminAsyncClient> ctx = provider.getCloudClient();

    try {//from w  ww .ja v  a 2  s  . com
        try {
            VAppTemplate template = ctx.getApi().getVAppTemplateClient()
                    .getVAppTemplate(provider.toHref(ctx, machineImageId));

            if (template == null) {
                return null;
            }
            URI vdcURI = Iterables
                    .find(template.getLinks(), Predicates.and(LinkPredicates.relEquals(Link.Rel.UP),
                            LinkPredicates.typeEquals(VCloudDirectorMediaType.VDC)))
                    .getHref();
            Vdc vdc = ctx.getApi().getVdcClient().getVdc(vdcURI);
            URI orgURI = Iterables.find(vdc.getLinks(), Predicates.and(LinkPredicates.relEquals(Link.Rel.UP),
                    LinkPredicates.typeEquals(VCloudDirectorMediaType.VDC))).getHref();
            AdminOrg org = ctx.getApi().getOrgClient().getOrg(orgURI);

            return toMachineImage(ctx, org, template);
        } catch (AuthorizationException e) {
            return null;
        } catch (RuntimeException e) {
            logger.error("Error looking up machine image " + machineImageId + ": " + e.getMessage());
            if (logger.isDebugEnabled()) {
                e.printStackTrace();
            }
            throw new CloudException(e);
        }
    } finally {
        ctx.close();
    }
}

From source file:org.eclipse.sirius.diagram.sequence.business.internal.util.ParentOperandFinder.java

/**
 * Finds the deepest Operand container convering the range if existing.
 * //from   ww w.j  a  v a 2s .  c o m
 * @param verticalRange
 *            the range where to look for the deepest operand
 * @return the deepest Operand convering this lifeline at this range
 * @see ISequenceEvent#getParentOperand()
 */
public Option<Operand> getParentOperand(final Range verticalRange) {
    SequenceDiagram diagram = event.getDiagram();
    Set<Operand> allOperands = diagram.getAllOperands();
    // Map to store the result of the covered lifelines of a
    // CombinedFragment to avoid to make this call for each Operand of the
    // same CombinedFragment.
    final Map<CombinedFragment, Collection<Lifeline>> combinedFragmentToCoveredLifelines = Maps.newHashMap();

    Predicate<Operand> coveredLifeline = new Predicate<Operand>() {
        // Filter the operands that cover the execution parent lifeline
        public boolean apply(Operand input) {
            CombinedFragment parentCombinedFragment = input.getCombinedFragment();
            Collection<Lifeline> computeCoveredLifelines = combinedFragmentToCoveredLifelines
                    .get(parentCombinedFragment);
            if (computeCoveredLifelines == null) {
                computeCoveredLifelines = parentCombinedFragment.computeCoveredLifelines();
                combinedFragmentToCoveredLifelines.put(parentCombinedFragment, computeCoveredLifelines);
            }
            return computeCoveredLifelines != null
                    && computeCoveredLifelines.contains(event.getLifeline().get());
        }
    };

    Predicate<Operand> includingExecutionRange = new Predicate<Operand>() {
        // Filter the operands having a range that contains the execution
        // range (we consider the insertion point : lowerbound of range)
        public boolean apply(Operand input) {
            return rangeFunction.apply(input)
                    .includes(new Range(verticalRange.getLowerBound(), verticalRange.getLowerBound()));
            // return rangeFunction.apply(input).includes(verticalRange);
        }
    };

    Operand deepestCoveringOperand = null;
    for (Operand operand : Iterables.filter(allOperands,
            Predicates.and(includingExecutionRange, coveredLifeline))) {
        // Find the deepest operand among the filtered ones
        if (deepestCoveringOperand == null
                || rangeFunction.apply(deepestCoveringOperand).includes(rangeFunction.apply(operand))) {
            deepestCoveringOperand = operand;
        }
    }
    if (deepestCoveringOperand != null) {
        return Options.newSome(deepestCoveringOperand);
    } else {
        return Options.newNone();
    }
}