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:brooklyn.entity.rebind.Dumpers.java

private static void deepVisitInternal(Object o, Predicate<Field> fieldPredicate, List<Object> visited,
        Deque<Object> refChain, Visitor visitor) throws IllegalArgumentException, IllegalAccessException {
    Class<?> clazz = (o != null) ? o.getClass() : null;
    refChain.addLast(o);//from  www  .  j a  v a  2  s  .c  o m
    Iterable<Object> filteredRefChain = Iterables.filter(refChain,
            Predicates.not(Predicates.instanceOf(Dumpers.Entry.class)));
    try {
        if (o == null) {
            // no-op
        } else if (isClassUntraversable(clazz)) {
            visitor.visit(o, filteredRefChain);
        } else if (containsSame(visited, o)) {
            // no-op
        } else {
            visited.add(o);
            boolean subTreeComplete = visitor.visit(o, filteredRefChain);
            if (!subTreeComplete) {
                Map<String, Object> members = findMembers(o, fieldPredicate);
                for (Map.Entry<String, Object> entry : members.entrySet()) {
                    deepVisitInternal(entry.getValue(), fieldPredicate, visited, refChain, visitor);
                }
            }
        }
    } finally {
        refChain.removeLast();
    }
}

From source file:org.obeonetwork.dsl.uml2.design.tests.plugin.manual.ServiceTestsUtils.java

private static List<String> getAllUmlOperations() {
    // Obtain a new resource set
    ResourceSet resSet = new ResourceSetImpl();

    // Create a resource
    Resource res = resSet.getResource(URI.createURI("http://www.eclipse.org/uml2/2.0.0/UML"), true);
    EObject root = res.getContents().get(0);

    // Get all eOperations
    List<EObject> umlOperations = Lists.newArrayList();
    Iterators.addAll(umlOperations,/*from   w  w  w  . j  av  a 2  s .  co m*/
            Iterators.filter(root.eAllContents(), Predicates.instanceOf(EOperation.class)));

    // Get eOperation names
    List<String> result = Lists.newArrayList();
    for (EObject umlOperation : umlOperations) {
        result.add(((EOperation) umlOperation).getName());
    }
    return result;
}

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

@Override
public void stop() {
    ServiceStateLogic.setExpectedState(this, Lifecycle.STOPPING);
    try {/* w ww.  j  ava2 s. c o  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);
        sensors().set(SERVICE_UP, false);
    } catch (Exception e) {
        ServiceStateLogic.setExpectedState(this, Lifecycle.ON_FIRE);
        throw Exceptions.propagate(e);
    }
}

From source file:brooklyn.networking.cloudstack.loadbalancer.CloudStackLoadBalancerImpl.java

@Override
protected String getAddressOfEntity(Entity member) {
    JcloudsSshMachineLocation machine = (JcloudsSshMachineLocation) Iterables.find(member.getLocations(),
            Predicates.instanceOf(JcloudsSshMachineLocation.class), null);

    if (machine != null && machine.getNode().getProviderId() != null) {
        return machine.getNode().getProviderId();
    } else {//from w  ww .j a v a 2s  .com
        LOG.error("Unable to construct cloudstack-id representation for {} in {}; skipping in {}",
                new Object[] { member, machine, this });
        return null;
    }
}

From source file:com.isotrol.impe3.freemarker.DefaultFreeMarkerService.java

/**
 * @see com.isotrol.impe3.freemarker.FreeMarkerService#decorateRenderModel(com.isotrol.impe3.api.component.RenderContext,
 * com.isotrol.impe3.api.component.TemplateModel)
 *//*from   w w  w  .j  a va  2  s  . c o  m*/
public void decorateRenderModel(RenderContext context, TemplateModel model) {
    // Img Uri
    if (!model.containsKey(IMG_URI) && imgUri != null) {
        model.put("imgUri", FreeMarker.uri(context, imgUri));
    }
    final Map<String, Object> map = Maps.newHashMap();
    for (Entry<String, Object> e : Maps.filterValues(model, Predicates.instanceOf(RenderingPhaseObject.class))
            .entrySet()) {
        RenderingPhaseObject rpo = (RenderingPhaseObject) e.getValue();
        Object val = rpo.apply(context);
        map.put(e.getKey(), val);
    }
    model.putAll(map);
}

From source file:net.derquinse.common.meta.MetaProperty.java

/**
 * Returns a predicate that evaluates to {@code true} if the property value tested is an instance
 * of the given class. If the property value being tested is {@code null} this predicate evaluates
 * to {@code false}.//from w  ww . j  a  va 2s  .  co m
 * <p>
 * <b>Warning:</b> contrary to the typical assumptions about predicates (as documented at
 * {@link Predicate#apply}), the returned predicate may not be <i>consistent with equals</i>. For
 * example, {@code instanceOf(ArrayList.class)} will yield different results for the two equal
 * instances {@code Lists.newArrayList(1)} and {@code Arrays.asList(1)}.
 */
public final Predicate<C> instanceOf(Class<?> clazz) {
    return compose(Predicates.instanceOf(clazz));
}

From source file:org.sosy_lab.cpachecker.cpa.value.symbolic.refiner.ARGTreePrecisionUpdater.java

/**
 * Updates the precision of the {@link ARGReachedSet} starting at the given refinement root
 * with the given precision increment for {@link ValueAnalysisCPA} and {@link ConstraintsCPA}.
 *
 * @param pReached the complete <code>ARGReachedSet</code>
 * @param pRefinementRoot the refinement root to start the update at
 * @param pValuePrecIncrement the precision increment for the <code>ValueAnalysisCPA</code>
 * @param pConstraintsPrecIncrement the precision increment for the <code>ConstraintsCPA</code>
 *//*  w w w .ja  v  a  2  s. c  o m*/
public void updateARGTree(final ARGReachedSet pReached, final ARGState pRefinementRoot,
        final Multimap<CFANode, MemoryLocation> pValuePrecIncrement,
        final ConstraintsPrecision.Increment pConstraintsPrecIncrement) {
    List<Precision> precisions = new ArrayList<>(2);

    precisions.add(createValuePrec(pRefinementRoot, pReached, pValuePrecIncrement));
    precisions.add(createConstraintsPrec(pRefinementRoot, pReached, pConstraintsPrecIncrement));

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

    precisionTypes.add(VariableTrackingPrecision.isMatchingCPAClass(ValueAnalysisCPA.class));
    precisionTypes.add(Predicates.instanceOf(ConstraintsPrecision.class));

    pReached.removeSubtree(pRefinementRoot, precisions, precisionTypes);
}

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 standard
 * message.//  w w w.j a  va  2 s  .c  om
 * 
 * @return true if the current request is a creation request for a new
 *         standard message
 */
public boolean isStandardMessageCreation() {
    return isSequenceMessageCreation(Predicates.instanceOf(BasicMessageMapping.class));
}

From source file:eu.stratosphere.sopremo.expressions.ExpressionUtil.java

public static EvaluationExpression replaceInputSelectionsWithArrayAccess(
        final EvaluationExpression evaluationExpression) {
    return evaluationExpression.clone()
            .replace(Predicates.instanceOf(InputSelection.class), new TransformFunction() {
                @Override/*from ww w.j  a  v  a  2s  .  c  o m*/
                public EvaluationExpression apply(final EvaluationExpression argument) {
                    return ((InputSelection) argument).asArrayAccess();
                }
            }).simplify();
}

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

/**
 * Creates resultExprs and baseTblResultExprs.
 *//*  w  w w. ja  v  a 2 s.  c  om*/
@Override
public void analyze(Analyzer analyzer) throws AnalysisException {
    super.analyze(analyzer);

    // Start out with table refs to establish aliases.
    TableRef leftTblRef = null; // the one to the left of tblRef
    for (int i = 0; i < tableRefs_.size(); ++i) {
        // Resolve and replace non-InlineViewRef table refs with a BaseTableRef or ViewRef.
        TableRef tblRef = tableRefs_.get(i);
        tblRef = analyzer.resolveTableRef(tblRef);
        Preconditions.checkNotNull(tblRef);
        tableRefs_.set(i, tblRef);
        tblRef.setLeftTblRef(leftTblRef);
        try {
            tblRef.analyze(analyzer);
        } catch (AnalysisException e) {
            // Only re-throw the exception if no tables are missing.
            if (analyzer.getMissingTbls().isEmpty())
                throw e;
        }
        leftTblRef = tblRef;
    }

    // All tableRefs have been analyzed, but at least one table was found missing.
    // There is no reason to proceed with analysis past this point.
    if (!analyzer.getMissingTbls().isEmpty()) {
        throw new AnalysisException("Found missing tables. Aborting analysis.");
    }

    // analyze plan hints from select list
    selectList_.analyzePlanHints(analyzer);

    // populate resultExprs_, aliasSmap_, and colLabels_
    for (int i = 0; i < selectList_.getItems().size(); ++i) {
        SelectListItem item = selectList_.getItems().get(i);
        if (item.isStar()) {
            TableName tblName = item.getTblName();
            if (tblName == null) {
                expandStar(analyzer);
            } else {
                expandStar(analyzer, tblName);
            }
        } else {
            // Analyze the resultExpr before generating a label to ensure enforcement
            // of expr child and depth limits (toColumn() label may call toSql()).
            item.getExpr().analyze(analyzer);
            if (item.getExpr().contains(Predicates.instanceOf(Subquery.class))) {
                throw new AnalysisException("Subqueries are not supported in the select list.");
            }
            resultExprs_.add(item.getExpr());
            String label = item.toColumnLabel(i, analyzer.useHiveColLabels());
            SlotRef aliasRef = new SlotRef(null, label);
            Expr existingAliasExpr = aliasSmap_.get(aliasRef);
            if (existingAliasExpr != null && !existingAliasExpr.equals(item.getExpr())) {
                // If we have already seen this alias, it refers to more than one column and
                // therefore is ambiguous.
                ambiguousAliasList_.add(aliasRef);
            }
            aliasSmap_.put(aliasRef, item.getExpr().clone());
            colLabels_.add(label);
        }
    }
    // The root stmt may not return a complex-typed value directly because we'd need to
    // serialize it in a meaningful way. We allow complex types in the select list for
    // non-root stmts to support views.
    for (Expr expr : resultExprs_) {
        if (expr.getType().isComplexType() && analyzer.isRootAnalyzer()) {
            throw new AnalysisException(String.format(
                    "Expr '%s' in select list of root statement returns a complex type '%s'.\n"
                            + "Only scalar types are allowed in the select list of the root statement.",
                    expr.toSql(), expr.getType().toSql()));
        }
    }

    if (TreeNode.contains(resultExprs_, AnalyticExpr.class)) {
        if (tableRefs_.isEmpty()) {
            throw new AnalysisException("Analytic expressions require FROM clause.");
        }

        // do this here, not after analyzeAggregation(), otherwise the AnalyticExprs
        // will get substituted away
        if (selectList_.isDistinct()) {
            throw new AnalysisException("cannot combine SELECT DISTINCT with analytic functions");
        }
    }

    if (whereClause_ != null) {
        whereClause_.analyze(analyzer);
        if (whereClause_.contains(Expr.isAggregatePredicate())) {
            throw new AnalysisException("aggregate function not allowed in WHERE clause");
        }
        whereClause_.checkReturnsBool("WHERE clause", false);
        Expr e = whereClause_.findFirstOf(AnalyticExpr.class);
        if (e != null) {
            throw new AnalysisException("WHERE clause must not contain analytic expressions: " + e.toSql());
        }
        analyzer.registerConjuncts(whereClause_, false);
    }

    createSortInfo(analyzer);
    analyzeAggregation(analyzer);
    analyzeAnalytics(analyzer);
    if (evaluateOrderBy_)
        createSortTupleInfo(analyzer);

    // Remember the SQL string before inline-view expression substitution.
    sqlString_ = toSql();
    resolveInlineViewRefs(analyzer);

    // If this block's select-project-join portion returns an empty result set and the
    // block has no aggregation, then mark this block as returning an empty result set.
    if (analyzer.hasEmptySpjResultSet() && aggInfo_ == null) {
        analyzer.setHasEmptyResultSet();
    }

    if (aggInfo_ != null)
        LOG.debug("post-analysis " + aggInfo_.debugString());
}