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

/**
 * Create a tuple descriptor for the single tuple that is materialized, sorted and
 * output by the exec node implementing the sort. Done by materializing slot refs in
 * the order-by and result expressions. Those SlotRefs in the ordering and result exprs
 * are substituted with SlotRefs into the new tuple. This simplifies sorting logic for
 * total (no limit) sorts.//from   w w  w. j av a 2 s. c om
 * Done after analyzeAggregation() since ordering and result exprs may refer to
 * the outputs of aggregation. Invoked for UnionStmt as well since
 * TODO: We could do something more sophisticated than simply copying input
 * slotrefs - e.g. compute some order-by expressions.
 */
protected void createSortTupleInfo(Analyzer analyzer) {
    Preconditions.checkState(evaluateOrderBy_);

    // sourceSlots contains the slots from the input row to materialize.
    Set<SlotRef> sourceSlots = Sets.newHashSet();
    TreeNode.collect(resultExprs_, Predicates.instanceOf(SlotRef.class), sourceSlots);
    TreeNode.collect(sortInfo_.getOrderingExprs(), Predicates.instanceOf(SlotRef.class), sourceSlots);

    TupleDescriptor sortTupleDesc = analyzer.getDescTbl().createTupleDescriptor("sort");
    List<Expr> sortTupleExprs = Lists.newArrayList();
    sortTupleDesc.setIsMaterialized(true);
    // substOrderBy is the mapping from slot refs in the input row to slot refs in the
    // materialized sort tuple.
    ExprSubstitutionMap substOrderBy = new ExprSubstitutionMap();
    for (SlotRef origSlotRef : sourceSlots) {
        SlotDescriptor origSlotDesc = origSlotRef.getDesc();
        SlotDescriptor materializedDesc = analyzer.addSlotDescriptor(sortTupleDesc);
        Column origColumn = origSlotDesc.getColumn();
        if (origColumn != null) {
            materializedDesc.setColumn(origColumn);
        } else {
            materializedDesc.setType(origSlotDesc.getType());
        }
        materializedDesc.setLabel(origSlotDesc.getLabel());
        materializedDesc.setStats(ColumnStats.fromExpr(origSlotRef));
        SlotRef cloneRef = new SlotRef(materializedDesc);
        substOrderBy.put(origSlotRef, cloneRef);
        analyzer.createAuxEquivPredicate(cloneRef, origSlotRef);
        sortTupleExprs.add(origSlotRef);
    }

    resultExprs_ = Expr.substituteList(resultExprs_, substOrderBy, analyzer, false);
    sortInfo_.substituteOrderingExprs(substOrderBy, analyzer);
    sortInfo_.setMaterializedTupleInfo(sortTupleDesc, sortTupleExprs);
}

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

/**
 * Check if this {@link DDiagramElement} is directly collapsed.
 * /*ww w  .ja  v  a 2  s. com*/
 * @return true if the given element is directly collapsed.
 */
public boolean isCollapsed() {
    return Iterables.any(element.getGraphicalFilters(),
            Predicates.and(Predicates.instanceOf(CollapseFilter.class),
                    Predicates.not(Predicates.instanceOf(IndirectlyCollapseFilter.class))));

}

From source file:org.grouplens.lenskit.eval.script.ConfigMethodInvoker.java

/**
 * Find a method that should be invoked multiple times, if the argument is iterable.  The
 * argument may be iterated multiple times.
 *
 * @param self The configurable object./*from  w  w  w  . java2s.com*/
 * @param name The method name.
 * @param args The arguments.
 * @return A thunk that will invoke the method.
 */
private Supplier<Object> findMultiMethod(final Object self, String name, final Object[] args) {
    if (args.length != 1)
        return null;
    // the argument is a list
    final Object arg = args[0];
    if (!(arg instanceof Iterable)) {
        return null;
    }

    final Iterable<?> objects = (Iterable<?>) arg;

    Supplier<Object> result = null;
    for (final Method method : getOneArgMethods(self, name)) {
        Class ptype = method.getParameterTypes()[0];
        boolean good = Iterables.all(objects, Predicates.or(Predicates.isNull(), Predicates.instanceOf(ptype)));
        if (good) {
            if (result != null) {
                throw new RuntimeException("multiple compatible methods named " + name);
            } else {
                result = new Supplier<Object>() {
                    @Override
                    public Object get() {
                        for (Object obj : objects) {
                            try {
                                method.invoke(self, obj);
                            } catch (IllegalAccessException e) {
                                throw Throwables.propagate(e);
                            } catch (InvocationTargetException e) {
                                if (e.getCause() != null) {
                                    throw Throwables.propagate(e);
                                }
                            }
                        }
                        return null;
                    }
                };
            }
        }
    }

    return result;
}

From source file:org.apache.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./* www. j av a  2s  . c o  m*/
 */
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());
    }
    substituteOrdinalsAliases(orderingExprs, "ORDER BY", analyzer);

    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 appearing in a view, subquery, union operand, ");
        strBuilder.append("or an insert/ctas statement has no effect on the query result ");
        strBuilder.append("unless a LIMIT and/or OFFSET is used in conjunction ");
        strBuilder.append("with the ORDER BY.");
        analyzer.addWarning(strBuilder.toString());
    } else {
        evaluateOrderBy_ = true;
    }
}

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

private void refineUsingInterpolants(final ARGReachedSet pReached,
        ValueAnalysisInterpolationTree interpolationTree) {
    Map<ARGState, List<Precision>> refinementInformation = new HashMap<>();
    for (ARGState root : interpolationTree.obtainRefinementRoots(restartStrategy)) {
        List<Precision> precisions = new ArrayList<>(2);

        // merge the value precisions of the subtree, and refine it
        precisions.add(mergeValuePrecisionsForSubgraph(root, pReached)
                .withIncrement(interpolationTree.extractPrecisionIncrement(root)));

        // merge the predicate precisions of the subtree, if available
        if (isPredicatePrecisionAvailable(pReached, root)) {
            precisions.add(mergePredictePrecisionsForSubgraph(root, pReached));
        }/*from   w w  w. java 2 s  . c o  m*/

        refinementInformation.put(root, precisions);
    }

    for (Map.Entry<ARGState, List<Precision>> info : refinementInformation.entrySet()) {
        List<Predicate<? super Precision>> precisionTypes = new ArrayList<>(2);

        precisionTypes.add(VariableTrackingPrecision.isMatchingCPAClass(ValueAnalysisCPA.class));
        if (isPredicatePrecisionAvailable(pReached, info.getKey())) {
            precisionTypes.add(Predicates.instanceOf(PredicatePrecision.class));
        }

        pReached.removeSubtree(info.getKey(), info.getValue(), precisionTypes);
    }
}

From source file:org.sosy_lab.java_smt.basicimpl.AbstractBooleanFormulaManager.java

@Override
public void visitRecursively(BooleanFormula pF, BooleanFormulaVisitor<TraversalProcess> pFormulaVisitor) {
    formulaCreator.visitRecursively(new DelegatingFormulaVisitor<>(pFormulaVisitor), pF,
            Predicates.instanceOf(BooleanFormula.class)::apply);
}

From source file:vazkii.botania.api.corporea.CorporeaHelper.java

/**
 * Gets the spark attached to the block in the coords passed in. Note that the coords passed
 * in are for the block that the spark will be on, not the coords of the spark itself.
 */// w w  w  .  ja v  a  2  s. co m
public static ICorporeaSpark getSparkForBlock(World world, BlockPos pos) {
    List<Entity> sparks = world.getEntitiesWithinAABB(Entity.class,
            new AxisAlignedBB(pos.up(), pos.add(1, 2, 1)), Predicates.instanceOf(ICorporeaSpark.class));
    return sparks.isEmpty() ? null : (ICorporeaSpark) sparks.get(0);
}

From source file:org.apache.impala.analysis.StmtRewriter.java

/**
 * Rewrite all subqueries of a stmt's WHERE clause. Initially, all the
 * conjuncts containing subqueries are extracted from the WHERE clause and are
 * replaced with true BoolLiterals. Subsequently, each extracted conjunct is
 * merged into its parent select block by converting it into a join.
 * Conjuncts with subqueries that themselves contain conjuncts with subqueries are
 * recursively rewritten in a bottom up fashion.
 *
 * The following example illustrates the bottom up rewriting of nested queries.
 * Suppose we have the following three level nested query Q0:
 *
 * SELECT */*from   www.  j  a va  2s . c  o  m*/
 * FROM T1                                            : Q0
 * WHERE T1.a IN (SELECT a
 *                FROM T2 WHERE T2.b IN (SELECT b
 *                                       FROM T3))
 * AND T1.c < 10;
 *
 * This query will be rewritten as follows. Initially, the IN predicate
 * T1.a IN (SELECT a FROM T2 WHERE T2.b IN (SELECT b FROM T3)) is extracted
 * from the top level block (Q0) since it contains a subquery and is
 * replaced by a true BoolLiteral, resulting in the following query Q1:
 *
 * SELECT * FROM T1 WHERE TRUE : Q1
 *
 * Since the stmt in the extracted predicate contains a conjunct with a subquery,
 * it is also rewritten. As before, rewriting stmt SELECT a FROM T2
 * WHERE T2.b IN (SELECT b FROM T3) works by first extracting the conjunct that
 * contains the subquery (T2.b IN (SELECT b FROM T3)) and substituting it with
 * a true BoolLiteral, producing the following stmt Q2:
 *
 * SELECT a FROM T2 WHERE TRUE : Q2
 *
 * The predicate T2.b IN (SELECT b FROM T3) is then merged with Q2,
 * producing the following unnested query Q3:
 *
 * SELECT a FROM T2 LEFT SEMI JOIN (SELECT b FROM T3) $a$1 ON T2.b = $a$1.b : Q3
 *
 * The extracted IN predicate becomes:
 *
 * T1.a IN (SELECT a FROM T2 LEFT SEMI JOIN (SELECT b FROM T3) $a$1 ON T2.b = $a$1.b)
 *
 * Finally, the rewritten IN predicate is merged with query block Q1,
 * producing the following unnested query (WHERE clauses that contain only
 * conjunctions of true BoolLiterals are eliminated):
 *
 * SELECT *
 * FROM T1 LEFT SEMI JOIN (SELECT a
 *                         FROM T2 LEFT SEMI JOIN (SELECT b FROM T3) $a$1
 *                         ON T2.b = $a$1.b) $a$1
 * ON $a$1.a = T1.a
 * WHERE T1.c < 10;
 *
 */
private static void rewriteWhereClauseSubqueries(SelectStmt stmt, Analyzer analyzer) throws AnalysisException {
    int numTableRefs = stmt.fromClause_.size();
    ArrayList<Expr> exprsWithSubqueries = Lists.newArrayList();
    ExprSubstitutionMap smap = new ExprSubstitutionMap();
    // Check if all the conjuncts in the WHERE clause that contain subqueries
    // can currently be rewritten as a join.
    for (Expr conjunct : stmt.whereClause_.getConjuncts()) {
        List<Subquery> subqueries = Lists.newArrayList();
        conjunct.collectAll(Predicates.instanceOf(Subquery.class), subqueries);
        if (subqueries.size() == 0)
            continue;
        if (subqueries.size() > 1) {
            throw new AnalysisException(
                    "Multiple subqueries are not supported in " + "expression: " + conjunct.toSql());
        }
        if (!(conjunct instanceof InPredicate) && !(conjunct instanceof ExistsPredicate)
                && !(conjunct instanceof BinaryPredicate) && !conjunct.contains(Expr.IS_SCALAR_SUBQUERY)) {
            throw new AnalysisException(
                    "Non-scalar subquery is not supported in " + "expression: " + conjunct.toSql());
        }

        if (conjunct instanceof ExistsPredicate) {
            // Check if we can determine the result of an ExistsPredicate during analysis.
            // If so, replace the predicate with a BoolLiteral predicate and remove it from
            // the list of predicates to be rewritten.
            BoolLiteral boolLiteral = replaceExistsPredicate((ExistsPredicate) conjunct);
            if (boolLiteral != null) {
                boolLiteral.analyze(analyzer);
                smap.put(conjunct, boolLiteral);
                continue;
            }
        }

        // Replace all the supported exprs with subqueries with true BoolLiterals
        // using an smap.
        BoolLiteral boolLiteral = new BoolLiteral(true);
        boolLiteral.analyze(analyzer);
        smap.put(conjunct, boolLiteral);
        exprsWithSubqueries.add(conjunct);
    }
    stmt.whereClause_ = stmt.whereClause_.substitute(smap, analyzer, false);

    boolean hasNewVisibleTuple = false;
    // Recursively rewrite all the exprs that contain subqueries and merge them
    // with 'stmt'.
    for (Expr expr : exprsWithSubqueries) {
        if (mergeExpr(stmt, rewriteExpr(expr, analyzer), analyzer)) {
            hasNewVisibleTuple = true;
        }
    }
    if (canEliminate(stmt.whereClause_))
        stmt.whereClause_ = null;
    if (hasNewVisibleTuple)
        replaceUnqualifiedStarItems(stmt, numTableRefs);
}

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

/**
 * Rewrite all subqueries of a stmt's WHERE clause. Initially, all the
 * conjuncts containing subqueries are extracted from the WHERE clause and are
 * replaced with true BoolLiterals. Subsequently, each extracted conjunct is
 * merged into its parent select block by converting it into a join.
 * Conjuncts with subqueries that themselves contain conjuncts with subqueries are
 * recursively rewritten in a bottom up fashion.
 *
 * The following example illustrates the bottom up rewriting of nested queries.
 * Suppose we have the following three level nested query Q0:
 *
 * SELECT */*from  w  w  w  .  ja v a 2s.c o  m*/
 * FROM T1                                            : Q0
 * WHERE T1.a IN (SELECT a
 *                FROM T2 WHERE T2.b IN (SELECT b
 *                                       FROM T3))
 * AND T1.c < 10;
 *
 * This query will be rewritten as follows. Initially, the IN predicate
 * T1.a IN (SELECT a FROM T2 WHERE T2.b IN (SELECT b FROM T3)) is extracted
 * from the top level block (Q0) since it contains a subquery and is
 * replaced by a true BoolLiteral, resulting in the following query Q1:
 *
 * SELECT * FROM T1 WHERE TRUE : Q1
 *
 * Since the stmt in the extracted predicate contains a conjunct with a subquery,
 * it is also rewritten. As before, rewriting stmt SELECT a FROM T2
 * WHERE T2.b IN (SELECT b FROM T3) works by first extracting the conjunct that
 * contains the subquery (T2.b IN (SELECT b FROM T3)) and substituting it with
 * a true BoolLiteral, producing the following stmt Q2:
 *
 * SELECT a FROM T2 WHERE TRUE : Q2
 *
 * The predicate T2.b IN (SELECT b FROM T3) is then merged with Q2,
 * producing the following unnested query Q3:
 *
 * SELECT a FROM T2 LEFT SEMI JOIN (SELECT b FROM T3) $a$1 ON T2.b = $a$1.b : Q3
 *
 * The extracted IN predicate becomes:
 *
 * T1.a IN (SELECT a FROM T2 LEFT SEMI JOIN (SELECT b FROM T3) $a$1 ON T2.b = $a$1.b)
 *
 * Finally, the rewritten IN predicate is merged with query block Q1,
 * producing the following unnested query (WHERE clauses that contain only
 * conjunctions of true BoolLiterals are eliminated):
 *
 * SELECT *
 * FROM T1 LEFT SEMI JOIN (SELECT a
 *                         FROM T2 LEFT SEMI JOIN (SELECT b FROM T3) $a$1
 *                         ON T2.b = $a$1.b) $a$1
 * ON $a$1.a = T1.a
 * WHERE T1.c < 10;
 *
 */
private static void rewriteWhereClauseSubqueries(SelectStmt stmt, Analyzer analyzer) throws AnalysisException {
    int numTableRefs = stmt.tableRefs_.size();
    ArrayList<Expr> exprsWithSubqueries = Lists.newArrayList();
    ExprSubstitutionMap smap = new ExprSubstitutionMap();
    // Replace all BetweenPredicates that contain subqueries with their
    // equivalent compound predicates.
    stmt.whereClause_ = replaceBetweenPredicates(stmt.whereClause_);
    // Check if all the conjuncts in the WHERE clause that contain subqueries
    // can currently be rewritten as a join.
    for (Expr conjunct : stmt.whereClause_.getConjuncts()) {
        List<Subquery> subqueries = Lists.newArrayList();
        conjunct.collectAll(Predicates.instanceOf(Subquery.class), subqueries);
        if (subqueries.size() == 0)
            continue;
        if (subqueries.size() > 1) {
            throw new AnalysisException(
                    "Multiple subqueries are not supported in " + "expression: " + conjunct.toSql());
        }
        if (!(conjunct instanceof InPredicate) && !(conjunct instanceof ExistsPredicate)
                && !(conjunct instanceof BinaryPredicate) && !conjunct.contains(Expr.IS_SCALAR_SUBQUERY)) {
            throw new AnalysisException(
                    "Non-scalar subquery is not supported in " + "expression: " + conjunct.toSql());
        }

        // Replace all the supported exprs with subqueries with true BoolLiterals
        // using an smap.
        BoolLiteral boolLiteral = new BoolLiteral(true);
        boolLiteral.analyze(analyzer);
        smap.put(conjunct, boolLiteral);
        exprsWithSubqueries.add(conjunct);
    }
    stmt.whereClause_ = stmt.whereClause_.substitute(smap, analyzer, false);

    boolean hasNewVisibleTuple = false;
    // Recursively rewrite all the exprs that contain subqueries and merge them
    // with 'stmt'.
    for (Expr expr : exprsWithSubqueries) {
        if (mergeExpr(stmt, rewriteExpr(expr, analyzer), analyzer)) {
            hasNewVisibleTuple = true;
        }
    }
    if (canEliminate(stmt.whereClause_))
        stmt.whereClause_ = null;
    if (hasNewVisibleTuple)
        replaceUnqualifiedStarItems(stmt, numTableRefs);
}

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

private Option<Bounds> getNewGMFBounds(boolean isCollapsed) {
    EObject element = node.getElement();
    LayoutConstraint layoutConstraint = node.getLayoutConstraint();

    if (element instanceof DDiagramElement && layoutConstraint instanceof Bounds) {
        Bounds bounds = (Bounds) layoutConstraint;
        Bounds newBounds = NotationFactory.eINSTANCE.createBounds();

        Dimension dim;// w  ww  . j  a va  2s .c om
        if (isCollapsed) {
            dim = getCollapsedSize();
        } else {
            CollapseFilter filter = (CollapseFilter) Iterables
                    .getFirst(Iterables.filter(((DDiagramElement) element).getGraphicalFilters(),
                            Predicates.instanceOf(CollapseFilter.class)), null);

            if (filter == null || (filter.getWidth() == 0 || filter.getHeight() == 0)) {
                dim = getDefaultDim((DDiagramElement) element);
            } else {
                dim = new Dimension(filter.getWidth(), filter.getHeight());
            }
        }
        Rectangle rect = null;
        Rectangle constraint = new Rectangle(bounds.getX(), bounds.getY(), bounds.getWidth(),
                bounds.getHeight());
        Option<Rectangle> parentBorder = getParentBorder();
        if (parentBorder.some()) {
            // When the node is on diagram, there is no need to translate to
            // absolute.
            constraint.translate(parentBorder.get().x, parentBorder.get().y);
        }
        if (isCollapsed) {
            rect = PortLayoutHelper.getCollapseCandidateLocation(dim, constraint, parentBorder.get());
        } else {
            rect = PortLayoutHelper.getUncollapseCandidateLocation(dim, constraint, parentBorder.get());
        }
        if (parentBorder.some()) {
            // we translate to relative if there is a parent node.
            Dimension d = rect.getLocation().getDifference(parentBorder.get().getLocation());
            rect.setLocation(new Point(d.width, d.height));
        } else {
            rect.setLocation(rect.getLocation().getCopy());
        }
        newBounds.setHeight(rect.height);
        newBounds.setWidth(rect.width);
        newBounds.setX(rect.x);
        newBounds.setY(rect.y);

        return Options.newSome(newBounds);
    }
    return Options.newNone();
}