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:eu.stratosphere.sopremo.expressions.ExpressionUtil.java

public static EvaluationExpression replaceArrayProjections(final EvaluationExpression evaluationExpression) {
    return evaluationExpression.clone().remove(InputSelection.class)
            .replace(Predicates.instanceOf(ArrayProjection.class), new TransformFunction() {
                @Override/*from  w  ww  . jav  a  2 s.c o m*/
                public EvaluationExpression apply(final EvaluationExpression argument) {
                    final ArrayProjection arrayProjection = (ArrayProjection) argument;
                    final EvaluationExpression projection = arrayProjection.getProjection();
                    return new ChainedSegmentExpression(arrayProjection.getInputExpression(), projection);
                }
            }).simplify();
}

From source file:org.apache.impala.planner.PlanFragment.java

/**
 * Finalize plan tree and create stream sink, if needed.
 * If this fragment is hash partitioned, ensures that the corresponding partition
 * exprs of all hash-partitioning senders are cast to identical types.
 * Otherwise, the hashes generated for identical partition values may differ
 * among senders if the partition-expr types are not identical.
 *//*from w ww . j  av  a  2 s.  co m*/
public void finalize(Analyzer analyzer) throws InternalException, NotImplementedException {
    if (destNode_ != null) {
        Preconditions.checkState(sink_ == null);
        // we're streaming to an exchange node
        DataStreamSink streamSink = new DataStreamSink(destNode_, outputPartition_);
        streamSink.setFragment(this);
        sink_ = streamSink;
    }

    if (!dataPartition_.isHashPartitioned())
        return;

    // This fragment is hash partitioned. Gather all exchange nodes and ensure
    // that all hash-partitioning senders hash on exprs-values of the same type.
    List<ExchangeNode> exchNodes = Lists.newArrayList();
    planRoot_.collect(Predicates.instanceOf(ExchangeNode.class), exchNodes);

    // Contains partition-expr lists of all hash-partitioning sender fragments.
    List<List<Expr>> senderPartitionExprs = Lists.newArrayList();
    for (ExchangeNode exchNode : exchNodes) {
        Preconditions.checkState(!exchNode.getChildren().isEmpty());
        PlanFragment senderFragment = exchNode.getChild(0).getFragment();
        Preconditions.checkNotNull(senderFragment);
        if (!senderFragment.getOutputPartition().isHashPartitioned())
            continue;
        List<Expr> partExprs = senderFragment.getOutputPartition().getPartitionExprs();
        // All hash-partitioning senders must have compatible partition exprs, otherwise
        // this fragment's data partition must not be hash partitioned.
        Preconditions.checkState(partExprs.size() == dataPartition_.getPartitionExprs().size());
        senderPartitionExprs.add(partExprs);
    }

    // Cast all corresponding hash partition exprs of all hash-partitioning senders
    // to their compatible types. Also cast the data partition's exprs for consistency,
    // although not strictly necessary. They should already be type identical to the
    // exprs of one of the senders and they are not directly used for hashing in the BE.
    senderPartitionExprs.add(dataPartition_.getPartitionExprs());
    try {
        analyzer.castToUnionCompatibleTypes(senderPartitionExprs);
    } catch (AnalysisException e) {
        // Should never happen. Analysis should have ensured type compatibility already.
        throw new IllegalStateException(e);
    }
}

From source file:org.apache.brooklyn.util.text.StringPredicates.java

/** true if the object *is* a {@link CharSequence} starting with the given prefix */
public static Predicate<Object> isStringStartingWith(final String prefix) {
    return Predicates.<Object>and(Predicates.instanceOf(CharSequence.class),
            Predicates.compose(startsWith(prefix), StringFunctions.toStringFunction()));
}

From source file:org.sosy_lab.cpachecker.cpa.predicate.PredicateAbstractionGlobalRefinementStrategy.java

protected void updateARG(PredicatePrecision pNewPrecision, ARGState pRefinementRoot)
        throws InterruptedException {

    argUpdate.start();//ww w  .  ja  v  a2  s .  com

    List<Precision> precisions = new ArrayList<>(2);
    List<Predicate<? super Precision>> precisionTypes = new ArrayList<>(2);

    precisions.add(pNewPrecision);
    precisionTypes.add(Predicates.instanceOf(PredicatePrecision.class));

    UnmodifiableReachedSet unmodifiableReached = reached.asReachedSet();

    if (isValuePrecisionAvailable(pRefinementRoot)) {
        precisions.add(mergeAllValuePrecisionsFromSubgraph(pRefinementRoot, unmodifiableReached));
        precisionTypes.add(VariableTrackingPrecision.isMatchingCPAClass(ValueAnalysisCPA.class));
    }

    reached.removeSubtree(pRefinementRoot, precisions, precisionTypes);

    if (sharePredicates) {
        reached.updatePrecisionGlobally(pNewPrecision, Predicates.instanceOf(PredicatePrecision.class));
    }

    argUpdate.stop();
}

From source file:brooklyn.entity.cloud.CloudEnvironmentImpl.java

@Override
public void start(Collection<? extends Location> locations) {
    Optional<? extends Location> location = Optional.absent();
    if (Iterables.size(locations) > 0) {
        location = Iterables.tryFind(locations, Predicates.instanceOf(MachineProvisioningLocation.class));
    }//from  w  w  w. j  a va  2s  .  c o m
    Location provisioner;
    if (!location.isPresent() || location.get() instanceof LocalhostMachineProvisioningLocation) {
        LocationSpec<?> spec = getConfig(CLOUD_LOCATION_SPEC);
        provisioner = getManagementContext().getLocationManager().createLocation(spec);
    } else {
        provisioner = location.get();
    }
    log.info("Creating new CloudLocation wrapping {}", provisioner);

    Map<String, ?> flags = MutableMap.<String, Object>builder().putAll(getConfig(LOCATION_FLAGS))
            .put("provisioner", provisioner).build();
    createLocation(flags);

    super.start(locations);
}

From source file:org.eclipse.sirius.diagram.sequence.business.internal.query.SequenceDiagramQuery.java

/**
 * Get all {@link ISequenceEvent} of the current {@link SequenceDiagram} of
 * the specified {@link Lifeline}./*from  w  ww.  j  a  v a2 s  .com*/
 * 
 * @param lifeline
 *            the specified {@link Lifeline}
 * 
 * @return the set of {@link ISequenceEvent} of the current
 *         {@link SequenceDiagram} of the specified {@link Lifeline}, sorted
 *         by range from lower to upper
 */
public Set<ISequenceEvent> getAllSequenceEventsOnLifeline(Lifeline lifeline) {
    Set<ISequenceEvent> allSequenceEventsOnLifeline = new TreeSet<ISequenceEvent>(new RangeComparator());
    for (ISequenceEvent sequenceEvent : Iterables.filter(getAllSequenceEvents(),
            Predicates.not(Predicates.instanceOf(Lifeline.class)))) {
        Option<Lifeline> lifelineOfSequenceEventOption = sequenceEvent.getLifeline();
        if (lifelineOfSequenceEventOption.some() && lifelineOfSequenceEventOption.get().equals(lifeline)) {
            allSequenceEventsOnLifeline.add(sequenceEvent);
        } else if (!lifelineOfSequenceEventOption.some()) {
            if (sequenceEvent instanceof Message) {
                Message message = (Message) sequenceEvent;
                Option<Lifeline> sourceLifelineOption = message.getSourceLifeline();
                Option<Lifeline> targetLifelineOption = message.getTargetLifeline();
                if (sourceLifelineOption.some() && sourceLifelineOption.get().equals(lifeline)) {
                    allSequenceEventsOnLifeline.add(message);
                } else if (targetLifelineOption.some() && targetLifelineOption.get().equals(lifeline)) {
                    allSequenceEventsOnLifeline.add(message);
                }
            } else if (sequenceEvent instanceof AbstractFrame) {
                AbstractFrame abstractFrame = (AbstractFrame) sequenceEvent;
                Collection<Lifeline> coveredLifelines = abstractFrame.computeCoveredLifelines();
                if (coveredLifelines.contains(lifeline)) {
                    allSequenceEventsOnLifeline.add(abstractFrame);
                }
            }
        }
    }
    return allSequenceEventsOnLifeline;
}

From source file:vazkii.botania.common.block.tile.TileTerraPlate.java

@Override
public ISparkEntity getAttachedSpark() {
    List<Entity> sparks = worldObj.getEntitiesWithinAABB(Entity.class,
            new AxisAlignedBB(pos.up(), pos.up().add(1, 1, 1)), Predicates.instanceOf(ISparkEntity.class));
    if (sparks.size() == 1) {
        Entity e = sparks.get(0);
        return (ISparkEntity) e;
    }//from   w w w.ja v  a2 s .com

    return null;
}

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

@Override
public void analyze(Analyzer analyzer) throws AnalysisException {
    if (isAnalyzed_)
        return;/*w  ww. ja  va  2s . c o  m*/
    super.analyze(analyzer);

    convertNumericLiteralsFromDecimal(analyzer);
    String opName = op_.getName().equals("null_matching_eq") ? "eq" : op_.getName();
    fn_ = getBuiltinFunction(analyzer, opName, collectChildReturnTypes(), CompareMode.IS_SUPERTYPE_OF);
    if (fn_ == null) {
        // Construct an appropriate error message and throw an AnalysisException.
        String errMsg = "operands of type " + getChild(0).getType().toSql() + " and "
                + getChild(1).getType().toSql() + " are not comparable: " + toSql();

        // Check if any of the children is a Subquery that does not return a
        // scalar.
        for (Expr expr : children_) {
            if (expr instanceof Subquery && !expr.getType().isScalarType()) {
                errMsg = "Subquery must return a single row: " + expr.toSql();
                break;
            }
        }

        throw new AnalysisException(errMsg);
    }
    Preconditions.checkState(fn_.getReturnType().isBoolean());

    ArrayList<Expr> subqueries = Lists.newArrayList();
    collectAll(Predicates.instanceOf(Subquery.class), subqueries);
    if (subqueries.size() > 1) {
        // TODO Remove that restriction when we add support for independent subquery
        // evaluation.
        throw new AnalysisException(
                "Multiple subqueries are not supported in binary " + "predicates: " + toSql());
    }
    if (contains(InPredicate.class) || contains(ExistsPredicate.class)) {
        throw new AnalysisException(
                "IN and/or EXISTS subquery predicates are not " + "supported in binary predicates: " + toSql());
    }

    // Don't perform any casting for predicates with subqueries here. Any casting
    // required will be performed when the subquery is unnested.
    if (!contains(Subquery.class))
        castForFunctionCall(true);

    // determine selectivity
    // TODO: Compute selectivity for nested predicates
    Reference<SlotRef> slotRefRef = new Reference<SlotRef>();
    if (op_ == Operator.EQ && isSingleColumnPredicate(slotRefRef, null)
            && slotRefRef.getRef().getNumDistinctValues() > 0) {
        Preconditions.checkState(slotRefRef.getRef() != null);
        selectivity_ = 1.0 / slotRefRef.getRef().getNumDistinctValues();
        selectivity_ = Math.max(0, Math.min(1, selectivity_));
    } else {
        // TODO: improve using histograms, once they show up
        selectivity_ = Expr.DEFAULT_SELECTIVITY;
    }
}

From source file:brooklyn.entity.group.DynamicFabricImpl.java

@Override
public void stop() {
    ServiceStateLogic.setExpectedState(this, Lifecycle.STOPPING);
    try {/*from  w  w  w .j  a  v a 2s  .  co  m*/
        Iterable<Entity> stoppableChildren = Iterables.filter(getChildren(),
                Predicates.instanceOf(Startable.class));
        Task<?> invoke = Entities.invokeEffector(this, stoppableChildren, Startable.STOP);
        if (invoke != null)
            invoke.get();
        ServiceStateLogic.setExpectedState(this, Lifecycle.STOPPED);
        setAttribute(SERVICE_UP, false);
    } catch (Exception e) {
        ServiceStateLogic.setExpectedState(this, Lifecycle.ON_FIRE);
        throw Exceptions.propagate(e);
    }
}

From source file:org.eclipse.sirius.diagram.sequence.ui.tool.internal.util.RequestQuery.java

/**
 * Checks if the current request is a creation request for a new destroy
 * message./*from  ww  w  .  j av  a2 s . c o m*/
 * 
 * @return true if the current request is a creation request for a new
 *         destroy message
 */
public boolean isDestroyMessageCreation() {
    return isSequenceMessageCreation(Predicates.instanceOf(DestructionMessageMapping.class));
}