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

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

Introduction

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

Prototype

@GwtIncompatible("Class.isInstance")
public static Predicate<Object> instanceOf(Class<?> clazz) 

Source Link

Document

Returns a predicate that evaluates to true if the object being tested is an instance of the given class.

Usage

From source file:com.cloudera.impala.analysis.QueryStmt.java

/**
 * Creates sortInfo by resolving aliases and ordinals in the orderingExprs.
 * If the query stmt is an inline view/union operand, then order-by with no
 * limit with offset is not allowed, since that requires a sort and merging-exchange,
 * and subsequent query execution would occur on a single machine.
 * Sets evaluateOrderBy_ to false for ignored order-by w/o limit/offset in nested
 * queries./*from  w  ww. ja  v  a2 s.  c om*/
 */
protected void createSortInfo(Analyzer analyzer) throws AnalysisException {
    // not computing order by
    if (orderByElements_ == null) {
        evaluateOrderBy_ = false;
        return;
    }

    ArrayList<Expr> orderingExprs = Lists.newArrayList();
    ArrayList<Boolean> isAscOrder = Lists.newArrayList();
    ArrayList<Boolean> nullsFirstParams = Lists.newArrayList();

    // extract exprs
    for (OrderByElement orderByElement : orderByElements_) {
        if (orderByElement.getExpr().contains(Predicates.instanceOf(Subquery.class))) {
            throw new AnalysisException("Subqueries are not supported in the ORDER BY clause.");
        }
        // create copies, we don't want to modify the original parse node, in case
        // we need to print it
        orderingExprs.add(orderByElement.getExpr().clone());
        isAscOrder.add(Boolean.valueOf(orderByElement.isAsc()));
        nullsFirstParams.add(orderByElement.getNullsFirstParam());
    }
    substituteOrdinals(orderingExprs, "ORDER BY", analyzer);
    Expr ambiguousAlias = getFirstAmbiguousAlias(orderingExprs);
    if (ambiguousAlias != null) {
        throw new AnalysisException("Column '" + ambiguousAlias.toSql() + "' in ORDER BY clause is ambiguous");
    }
    orderingExprs = Expr.trySubstituteList(orderingExprs, aliasSmap_, analyzer, false);

    if (!analyzer.isRootAnalyzer() && hasOffset() && !hasLimit()) {
        throw new AnalysisException("Order-by with offset without limit not supported" + " in nested queries.");
    }

    sortInfo_ = new SortInfo(orderingExprs, isAscOrder, nullsFirstParams);
    // order by w/o limit and offset in inline views, union operands and insert statements
    // are ignored.
    if (!hasLimit() && !hasOffset() && !analyzer.isRootAnalyzer()) {
        evaluateOrderBy_ = false;
        // Return a warning that the order by was ignored.
        StringBuilder strBuilder = new StringBuilder();
        strBuilder.append("Ignoring ORDER BY clause without LIMIT or OFFSET: ");
        strBuilder.append("ORDER BY ");
        strBuilder.append(orderByElements_.get(0).toSql());
        for (int i = 1; i < orderByElements_.size(); ++i) {
            strBuilder.append(", ").append(orderByElements_.get(i).toSql());
        }
        strBuilder.append(".\nAn ORDER BY without a LIMIT or OFFSET appearing in ");
        strBuilder.append("an (inline) view, union operand or an INSERT/CTAS statement ");
        strBuilder.append("has no effect on the query result.");
        analyzer.addWarning(strBuilder.toString());
    } else {
        evaluateOrderBy_ = true;
    }
}

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  .  ja  va  2  s .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:org.openengsb.core.test.UserManagerStub.java

@SuppressWarnings("unchecked")
@Override//from   w  ww  .  ja  v a  2 s .c o m
public <T extends Permission> Collection<T> getAllPermissionsForUser(String username, Class<T> type)
        throws UserNotFoundException {
    return (Collection<T>) Collections2.filter(getAllPermissionsForUser(username), Predicates.instanceOf(type));
}

From source file:org.eclipse.sirius.diagram.business.api.query.DDiagramElementQuery.java

/**
 * Check if the label of this {@link DDiagramElement} is directly hidden.
 * /*from  w ww  .  ja va 2  s.c  o m*/
 * @return true if the label of the given element is hidden.
 */
public boolean isLabelHidden() {
    return Iterables.any(element.getGraphicalFilters(), Predicates.instanceOf(HideLabelFilter.class));
}

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

@Override
public void init() {
    LOG.info("Starting Mesos cluster id {}", getId());
    registerLocationResolver();// w ww  .j  a  v a 2s  .  c  om
    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:org.apache.brooklyn.launcher.AbstractBrooklynLauncherRebindTestFixture.java

protected void assertOnlyApp(ManagementContext managementContext, Class<? extends Application> expectedType) {
    assertEquals(managementContext.getApplications().size(), 1, "apps=" + managementContext.getApplications());
    assertNotNull(Iterables.find(managementContext.getApplications(),
            Predicates.instanceOf(TestApplication.class), null), "apps=" + managementContext.getApplications());
}

From source file:vazkii.botania.common.entity.EntityCorporeaSpark.java

private List<ICorporeaSpark> getNearbySparks() {
    List ret = worldObj.getEntitiesWithinAABB(
            Entity.class, new AxisAlignedBB(posX - SCAN_RANGE, posY - SCAN_RANGE, posZ - SCAN_RANGE,
                    posX + SCAN_RANGE, posY + SCAN_RANGE, posZ + SCAN_RANGE),
            Predicates.instanceOf(ICorporeaSpark.class));
    return ret;/*from ww  w  .j  a  v  a  2 s .  c o m*/
}

From source file:org.eclipselabs.agrum.services.model.plugin.parser.ModelParser.java

/**
 * To get an iterator on each outgoing transition of a state, which possessed a tick event as trigger
 * @param s - the state// ww  w .j a  v a2 s . co m
 * @return the iterator
 */
private static Iterator<Transition> completionTransitionIterator(State s) {
    Predicate<Object> allTransitions = Predicates.instanceOf(Transition.class);
    Iterator<Transition> transitions = Iterators.filter(s.getOutgoings().listIterator(), allTransitions);

    transitions = Iterators.filter(transitions, new com.google.common.base.Predicate<Transition>() {

        @Override
        public boolean apply(Transition arg0) {
            if (arg0.getTriggers().isEmpty())
                return true;
            return false;
        }
    });
    return transitions;
}

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();
            }/*from ww  w . j  av a  2s.  co m*/
            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:org.opendaylight.yangtools.yang.parser.stmt.rfc6020.effective.EffectiveStatementBase.java

protected final EffectiveStatement<?, ?> firstEffectiveSubstatementOfType(final Class<?> type) {
    return Iterables.tryFind(substatements, Predicates.instanceOf(type)).orNull();
}