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:de.sanandrew.mods.claysoldiers.entity.EntityClayMan.java

@SuppressWarnings("unchecked")
public Collection<IMount> getMountsInRange() {
    return Collections2.transform(
            Collections2.filter(this.p_entitiesInRange, Predicates.instanceOf(IMount.class)),
            new Function<Object, IMount>() {
                @Override/* w  w  w .j av  a2  s.  com*/
                public IMount apply(Object input) {
                    return (IMount) input;
                }
            });
}

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

/**
 * {@inheritDoc}/*from   w w w  .j av a2  s . co  m*/
 *
 * <strong>Note</strong> for sub-classes; this method can be called while synchronized on {@link #mutex}.
 */
@Override
public String replaceMember(String memberId) {
    Entity member = getEntityManager().getEntity(memberId);
    LOG.info("In {}, replacing member {} ({})", new Object[] { this, memberId, member });

    if (member == null) {
        throw new NoSuchElementException(
                "In " + this + ", entity " + memberId + " cannot be resolved, so not replacing");
    }

    synchronized (mutex) {
        if (!getMembers().contains(member)) {
            throw new NoSuchElementException(
                    "In " + this + ", entity " + member + " is not a member so not replacing");
        }

        Location memberLoc = null;
        if (isAvailabilityZoneEnabled()) {
            // this member's location could be a machine provisioned by a sub-location, or the actual sub-location
            List<Location> subLocations = findSubLocations(getLocation(true));
            Collection<Location> actualMemberLocs = member.getLocations();
            boolean foundMatch = false;
            for (Iterator<Location> iter = actualMemberLocs.iterator(); !foundMatch && iter.hasNext();) {
                Location actualMemberLoc = iter.next();
                Location contenderMemberLoc = actualMemberLoc;
                do {
                    if (subLocations.contains(contenderMemberLoc)) {
                        memberLoc = contenderMemberLoc;
                        foundMatch = true;
                        LOG.debug("In {} replacing member {} ({}), inferred its sub-location is {}",
                                new Object[] { this, memberId, member, memberLoc });
                    }
                    contenderMemberLoc = contenderMemberLoc.getParent();
                } while (!foundMatch && contenderMemberLoc != null);
            }
            if (!foundMatch) {
                if (actualMemberLocs.isEmpty()) {
                    memberLoc = subLocations.get(0);
                    LOG.warn(
                            "In {} replacing member {} ({}), has no locations; falling back to first availability zone: {}",
                            new Object[] { this, memberId, member, memberLoc });
                } else {
                    memberLoc = Iterables
                            .tryFind(actualMemberLocs, Predicates.instanceOf(MachineProvisioningLocation.class))
                            .or(Iterables.getFirst(actualMemberLocs, null));
                    LOG.warn(
                            "In {} replacing member {} ({}), could not find matching sub-location; falling back to its actual location: {}",
                            new Object[] { this, memberId, member, memberLoc });
                }
            } else if (memberLoc == null) {
                // impossible to get here, based on logic above!
                throw new IllegalStateException("Unexpected condition! cluster=" + this + "; member=" + member
                        + "; actualMemberLocs=" + actualMemberLocs);
            }
        } else {
            // Replacing member, so new member should be in the same location as that being replaced.
            // Expect this to agree with `getMemberSpec().getLocations()` (if set). If not, then 
            // presumably there was a reason this specific member was started somewhere else!
            memberLoc = getLocation(false);
        }

        Entity replacement = replaceMember(member, memberLoc, ImmutableMap.of());
        return replacement.getId();
    }
}

From source file:org.eclipse.sirius.diagram.sequence.business.internal.layout.vertical.SequenceVerticalLayout.java

private int getMinY(EventEnd endBefore, EventEnd end, Collection<ISequenceEvent> commonIses, boolean pack,
        int currentLocation, Map<EventEnd, Integer> alreadyComputedLocations) {
    int genericGap = getGenericGap(endBefore, end, pack);
    int minGap = genericGap;

    if (!commonIses.isEmpty()) {
        int commonIseGap = getGapFromCommonSequenceEvent(end, commonIses, pack, genericGap);
        minGap = commonIseGap;/* w w  w.j av a 2  s .co  m*/
    } else {
        boolean operands = Iterables.any(eventEndToSequenceEvents.apply(end),
                Predicates.instanceOf(Operand.class));
        if (operands) {
            minGap = getGapBeforeOperandEnd(endBefore, end, currentLocation, genericGap,
                    alreadyComputedLocations);
        }
    }

    return currentLocation + minGap;
}

From source file:org.sosy_lab.cpachecker.core.algorithm.AnalysisWithRefinableEnablerCPAAlgorithm.java

private Precision replaceEnablerPrecision(final Precision pInitialPrecision, final Precision pNewPrec) {
    if (enablerCPA == Enabler.PREDICATE) {
        return Precisions.replaceByType(pInitialPrecision, pNewPrec,
                Predicates.instanceOf(PredicatePrecision.class));
    } else {/*  ww w. ja va 2  s . c  o  m*/
        return Precisions.replaceByType(pInitialPrecision, pNewPrec,
                VariableTrackingPrecision.isMatchingCPAClass(enablerCPA.cpaClass));
    }
}

From source file:org.eclipse.emf.compare.merge.AbstractMerger.java

/**
 * Returns the master equivalence of type {@link FeatureMapChange}, for a {@link ReferenceChange}.
 * /*ww  w. j  a va2 s .co m*/
 * @see AbstractMerger#findMasterEquivalence(Diff, boolean)
 * @param diff
 *            The {@link Diff} we need to check the equivalence for a 'master' difference.
 * @param mergeRightToLeft
 *            Direction of the current merging.
 * @return The master difference of {@code diff} and its equivalent diffs. This method may return
 *         <code>null</code> if there is no master diff.
 */
private Diff getMasterEquivalenceOnFeatureMap(ReferenceChange diff, boolean mergeRightToLeft) {
    if (diff.getKind() == DifferenceKind.MOVE) {

        Comparison comparison = diff.getMatch().getComparison();
        Match valueMatch = comparison.getMatch(diff.getValue());

        EObject sourceValue = ComparisonUtil.getExpectedSide(valueMatch, diff.getSource(), mergeRightToLeft);

        // No FeatureMap-MasterEquivalence when the resulting destination is not a FeatureMap
        if (!ComparisonUtil.isContainedInFeatureMap(sourceValue)) {
            return null;
        }
    }

    return Iterators.tryFind(diff.getEquivalence().getDifferences().iterator(),
            Predicates.instanceOf(FeatureMapChange.class)).orNull();
}

From source file:org.eclipse.sirius.diagram.ui.tools.internal.dialogs.DiagramElementsSelectionDialog.java

/**
 * Init the content provider.//from  ww  w. j ava2 s  .c  o  m
 * 
 * @param includeLabel
 *            include label (containers, lists, edges and nodes if there are
 *            on border for nodes) in the tree content
 */
protected void initContentProvider(boolean includeLabel) {
    AdapterFactory adapterFactory = getAdapterFactory(includeLabel);
    Predicate<Object> predicate = Predicates.instanceOf(DDiagramElement.class);
    if (includeLabel) {
        predicate = Predicates.or(predicate,
                Predicates.instanceOf(AbstractDDiagramElementLabelItemProvider.class));
    }
    contentProvider = new FilteredTreeContentProvider(adapterFactory, predicate);
}

From source file:org.eclipse.sirius.diagram.sequence.business.internal.layout.vertical.SequenceVerticalLayout.java

private int getGenericGap(EventEnd endBefore, EventEnd end, boolean pack) {
    int beforeGap = 0;

    if (endBefore != null) {
        Collection<ISequenceEvent> endBeforeEvents = eventEndToSequenceEvents.apply(endBefore);
        beforeGap = pack ? LayoutConstants.MIN_INTER_SEQUENCE_EVENTS_VERTICAL_GAP
                : LayoutConstants.EXECUTION_CHILDREN_MARGIN;

        // Predecessor : Logically instantaneouse States
        Iterable<State> predStates = Iterables.filter(endBeforeEvents, State.class);
        if (EventEndHelper.PUNCTUAL_COMPOUND_EVENT_END.apply(endBefore) && endBeforeEvents.size() == 1
                && Iterables.size(predStates) == 1) {
            State predState = Iterables.getOnlyElement(predStates);
            if (predState.isLogicallyInstantaneous()) {
                beforeGap += getAbstractNodeEventVerticalSize(endBefore, predState, endBeforeEvents, pack) / 2;
            }/*w  ww .java2  s. co m*/
        }

        if (Iterables.any(endBeforeEvents, Predicates.instanceOf(InteractionUse.class))
                && endBefore instanceof SingleEventEnd && ((SingleEventEnd) endBefore).isStart()) {
            beforeGap = LayoutConstants.DEFAULT_INTERACTION_USE_HEIGHT / 2;
        }

        if (Iterables.any(eventEndToSequenceEvents.apply(end), Predicates.instanceOf(InteractionUse.class))
                && end instanceof SingleEventEnd && !((SingleEventEnd) end).isStart()) {
            beforeGap = LayoutConstants.DEFAULT_INTERACTION_USE_HEIGHT / 2;
        }

        if (creators.keySet().contains(endBefore)) {
            if (pack) {
                beforeGap += getTargetFigureMidHeight(creators.get(endBefore))
                        + LayoutConstants.TIME_START_OFFSET
                        - LayoutConstants.MIN_INTER_SEQUENCE_EVENTS_VERTICAL_GAP;
            } else {
                beforeGap += getTargetFigureMidHeight(creators.get(endBefore));
            }
        } else if (losts.containsKey(endBefore)) {
            beforeGap += losts.get(endBefore).getBounds().height / 2;
        }
    } else {
        beforeGap = pack ? LayoutConstants.TIME_START_OFFSET : LayoutConstants.TIME_START_MIN_OFFSET;
    }

    if (destructors.keySet().contains(end)) {
        beforeGap += getTargetFigureMidHeight(destructors.get(end));
    } else if (losts.containsKey(end)) {
        beforeGap += losts.get(end).getBounds().height / 2;
    }

    // current event : Logically instantaneouse States
    Collection<ISequenceEvent> endEvents = eventEndToSequenceEvents.apply(end);
    Iterable<State> states = Iterables.filter(endEvents, State.class);
    if (EventEndHelper.PUNCTUAL_COMPOUND_EVENT_END.apply(end) && endEvents.size() == 1
            && Iterables.size(states) == 1) {
        State state = Iterables.getOnlyElement(states);
        if (state.isLogicallyInstantaneous()) {
            beforeGap += getAbstractNodeEventVerticalSize(endBefore, state, endEvents, pack) / 2;
        }
    }
    return beforeGap;
}

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

/**
 * Update the subquery within an inline view by expanding its select list with exprs
 * from a correlated predicate 'expr' that will be 'moved' to an ON clause in the
 * subquery's parent query block. We need to make sure that every expr extracted from
 * the subquery references an item in the subquery's select list. If 'updateGroupBy'
 * is true, the exprs extracted from 'expr' are also added in stmt's GROUP BY clause.
 * Throws an AnalysisException if we need to update the GROUP BY clause but
 * both the lhs and rhs of 'expr' reference a tuple of the subquery stmt.
 *//*  www .  ja  va2  s .co  m*/
private static void updateInlineView(InlineViewRef inlineView, Expr expr, List<TupleId> parentQueryTids,
        List<Expr> lhsExprs, List<Expr> rhsExprs, boolean updateGroupBy) throws AnalysisException {
    SelectStmt stmt = (SelectStmt) inlineView.getViewStmt();
    List<TupleId> subqueryTblIds = stmt.getTableRefIds();
    ArrayList<Expr> groupByExprs = null;
    if (updateGroupBy)
        groupByExprs = Lists.newArrayList();

    List<SelectListItem> items = stmt.selectList_.getItems();
    // Collect all the SlotRefs from 'expr' and identify those that are bound by
    // subquery tuple ids.
    ArrayList<Expr> slotRefs = Lists.newArrayList();
    expr.collectAll(Predicates.instanceOf(SlotRef.class), slotRefs);
    List<Expr> exprsBoundBySubqueryTids = Lists.newArrayList();
    for (Expr slotRef : slotRefs) {
        if (slotRef.isBoundByTupleIds(subqueryTblIds)) {
            exprsBoundBySubqueryTids.add(slotRef);
        }
    }
    // The correlated predicate only references slots from a parent block,
    // no need to update the subquery's select or group by list.
    if (exprsBoundBySubqueryTids.isEmpty())
        return;
    if (updateGroupBy) {
        Preconditions.checkState(expr instanceof BinaryPredicate);
        Expr exprBoundBySubqueryTids = null;
        if (exprsBoundBySubqueryTids.size() > 1) {
            // If the predicate contains multiple SlotRefs bound by subquery tuple
            // ids, they must all be on the same side of that predicate.
            if (expr.getChild(0).isBoundByTupleIds(subqueryTblIds)
                    && expr.getChild(1).isBoundByTupleIds(parentQueryTids)) {
                exprBoundBySubqueryTids = expr.getChild(0);
            } else if (expr.getChild(0).isBoundByTupleIds(parentQueryTids)
                    && expr.getChild(1).isBoundByTupleIds(subqueryTblIds)) {
                exprBoundBySubqueryTids = expr.getChild(1);
            } else {
                throw new AnalysisException(
                        "All subquery columns " + "that participate in a predicate must be on the same side of "
                                + "that predicate: " + expr.toSql());
            }
        } else {
            Preconditions.checkState(exprsBoundBySubqueryTids.size() == 1);
            exprBoundBySubqueryTids = exprsBoundBySubqueryTids.get(0);
        }
        exprsBoundBySubqueryTids.clear();
        exprsBoundBySubqueryTids.add(exprBoundBySubqueryTids);
    }

    // Add the exprs bound by subquery tuple ids to the select list and
    // register it for substitution. We use a temporary substitution map
    // because we cannot at this point analyze the new select list expr. Once
    // the new inline view is analyzed, the entries from this map will be
    // added to an ExprSubstitutionMap.
    for (Expr boundExpr : exprsBoundBySubqueryTids) {
        String colAlias = stmt.getColumnAliasGenerator().getNextAlias();
        items.add(new SelectListItem(boundExpr, null));
        inlineView.getExplicitColLabels().add(colAlias);
        lhsExprs.add(boundExpr);
        rhsExprs.add(new SlotRef(inlineView.getAliasAsName(), colAlias));
        if (groupByExprs != null)
            groupByExprs.add(boundExpr);
    }

    // Update the subquery's select list.
    boolean isDistinct = stmt.selectList_.isDistinct();
    Preconditions.checkState(!isDistinct);
    stmt.selectList_ = new SelectList(items, isDistinct, stmt.selectList_.getPlanHints());
    // Update subquery's GROUP BY clause
    if (groupByExprs != null && !groupByExprs.isEmpty()) {
        if (stmt.hasGroupByClause()) {
            stmt.groupingExprs_.addAll(groupByExprs);
        } else {
            stmt.groupingExprs_ = groupByExprs;
        }
    }
}

From source file:org.eclipse.sirius.ui.tools.internal.views.common.ContextMenuFiller.java

private Collection<EObject> getEObjects(final Collection<?> selection) {
    Collection<EObject> eObjects = Collections.emptyList();
    if (selection != null) {
        // Keep only EObjects, not Resources (CDOResources are EObjects).
        eObjects = Sets.newLinkedHashSet(Iterables.filter(Iterables.filter(selection, EObject.class),
                Predicates.not(Predicates.instanceOf(Resource.class))));
    }//from  www  . j a v  a2s.c o m
    return eObjects;
}

From source file:org.eclipse.sirius.diagram.sequence.business.internal.layout.vertical.SequenceVerticalLayout.java

private int getGapBeforeOperandEnd(EventEnd endBefore, EventEnd end, int currentLocation, int genericGap,
        Map<EventEnd, Integer> alreadyComputedLocations) {
    int beforeGap = genericGap;
    Iterable<Operand> operands = Iterables.filter(eventEndToSequenceEvents.apply(end), Operand.class);
    if (!Iterables.isEmpty(operands) && endBefore instanceof SingleEventEnd) {
        if (Iterables.any(eventEndToSequenceEvents.apply(endBefore),
                Predicates.instanceOf(CombinedFragment.class)) && ((SingleEventEnd) endBefore).isStart()) {
            beforeGap = LayoutConstants.COMBINED_FRAGMENT_TITLE_HEIGHT;
        } else {//w w  w.  ja v a 2 s  . c o m
            Operand op = selectEndedOperand(end, operands);
            if (op != null) {
                int startLoc = getStartLocation(op, alreadyComputedLocations);
                int minEndLoc = startLoc + LayoutConstants.DEFAULT_OPERAND_HEIGHT;
                beforeGap = Math.max(minEndLoc - currentLocation, genericGap);
            }
        }
    }
    return beforeGap;
}