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:jenkins.plugins.office365connector.Office365ConnectorWebhookNotifier.java

private void addScmDetails() {
    Set<User> users;/*from   w ww.  j  a v a  2 s  .  c  om*/
    List<ChangeLogSet<ChangeLogSet.Entry>> sets;

    try {
        users = (Set<User>) run.getClass().getMethod("getCulprits").invoke(run);
        sets = (List<ChangeLogSet<ChangeLogSet.Entry>>) run.getClass().getMethod("getChangeSets").invoke(run);
    } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
        users = Collections.emptySet();
        sets = Collections.emptyList();
    }

    factsBuilder.addCulprits(users);

    if (!sets.isEmpty()) {
        Set<User> authors = new HashSet<>();
        int filesCounter = 0;
        if (Iterables.all(sets, Predicates.instanceOf(ChangeLogSet.class))) {
            for (ChangeLogSet<ChangeLogSet.Entry> set : sets) {
                for (ChangeLogSet.Entry entry : set) {
                    authors.add(entry.getAuthor());
                    filesCounter += getAffectedFiles(entry).size();
                }
            }
        }
        factsBuilder.addDevelopers(authors);
        factsBuilder.addNumberOfFilesChanged(filesCounter);
    }
}

From source file:org.apache.brooklyn.core.mgmt.rebind.dto.MementosGenerators.java

/**
 * @deprecated since 0.7.0; use {@link #newBasicMemento(BrooklynObject)} instead
 *//*from ww  w. j  a  v  a2  s. c  o  m*/
@Deprecated
public static BasicLocationMemento.Builder newLocationMementoBuilder(Location location) {
    BasicLocationMemento.Builder builder = BasicLocationMemento.builder();
    populateBrooklynObjectMementoBuilder(location, builder);

    Set<String> nonPersistableFlagNames = MutableMap.<String, Object>builder()
            .putAll(FlagUtils.getFieldsWithFlagsWithModifiers(location, Modifier.TRANSIENT))
            .putAll(FlagUtils.getFieldsWithFlagsWithModifiers(location, Modifier.STATIC))
            .put("id", String.class).filterValues(Predicates.not(Predicates.instanceOf(ConfigKey.class)))
            .build().keySet();
    Map<String, Object> persistableFlags = MutableMap.<String, Object>builder().putAll(
            FlagUtils.getFieldsWithFlagsExcludingModifiers(location, Modifier.STATIC ^ Modifier.TRANSIENT))
            .removeAll(nonPersistableFlagNames).build();
    ConfigBag persistableConfig = new ConfigBag().copy(((LocationInternal) location).config().getLocalBag())
            .removeAll(nonPersistableFlagNames);

    builder.copyConfig(persistableConfig);
    builder.locationConfig.putAll(persistableFlags);

    Location parentLocation = location.getParent();
    builder.parent = (parentLocation != null) ? parentLocation.getId() : null;

    for (Location child : location.getChildren()) {
        builder.children.add(child.getId());
    }

    return builder;
}

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

/**
 * {@inheritDoc}/*from   w ww  . j ava  2s.  c  o m*/
 */
@Override
protected boolean applyComputedLayout(Map<? extends ISequenceElement, Range> finalRanges, boolean pack) {
    boolean applied = false;
    Iterable<ISequenceEvent> keySet = Iterables.filter(finalRanges.keySet(), ISequenceEvent.class);

    // Begin with lifelines and executions (anchor positions move)
    for (ISequenceEvent ise : Iterables.filter(keySet, Predicates.not(Predicates.instanceOf(Message.class)))) {
        final Range newRange = finalRanges.get(ise);
        ise.setVerticalRange(newRange);
        applied = true;
    }

    // Then apply computed vertical range on messages
    for (Message smep : Iterables.filter(keySet, Message.class)) {
        final Range newRange = finalRanges.get(smep);
        smep.setVerticalRange(newRange);
        applied = true;
    }

    applied = layoutUnconnectedLostMessageEnd() || applied;

    return applied;
}

From source file:edu.buaa.satla.analysis.core.arg.ARGUtils.java

/**
 * Find a path in the ARG. The necessary information to find the path is a
 * boolean value for each branching situation that indicates which of the two
 * AssumeEdges should be taken./*from   w ww .j  a va 2  s.  co m*/
 *
 * @param root The root element of the ARG (where to start the path)
 * @param arg All elements in the ARG or a subset thereof (elements outside this set will be ignored).
 * @param branchingInformation A map from ARG state ids to boolean values indicating the outgoing direction.
 * @return A path through the ARG from root to target.
 * @throws IllegalArgumentException If the direction information doesn't match the ARG or the ARG is inconsistent.
 */
public static ARGPath getPathFromBranchingInformation(ARGState root, Set<? extends AbstractState> arg,
        Map<Integer, Boolean> branchingInformation) throws IllegalArgumentException {

    checkArgument(arg.contains(root));

    List<ARGState> states = new ArrayList<>();
    List<CFAEdge> edges = new ArrayList<>();
    ARGState currentElement = root;
    while (!currentElement.isTarget()) {
        Collection<ARGState> children = currentElement.getChildren();

        ARGState child;
        CFAEdge edge;
        switch (children.size()) {

        case 0:
            throw new IllegalArgumentException("ARG target path terminates without reaching target state!");

        case 1: // only one successor, easy
            child = Iterables.getOnlyElement(children);
            edge = currentElement.getEdgeToChild(child);
            break;

        case 2: // branch
            // first, find out the edges and the children
            CFAEdge trueEdge = null;
            CFAEdge falseEdge = null;
            ARGState trueChild = null;
            ARGState falseChild = null;

            CFANode loc = AbstractStates.extractLocation(currentElement);
            if (!leavingEdges(loc).allMatch(Predicates.instanceOf(AssumeEdge.class))) {
                Set<ARGState> candidates = Sets.intersection(Sets.newHashSet(children), arg).immutableCopy();
                if (candidates.size() != 1) {
                    throw new IllegalArgumentException("ARG branches where there is no AssumeEdge!");
                }
                child = Iterables.getOnlyElement(candidates);
                edge = currentElement.getEdgeToChild(child);
                break;
            }

            for (ARGState currentChild : children) {
                CFAEdge currentEdge = currentElement.getEdgeToChild(currentChild);
                if (((AssumeEdge) currentEdge).getTruthAssumption()) {
                    trueEdge = currentEdge;
                    trueChild = currentChild;
                } else {
                    falseEdge = currentEdge;
                    falseChild = currentChild;
                }
            }
            if (trueEdge == null || falseEdge == null) {
                throw new IllegalArgumentException("ARG branches with non-complementary AssumeEdges!");
            }
            assert trueChild != null;
            assert falseChild != null;

            // search first idx where we have a predicate for the current branching
            Boolean predValue = branchingInformation.get(currentElement.getStateId());
            if (predValue == null) {
                throw new IllegalArgumentException("ARG branches without direction information!");
            }

            // now select the right edge
            if (predValue) {
                edge = trueEdge;
                child = trueChild;
            } else {
                edge = falseEdge;
                child = falseChild;
            }
            break;

        default:
            Set<ARGState> candidates = Sets.intersection(Sets.newHashSet(children), arg).immutableCopy();
            if (candidates.size() != 1) {
                throw new IllegalArgumentException("ARG splits with more than two branches!");
            }
            child = Iterables.getOnlyElement(candidates);
            edge = currentElement.getEdgeToChild(child);
            break;
        }

        if (!arg.contains(child)) {
            throw new IllegalArgumentException("ARG and direction information from solver disagree!");
        }

        states.add(currentElement);
        edges.add(edge);
        currentElement = child;
    }

    // need to add another pair with target state and one (arbitrary) outgoing edge
    CFANode loc = extractLocation(currentElement);
    CFAEdge lastEdge = leavingEdges(loc).first().orNull();
    states.add(currentElement);
    edges.add(lastEdge);

    return new ARGPath(states, edges);
}

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

/**
 * Replaces all SloRefs in expr with a NullLiteral using nullSMap, and evaluates the
 * resulting constant expr. Returns true if the constant expr yields a non-NULL value,
 * false otherwise./* w ww .ja v  a2 s.  c  o  m*/
 */
private boolean requiresNullWrapping(Analyzer analyzer, Expr expr, ExprSubstitutionMap nullSMap)
        throws InternalException {
    // If the expr is already wrapped in an IF(TupleIsNull(), NULL, expr)
    // then do not try to execute it.
    // TODO: return true in this case?
    if (expr.contains(Predicates.instanceOf(TupleIsNullPredicate.class)))
        return true;

    // Replace all SlotRefs in expr with NullLiterals, and wrap the result
    // with an IS NOT NULL predicate.
    Expr isNotNullLiteralPred = new IsNullPredicate(expr.substitute(nullSMap, analyzer, false), true);
    Preconditions.checkState(isNotNullLiteralPred.isConstant());
    // analyze to insert casts, etc.
    isNotNullLiteralPred.analyzeNoThrow(analyzer);
    return FeSupport.EvalPredicate(isNotNullLiteralPred, analyzer.getQueryCtx());
}

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

@Override
public void performRefinement(ARGReachedSet pReached, List<ARGState> abstractionStatesTrace,
        List<BooleanFormula> pInterpolants, boolean pRepeatedCounterexample)
        throws CPAException, InterruptedException {

    pRepeatedCounterexample = !lastRefinementUsedHeuristics && pRepeatedCounterexample;

    if (useStaticRefinement()) {
        UnmodifiableReachedSet reached = pReached.asReachedSet();
        ARGState root = (ARGState) reached.getFirstState();
        ARGState refinementRoot = Iterables.getLast(root.getChildren());

        PredicatePrecision heuristicPrecision;
        try {//from   w w  w .  j av a  2s .c o  m
            heuristicPrecision = staticRefiner.extractPrecisionFromCfa(pReached.asReachedSet(),
                    abstractionStatesTrace, atomicPredicates);
        } catch (CPATransferException | SolverException e) {
            logger.logUserException(Level.WARNING, e, "Static refinement failed");
            lastRefinementUsedHeuristics = false;
            super.performRefinement(pReached, abstractionStatesTrace, pInterpolants, pRepeatedCounterexample);
            return;
        }

        shutdownNotifier.shutdownIfNecessary();
        pReached.removeSubtree(refinementRoot, heuristicPrecision,
                Predicates.instanceOf(PredicatePrecision.class));

        heuristicsCount++;
        lastRefinementUsedHeuristics = true;
    } else {
        lastRefinementUsedHeuristics = false;
        super.performRefinement(pReached, abstractionStatesTrace, pInterpolants, pRepeatedCounterexample);
    }
}

From source file:org.eclipse.sirius.diagram.ui.tools.internal.actions.distribute.DistributeAction.java

@Override
protected List<?> createOperationSet() {
    List<?> selection = getSelectedObjects();
    if (selection.isEmpty() || !(selection.get(0) instanceof IGraphicalEditPart)) {
        selection = Collections.EMPTY_LIST;
    } else {/*from w w  w.  j a  va  2  s . c  om*/
        // Get the the top level selected edit parts
        selection = ToolUtilities.getSelectionWithoutDependants(selection);
        // Remove the connections
        selection = Lists.newArrayList(
                Iterables.filter(selection, Predicates.not(Predicates.instanceOf(ConnectionEditPart.class))));
        if (selection.size() < 3) {
            selection = Collections.EMPTY_LIST;
        } else {
            EditPart parent = ((EditPart) selection.get(0)).getParent();
            int sideOfFirstSelection = PositionConstants.NONE;
            if (selection.get(0) instanceof IBorderItemEditPart) {
                // If the first selected element is a border node
                sideOfFirstSelection = ((IBorderItemEditPart) selection.get(0)).getBorderItemLocator()
                        .getCurrentSideOfParent();
                // Check that the side corresponds to the action axis
                // (horizontal or vertical)
                if (!isHorizontalAxisAuthorizedForBorderNode(sideOfFirstSelection)
                        && !isVerticalAxisAuthorizedForBorderNode(sideOfFirstSelection)) {
                    selection = Collections.EMPTY_LIST;
                }
            }

            for (int i = 1; i < selection.size(); i++) {
                EditPart part = (EditPart) selection.get(i);
                if (part.getParent() != parent) {
                    // All the selected shapes must have the same parent.
                    selection = Collections.EMPTY_LIST;
                    break;
                } else if (sideOfFirstSelection != PositionConstants.NONE
                        && !isABorderNodeOnSameAxis(part, sideOfFirstSelection)) {
                    // All the selected border nodes must have the same
                    // axis.
                    selection = Collections.EMPTY_LIST;
                    break;
                } else if (part instanceof IGraphicalEditPart) {
                    EditPartQuery containerLayoutQuery = new EditPartQuery((IGraphicalEditPart) part);
                    if (!containerLayoutQuery.isFreeFormContainerChildrenPresentation()) {
                        // List item and elements inside compartment can not
                        // be distribute
                        selection = Collections.EMPTY_LIST;
                        break;
                    }
                }
            }
        }
    }
    return selection;
}

From source file:blue.lapis.pore.impl.PoreWorld.java

@Override
@SuppressWarnings("unchecked")
public <T extends Entity> Collection<T> getEntitiesByClass(Class<T> cls) {
    return (Collection<T>) Collections2.filter(getEntities(), Predicates.instanceOf(cls));
}

From source file:org.richfaces.ui.input.autocomplete.AbstractAutocomplete.java

/**
 * Returns 'table' if all children are columns and thus the component should be rendered as a table; it returns 'list'
 * otherwise/*from   ww  w .  j a v  a  2 s. com*/
 */
@Attribute(generate = false, hidden = true, defaultValue = "Layout.list")
public String getLayout() {
    return (getChildCount() > 0 && Iterables.all(getChildren(), Predicates.instanceOf(UIColumn.class)))
            ? "table"
            : "list";
}

From source file:brooklyn.networking.sdn.mesos.CalicoModuleImpl.java

@Override
public void provisionNetwork(VirtualNetwork network) {
    String networkId = network.sensors().get(VirtualNetwork.NETWORK_ID);
    Cidr subnetCidr = SdnUtils.provisionNetwork(this, network);
    boolean ipip = config().get(CalicoModule.USE_IPIP);
    boolean nat = config().get(CalicoModule.USE_NAT);
    String addPool = String.format("calicoctl pool add %s %s %s", subnetCidr, ipip ? "--ipip" : "",
            nat ? "--nat-outgoing" : "");
    MesosSlave slave = (MesosSlave) getMesosCluster().sensors().get(MesosCluster.MESOS_SLAVES).getMembers()
            .iterator().next();// www  .j  av a  2 s .  c o  m
    execCalicoCommand(slave, addPool);

    // Create a DynamicGroup with all attached entities
    EntitySpec<DynamicGroup> networkSpec = EntitySpec.create(DynamicGroup.class)
            .configure(DynamicGroup.ENTITY_FILTER,
                    Predicates.and(
                            Predicates.not(Predicates.or(Predicates.instanceOf(MarathonTask.class),
                                    Predicates.instanceOf(DelegateEntity.class))),
                            MesosUtils.sameCluster(getMesosCluster()), SdnUtils.attachedToNetwork(networkId)))
            .displayName(network.getDisplayName());
    DynamicGroup subnet = sensors().get(SDN_APPLICATIONS).addMemberChild(networkSpec);
    subnet.sensors().set(VirtualNetwork.NETWORK_ID, networkId);
    network.sensors().set(VirtualNetwork.NETWORKED_APPLICATIONS, subnet);

    sensors().get(SDN_NETWORKS).addMember(network);
}