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:co.cask.cdap.data2.dataset2.tx.Transactional.java

/**
 * Executes function within new transaction. See {@link Transactional} for more details.
 * @param txFactory transaction factory to create new transaction
 * @param supplier supplier of transaction context
 * @param func function to execute/*from w w w .  j  av a  2  s  .co  m*/
 * @param <V> type of object contained inside the transaction context
 * @param <T> type of the transaction context
 * @param <R> type of the function result
 * @return function result
 */
public static <V, T extends Iterable<V>, R> R execute(TransactionExecutorFactory txFactory,
        Supplier<T> supplier, TransactionExecutor.Function<T, R> func)
        throws TransactionFailureException, IOException, InterruptedException {

    T it = supplier.get();
    Iterable<TransactionAware> txAwares = Iterables.transform(
            Iterables.filter(it, Predicates.instanceOf(TransactionAware.class)),
            new Function<V, TransactionAware>() {
                @Override
                public TransactionAware apply(V input) {
                    return (TransactionAware) input;
                }
            });

    TransactionExecutor executor = txFactory.createExecutor(txAwares);
    try {
        return executor.execute(func, it);
    } finally {
        for (V t : it) {
            if (t instanceof Closeable) {
                ((Closeable) t).close();
            }
        }
    }
}

From source file:org.lenskit.data.history.BasicUserHistory.java

/**
 * {@inheritDoc}// www. j  a  v a  2 s. co  m
 * <p>This implementation filters into a new {@link BasicUserHistory} backed
 * by an {@link ArrayList}.
 */
@SuppressWarnings("unchecked")
@Override
public <T extends Event> UserHistory<T> filter(Class<T> type) {
    // pre-scan the history to see if we need to copy
    if (Iterables.all(this, Predicates.instanceOf(type))) {
        return (UserHistory<T>) this;
    } else {
        List<T> evts = ImmutableList.copyOf(Iterables.filter(this, type));
        return new BasicUserHistory<>(getUserId(), evts);
    }
}

From source file:brooklyn.networking.portforwarding.DockerPortForwarder.java

public void init(Iterable<? extends Location> locations) {
    Optional<? extends Location> jcloudsLoc = Iterables.tryFind(locations,
            Predicates.instanceOf(JcloudsLocation.class));
    String provider = (jcloudsLoc.isPresent()) ? ((JcloudsLocation) jcloudsLoc.get()).getProvider() : null;
    String endpoint = (jcloudsLoc.isPresent()) ? ((JcloudsLocation) jcloudsLoc.get()).getEndpoint() : null;
    String identity = (jcloudsLoc.isPresent()) ? ((JcloudsLocation) jcloudsLoc.get()).getIdentity() : null;
    String credential = (jcloudsLoc.isPresent()) ? ((JcloudsLocation) jcloudsLoc.get()).getCredential() : null;
    if (jcloudsLoc.isPresent() && "docker".equals(provider)) {
        init(URI.create(endpoint), identity, credential);
    } else {/*from  w  w w  . j a v  a  2s  .c  om*/
        throw new IllegalStateException("Cannot infer docker host URI from locations: " + locations);
    }
}

From source file:org.grouplens.lenskit.data.history.BasicUserHistory.java

/**
 * {@inheritDoc}/*from   w w  w .  j  av  a2s. c  o m*/
 * <p>This implementation filters into a new {@link BasicUserHistory} backed
 * by an {@link ArrayList}.
 */
@SuppressWarnings("unchecked")
@Override
public <T extends Event> UserHistory<T> filter(Class<T> type) {
    // pre-scan the history to see if we need to copy
    if (Iterables.all(this, Predicates.instanceOf(type))) {
        return (UserHistory<T>) this;
    } else {
        List<T> evts = ImmutableList.copyOf(Iterables.filter(this, type));
        return new BasicUserHistory<T>(getUserId(), evts);
    }
}

From source file:org.eclipse.sirius.tree.business.internal.migration.description.InitializeCreationToolElementsToSelectExpressionParticipant.java

@Override
protected void postLoad(Group group, Version loadedVersion) {
    if (loadedVersion.compareTo(MIGRATION_VERSION) < 0) {
        EList<Viewpoint> ownedViewpoints = group.getOwnedViewpoints();
        for (Viewpoint viewpoint : ownedViewpoints) {
            boolean atLeastOneChange = false;
            for (TreeDescription treeDescription : Iterables.filter(viewpoint.getOwnedRepresentations(),
                    TreeDescription.class)) {
                Iterator<EObject> creationTools = Iterators.filter(treeDescription.eAllContents(),
                        Predicates.or(//from w w w .j  av  a  2s.c o m
                                Predicates.or(Predicates.instanceOf(TreeItemContainerDropTool.class),
                                        Predicates.instanceOf(TreeItemDragTool.class)),
                                Predicates.instanceOf(TreeItemCreationTool.class)));
                while (creationTools.hasNext()) {
                    AbstractToolDescription tool = (AbstractToolDescription) creationTools.next();
                    if (StringUtil.isEmpty(tool.getElementsToSelect())) {
                        tool.setElementsToSelect(ELEMENTS_TO_SELECT_EXPRESSION);
                        atLeastOneChange = true;
                    }
                }
            }

            if (atLeastOneChange) {
                // Add the Java Extension to use the service:
                if (!Iterables.any(viewpoint.getOwnedJavaExtensions(), new Predicate<JavaExtension>() {
                    @Override
                    public boolean apply(JavaExtension input) {
                        return JAVA_EXTENSION_QUALIFIED_NAME.equals(input.getQualifiedClassName());
                    }
                })) {
                    JavaExtension javaExtension = DescriptionFactory.eINSTANCE.createJavaExtension();
                    javaExtension.setQualifiedClassName(JAVA_EXTENSION_QUALIFIED_NAME);
                    viewpoint.getOwnedJavaExtensions().add(javaExtension);
                }
            }
        }
    }
}

From source file:io.crate.planner.PlanNodeBuilder.java

static CollectNode collect(AbstractDataAnalyzedStatement analysis, List<Symbol> toCollect,
        ImmutableList<Projection> projections, @Nullable String partitionIdent) {
    assert !Iterables.any(toCollect, Predicates.instanceOf(InputColumn.class)) : "cannot collect inputcolumns";
    Routing routing = analysis.table().getRouting(analysis.whereClause());
    if (partitionIdent != null && routing.hasLocations()) {
        routing = filterRouting(routing, PartitionName
                .fromPartitionIdent(analysis.table().ident().name(), partitionIdent).stringValue());
    }// ww w  .  ja va 2  s.co m
    CollectNode node = new CollectNode("collect", routing);
    node.whereClause(analysis.whereClause());
    node.toCollect(toCollect);
    node.maxRowGranularity(analysis.table().rowGranularity());
    node.projections(projections);
    node.isPartitioned(analysis.table().isPartitioned());
    setOutputTypes(node);
    return node;
}

From source file:org.apache.brooklyn.entity.stock.BasicStartableImpl.java

private static Iterable<Entity> filterStartableManagedEntities(Iterable<Entity> contenders) {
    return Iterables.filter(contenders,
            Predicates.and(Predicates.instanceOf(Startable.class), EntityPredicates.isManaged()));
}

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

@Override
protected Integer convertConfigToSensor(PortRange value, Entity entity) {
    if (value == null)
        return null;
    Collection<? extends Location> locations = entity.getLocations();
    if (!locations.isEmpty()) {
        Maybe<? extends Location> lo = Locations.findUniqueMachineLocation(locations);
        if (!lo.isPresent()) {
            // Try a unique location which isn't a machine provisioner
            Iterator<? extends Location> li = Iterables
                    .filter(locations, Predicates.not(Predicates.instanceOf(MachineProvisioningLocation.class)))
                    .iterator();// w w w  .j  a  v a2  s  . com
            if (li.hasNext())
                lo = Maybe.of(li.next());
            if (li.hasNext())
                lo = Maybe.absent();
        }
        // Fall back to selecting the single location
        if (!lo.isPresent() && locations.size() == 1) {
            lo = Maybe.of(locations.iterator().next());
        }
        if (LOG.isTraceEnabled()) {
            LOG.trace("Convert config to sensor for {} found locations: {}. Selected: {}",
                    new Object[] { entity, locations, lo });
        }
        if (lo.isPresent()) {
            Location l = lo.get();
            Optional<Boolean> locationRunning = Optional
                    .fromNullable(l.getConfig(BrooklynConfigKeys.SKIP_ENTITY_START_IF_RUNNING));
            Optional<Boolean> entityRunning = Optional
                    .fromNullable(entity.getConfig(BrooklynConfigKeys.SKIP_ENTITY_START_IF_RUNNING));
            Optional<Boolean> locationInstalled = Optional
                    .fromNullable(l.getConfig(BrooklynConfigKeys.SKIP_ENTITY_INSTALLATION));
            Optional<Boolean> entityInstalled = Optional
                    .fromNullable(entity.getConfig(BrooklynConfigKeys.SKIP_ENTITY_INSTALLATION));
            Optional<Boolean> entityStarted = Optional
                    .fromNullable(entity.getConfig(BrooklynConfigKeys.SKIP_ENTITY_START));
            boolean skipCheck = locationRunning.or(entityRunning).or(locationInstalled).or(entityInstalled)
                    .or(entityStarted).or(false);
            if (l instanceof PortSupplier) {
                int p = ((PortSupplier) l).obtainPort(value);
                if (p != -1) {
                    LOG.debug("{}: choosing port {} for {}", new Object[] { entity, p, getName() });
                    return p;
                }
                // If we are not skipping install or already started, fail now
                if (!skipCheck) {
                    int rangeSize = Iterables.size(value);
                    if (rangeSize == 0) {
                        LOG.warn("{}: no port available for {} (empty range {})",
                                new Object[] { entity, getName(), value });
                    } else if (rangeSize == 1) {
                        Integer pp = value.iterator().next();
                        if (pp > 1024) {
                            LOG.warn("{}: port {} not available for {}",
                                    new Object[] { entity, pp, getName() });
                        } else {
                            LOG.warn("{}: port {} not available for {} (root may be required?)",
                                    new Object[] { entity, pp, getName() });
                        }
                    } else {
                        LOG.warn("{}: no port available for {} (tried range {})",
                                new Object[] { entity, getName(), value });
                    }
                    return null; // Definitively, no ports available
                }
            }
            // Ports may be available, we just can't tell from the location
            Integer v = (value.isEmpty() ? null : value.iterator().next());
            LOG.debug("{}: choosing port {} (unconfirmed) for {}", new Object[] { entity, v, getName() });
            return v;
        } else {
            LOG.warn(
                    "{}: ports not applicable, or not yet applicable, because has multiple locations {}; ignoring ",
                    new Object[] { entity, locations, getName() });
        }
    } else {
        LOG.warn("{}: ports not applicable, or not yet applicable, bacause has no locations; ignoring {}",
                entity, getName());
    }
    return null;
}

From source file:brooklyn.entity.waratek.cloudvm.WaratekApplicationGroupImpl.java

public void update() {
    synchronized (layout) {
        layout.clear();//from  w w  w .j ava  2 s  .  c o  m
        if (getMembers().isEmpty())
            return;
        for (Entity member : getMembers()) {
            if (application.compareAndSet(null, member.getApplication())) {
                setAttribute(WARATEK_APPLICATION, application.get());
            }
            Optional<Location> found = Iterables.tryFind(member.getLocations(),
                    Predicates.instanceOf(WaratekContainerLocation.class));
            if (found.isPresent()) {
                WaratekContainerLocation container = (WaratekContainerLocation) found.get();
                JavaVirtualContainer jvc = container.getOwner();
                JavaVirtualMachine jvm = container.getJavaVirtualMachine();
                layout.put(jvm, jvc);
            }
        }
    }
}

From source file:org.apache.brooklyn.entity.messaging.kafka.KafkaSupport.java

/**
 * Retrieve the next message on the given topic from the {@link KafkaCluster}.
 *///from w w w.  java  2 s .c om
public String getMessage(String topic) {
    ZooKeeperNode zookeeper = cluster.getZooKeeper();
    Optional<Entity> anyBrokerNodeInCluster = Iterables.tryFind(cluster.getCluster().getChildren(),
            Predicates.and(Predicates.instanceOf(KafkaBroker.class),
                    EntityPredicates.attributeEqualTo(KafkaBroker.SERVICE_UP, true)));
    if (anyBrokerNodeInCluster.isPresent()) {
        KafkaBroker broker = (KafkaBroker) anyBrokerNodeInCluster.get();

        Properties props = new Properties();

        props.put("bootstrap.servers",
                format("%s:%d", broker.getAttribute(KafkaBroker.HOSTNAME), broker.getKafkaPort()));
        props.put("zookeeper.connect", format(zookeeper.getHostname(), zookeeper.getZookeeperPort()));
        props.put("group.id", "brooklyn");
        props.put("partition.assignment.strategy", "RoundRobin");
        props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");

        KafkaConsumer consumer = new KafkaConsumer(props);

        consumer.subscribe(topic);
        // FIXME unimplemented KafkaConsumer.poll
        //            Object consumerRecords = consumer.poll(Duration.seconds(3).toMilliseconds()).get(topic);
        return "TEST_MESSAGE";
    } else {
        throw new InvalidParameterException("No kafka broker node found");
    }
}