Example usage for com.google.common.collect Iterables any

List of usage examples for com.google.common.collect Iterables any

Introduction

In this page you can find the example usage for com.google.common.collect Iterables any.

Prototype

public static <T> boolean any(Iterable<T> iterable, Predicate<? super T> predicate) 

Source Link

Document

Returns true if any element in iterable satisfies the predicate.

Usage

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

/**
 * Check if this {@link DDiagramElement} is directly filtered by an
 * activated filter.//from   www.  j  ava  2s.  com
 * 
 * @return true if the given element is filtered.
 */
public boolean isFiltered() {
    return Iterables.any(element.getGraphicalFilters(), Predicates.instanceOf(AppliedCompositeFilters.class));
}

From source file:google.registry.flows.ResourceFlowUtils.java

/** Check whether an asynchronous delete would obviously fail, and throw an exception if so. */
public static <R extends EppResource> void failfastForAsyncDelete(final String targetId, final DateTime now,
        final Class<R> resourceClass, final Function<DomainBase, ImmutableSet<?>> getPotentialReferences)
        throws EppException {
    // Enter a transactionless context briefly.
    EppException failfastException = ofy().doTransactionless(new Work<EppException>() {
        @Override//from   ww  w . j  a  v a  2  s  .c om
        public EppException run() {
            final ForeignKeyIndex<R> fki = ForeignKeyIndex.load(resourceClass, targetId, now);
            if (fki == null) {
                return new ResourceDoesNotExistException(resourceClass, targetId);
            }
            // Query for the first few linked domains, and if found, actually load them. The query is
            // eventually consistent and so might be very stale, but the direct load will not be stale,
            // just non-transactional. If we find at least one actual reference then we can reliably
            // fail. If we don't find any, we can't trust the query and need to do the full mapreduce.
            List<Key<DomainBase>> keys = queryDomainsUsingResource(resourceClass, fki.getResourceKey(), now,
                    FAILFAST_CHECK_COUNT);
            Predicate<DomainBase> predicate = new Predicate<DomainBase>() {
                @Override
                public boolean apply(DomainBase domain) {
                    return getPotentialReferences.apply(domain).contains(fki.getResourceKey());
                }
            };
            return Iterables.any(ofy().load().keys(keys).values(), predicate)
                    ? new ResourceToDeleteIsReferencedException()
                    : null;
        }
    });
    if (failfastException != null) {
        throw failfastException;
    }
}

From source file:org.raml.v2.internal.impl.commons.model.type.TypeDeclaration.java

/**
 * True if the node is a global named type declaration as opposed to an inline/anonymous declaration. This is computed based on the parent of the current type declaration node, i.e.
 * if its parent is one of the global named type declaration nodes possible.
 *
 * @return <code>true</code> if the node is a global named type declaration as opposed to an inline/anonymous declaration, <code>false</code> otherwise
 *///from  w  ww  . j av  a 2s. c  om
private boolean isGlobalNamedTypeDeclarationNode() {
    final Node parent = node.getParent();
    final Node rootNode = node.getRootNode();

    return Iterables.any(GLOBAL_NAMED_TYPE_DECLARATION_NODE_NAMES, new Predicate<String>() {

        @Override
        public boolean apply(final String name) {
            return parent == rootNode.get(name);
        }
    });
}

From source file:io.redlink.sdk.impl.analysis.model.Enhancements.java

/**
 * Returns true if the contents has been categorized with a category identified by the URI passed by parameter
 *
 * @param conceptURI URI of the category concept
 * @return// w ww. jav a2 s .  co m
 */
public boolean hasCategory(final String conceptURI) {
    return Iterables.any(getCategories(), new Predicate<TopicAnnotation>() {

        @Override
        public boolean apply(TopicAnnotation ta) {
            return ta.getTopicReference().equals(conceptURI);
        }

    });
}

From source file:org.eclipse.viatra.query.patternlanguage.validation.PatternLanguageJavaValidator.java

@Check
public void checkPrivatePatternCall(PatternCall call) {
    final Pattern calledPattern = call.getPatternRef();
    if (calledPattern != null) {
        if (Iterables.any(calledPattern.getModifiers(), new Predicate<Modifiers>() {

            @Override//from w  ww.ja va  2 s  . c om
            public boolean apply(Modifiers input) {
                return input.isPrivate();
            }
        }) && calledPattern.eResource() != call.eResource()) {
            error(String.format("The pattern %s is not visible.", getFormattedPattern(calledPattern)),
                    PatternLanguagePackage.Literals.PATTERN_CALL__PATTERN_REF,
                    IssueCodes.PRIVATE_PATTERN_CALLED);
        }
    }
}

From source file:com.google.devtools.build.lib.rules.objc.BundleSupport.java

/**
 * Returns true if this bundle is targeted to {@link TargetDeviceFamily#WATCH}, false otherwise.
 *//*from ww w .j  a  v  a2  s.  c  o m*/
boolean isBuildingForWatch() {
    return Iterables.any(targetDeviceFamilies(), new Predicate<TargetDeviceFamily>() {
        @Override
        public boolean apply(TargetDeviceFamily targetDeviceFamily) {
            return targetDeviceFamily.name().equalsIgnoreCase(TargetDeviceFamily.WATCH.getNameInRule());
        }
    });
}

From source file:heros.utilities.FieldSensitiveTestHelper.java

public InterproceduralCFG<Statement, TestMethod> buildIcfg() {
    return new InterproceduralCFG<Statement, TestMethod>() {

        @Override//from   www.  ja  v a  2  s . c o  m
        public boolean isStartPoint(Statement stmt) {
            return method2startPoint.values().contains(stmt);
        }

        @Override
        public boolean isFallThroughSuccessor(Statement stmt, Statement succ) {
            throw new IllegalStateException();
        }

        @Override
        public boolean isExitStmt(Statement stmt) {
            for (ReturnEdge edge : returnEdges) {
                if (edge.exitStmt.equals(stmt))
                    return true;
            }
            return false;
        }

        @Override
        public boolean isCallStmt(final Statement stmt) {
            return Iterables.any(callEdges, new Predicate<CallEdge>() {
                @Override
                public boolean apply(CallEdge edge) {
                    return edge.callSite.equals(stmt);
                }
            });
        }

        @Override
        public boolean isBranchTarget(Statement stmt, Statement succ) {
            throw new IllegalStateException();
        }

        @Override
        public List<Statement> getSuccsOf(Statement n) {
            LinkedList<Statement> result = Lists.newLinkedList();
            for (NormalEdge edge : normalEdges) {
                if (edge.includeInCfg && edge.unit.equals(n))
                    result.add(edge.succUnit);
            }
            return result;
        }

        @Override
        public List<Statement> getPredsOf(Statement stmt) {
            LinkedList<Statement> result = Lists.newLinkedList();
            for (NormalEdge edge : normalEdges) {
                if (edge.includeInCfg && edge.succUnit.equals(stmt))
                    result.add(edge.unit);
            }
            return result;
        }

        @Override
        public Collection<Statement> getStartPointsOf(TestMethod m) {
            return method2startPoint.get(m);
        }

        @Override
        public Collection<Statement> getReturnSitesOfCallAt(Statement n) {
            Set<Statement> result = Sets.newHashSet();
            for (Call2ReturnEdge edge : call2retEdges) {
                if (edge.includeInCfg && edge.callSite.equals(n))
                    result.add(edge.returnSite);
            }
            for (ReturnEdge edge : returnEdges) {
                if (edge.includeInCfg && edge.callSite.equals(n))
                    result.add(edge.returnSite);
            }
            return result;
        }

        @Override
        public TestMethod getMethodOf(Statement n) {
            if (stmt2method.containsKey(n))
                return stmt2method.get(n);
            else
                throw new IllegalArgumentException("Statement " + n + " is not defined in any method.");
        }

        @Override
        public Set<Statement> getCallsFromWithin(TestMethod m) {
            throw new IllegalStateException();
        }

        @Override
        public Collection<Statement> getCallersOf(TestMethod m) {
            Set<Statement> result = Sets.newHashSet();
            for (CallEdge edge : callEdges) {
                if (edge.includeInCfg && edge.destinationMethod.equals(m)) {
                    result.add(edge.callSite);
                }
            }
            for (ReturnEdge edge : returnEdges) {
                if (edge.includeInCfg && edge.calleeMethod.equals(m)) {
                    result.add(edge.callSite);
                }
            }
            return result;
        }

        @Override
        public Collection<TestMethod> getCalleesOfCallAt(Statement n) {
            List<TestMethod> result = Lists.newLinkedList();
            for (CallEdge edge : callEdges) {
                if (edge.includeInCfg && edge.callSite.equals(n)) {
                    result.add(edge.destinationMethod);
                }
            }
            return result;
        }

        @Override
        public Set<Statement> allNonCallStartNodes() {
            throw new IllegalStateException();
        }
    };
}

From source file:uk.co.unclealex.executable.generator.scan.ExecutableAnnotationInformationFinderImpl.java

/**
 * Check to see if the command class is instantiable and return any declared
 * Guice Modules.//from   w  w w. java2  s  .  co  m
 * 
 * @param clazz
 *          The command class.
 * @param executable
 *          The {@link Executable} annotation that has been found.
 * @return The array of Guice modules declared by the annotation.
 * @throws CommandNotInstantiableExecutableScanException
 *           Thrown if the command class cannot be instantiatied.
 * @throws NonGuiceModulesReferencedException Thrown if non-Guice {@link Module}s are found. 
 */
@SuppressWarnings("unchecked")
protected Class<? extends Module>[] extractGuiceModules(Class<?> clazz, Method annotatedMethod,
        Executable executable)
        throws CommandNotInstantiableExecutableScanException, NonGuiceModulesReferencedException {
    Class<?>[] guiceModules = executable.value();
    List<Class<?>> nonGuiceModules = Lists.newArrayList(
            Iterables.filter(Arrays.asList(guiceModules), Predicates.not(new IsGuiceModulePredicate())));
    if (!nonGuiceModules.isEmpty()) {
        throw new NonGuiceModulesReferencedException(clazz, annotatedMethod, nonGuiceModules);
    }
    Predicate<Constructor<?>> isInstantiablePredicate = new IsDefaultConstructor();
    if (guiceModules.length != 0) {
        isInstantiablePredicate = Predicates.or(isInstantiablePredicate,
                IsConstructorAnnotated.with(javax.inject.Inject.class));
        isInstantiablePredicate = Predicates.or(isInstantiablePredicate,
                IsConstructorAnnotated.with(com.google.inject.Inject.class));
    }
    if (!Iterables.any(Arrays.asList(clazz.getConstructors()), isInstantiablePredicate)) {
        throw new CommandNotInstantiableExecutableScanException(clazz);
    }
    return (Class<? extends Module>[]) guiceModules;
}

From source file:org.eclipse.sirius.diagram.ui.graphical.edit.policies.SiriusContainerEditPolicy.java

/**
 * Override this method for version before GMF 1.5.0 with Eclipse 3.6.
 * Indeed, in the previous version there is a test that launch arrange only
 * with more that one element. But we want to launch arrange even with one
 * element to have always the same result (one or more new elements) : to
 * avoid overlaps with pinned elements for example.<BR>
 * {@inheritDoc}//from w  ww . j  a va  2 s .c o m
 * 
 * @see org.eclipse.gmf.runtime.diagram.ui.editpolicies.ContainerEditPolicy#getArrangeCommand(org.eclipse.gmf.runtime.diagram.ui.requests.ArrangeRequest)
 */
@Override
protected Command getArrangeCommand(ArrangeRequest request) {
    Command commandToReturn = null;
    if (GMFRuntimeCompatibility.hasGMFPluginReleaseBetween1_2_0_And_1_3_3()) {
        if (RequestConstants.REQ_ARRANGE_DEFERRED.equals(request.getType())) {
            String layoutType = request.getLayoutType();
            TransactionalEditingDomain editingDomain = ((IGraphicalEditPart) getHost()).getEditingDomain();
            return new ICommandProxy(new DeferredLayoutCommand(editingDomain,
                    request.getViewAdaptersToArrange(), (IGraphicalEditPart) getHost(), layoutType));
        }

        String layoutDesc = request.getLayoutType() != null ? request.getLayoutType() : LayoutType.DEFAULT;
        boolean offsetFromBoundingBox = false;
        List editparts = new ArrayList();

        if ((ActionIds.ACTION_ARRANGE_ALL.equals(request.getType()))
                || (ActionIds.ACTION_TOOLBAR_ARRANGE_ALL.equals(request.getType()))) {
            editparts = ((IGraphicalEditPart) getHost()).getChildren();
            request.setPartsToArrange(editparts);
        }
        if ((ActionIds.ACTION_ARRANGE_SELECTION.equals(request.getType()))
                || (ActionIds.ACTION_TOOLBAR_ARRANGE_SELECTION.equals(request.getType()))) {
            editparts = request.getPartsToArrange();
            // Just comment this line to launch an arrange command even with
            // one elemnt
            // if (editparts.size() < 2
            // || !(((GraphicalEditPart) ((EditPart) editparts.get(0))
            // .getParent()).getContentPane().getLayoutManager() instanceof
            // XYLayout)) {
            // return null;
            // }
            offsetFromBoundingBox = true;
        }
        if (RequestConstants.REQ_ARRANGE_RADIAL.equals(request.getType())) {
            editparts = request.getPartsToArrange();
            offsetFromBoundingBox = true;
            layoutDesc = LayoutType.RADIAL;
        }
        if (editparts.isEmpty())
            return null;
        List nodes = new ArrayList(editparts.size());
        ListIterator li = editparts.listIterator();
        while (li.hasNext()) {
            IGraphicalEditPart ep = (IGraphicalEditPart) li.next();
            View view = ep.getNotationView();
            if (ep.isActive() && view instanceof Node) {
                Rectangle bounds = ep.getFigure().getBounds();
                nodes.add(new LayoutNode((Node) view, bounds.width, bounds.height));
            }
        }
        if (nodes.isEmpty()) {
            return null;
        }

        List hints = new ArrayList(2);
        hints.add(layoutDesc);
        hints.add(getHost());
        IAdaptable layoutHint = new ObjectAdapter(hints);
        final Runnable layoutRun = layoutNodes(nodes, offsetFromBoundingBox, layoutHint);

        boolean isSnap = true;
        // retrieves the preference store from the first edit part
        IGraphicalEditPart firstEditPart = (IGraphicalEditPart) editparts.get(0);
        if (firstEditPart.getViewer() instanceof DiagramGraphicalViewer) {
            IPreferenceStore preferenceStore = ((DiagramGraphicalViewer) firstEditPart.getViewer())
                    .getWorkspaceViewerPreferenceStore();
            if (preferenceStore != null) {
                isSnap = preferenceStore.getBoolean(WorkspaceViewerProperties.SNAPTOGRID);
            }
        }

        // the snapCommand still invokes proper calculations if snap to grid
        // is turned off, this additional check
        // is intended to make the code more appear more logical

        TransactionalEditingDomain editingDomain = ((IGraphicalEditPart) getHost()).getEditingDomain();
        CompositeTransactionalCommand ctc = new CompositeTransactionalCommand(editingDomain,
                StringStatics.BLANK);
        if (layoutRun instanceof IInternalLayoutRunnable) {
            ctc.add(new CommandProxy(((IInternalLayoutRunnable) layoutRun).getCommand()));
        } else {
            ctc.add(new AbstractTransactionalCommand(editingDomain, StringStatics.BLANK, null) {
                @Override
                protected CommandResult doExecuteWithResult(IProgressMonitor progressMonitor, IAdaptable info)
                        throws ExecutionException {
                    layoutRun.run();
                    return CommandResult.newOKCommandResult();
                }
            });
        }
        if (isSnap) {
            Command snapCmd = getSnapCommand(request);
            if (snapCmd != null) {
                ctc.add(new CommandProxy(getSnapCommand(request)));
            }
        }
        commandToReturn = new ICommandProxy(ctc);
    } else {
        commandToReturn = super.getArrangeCommand(request);
    }

    if ((ActionIds.ACTION_ARRANGE_SELECTION.equals(request.getType()))
            || (ActionIds.ACTION_TOOLBAR_ARRANGE_SELECTION.equals(request.getType()))) {
        if (Iterables.any(request.getPartsToArrange(), isRegionEditPart)) {
            return UnexecutableCommand.INSTANCE;
        }
    }

    // We add a Command to center edges that need to be at the end of the
    // layout.
    if (commandToReturn != null) {
        EditPart host = getHost();
        if (host instanceof GraphicalEditPart) {
            CenterEdgeLayoutCommand centerEdgeLayoutCommand = new CenterEdgeLayoutCommand(
                    (GraphicalEditPart) host);
            commandToReturn = commandToReturn.chain(new ICommandProxy(centerEdgeLayoutCommand));
        }
    }
    return commandToReturn;
}

From source file:gov.nih.nci.firebird.service.protocol.ProtocolModificationDetector.java

private boolean containsLeadOrganization(Set<ProtocolLeadOrganization> leadOrganizations,
        final ProtocolLeadOrganization leadOrganization) {
    return Iterables.any(leadOrganizations, new Predicate<ProtocolLeadOrganization>() {
        @Override/*  w ww  .  j a  v  a 2 s .  com*/
        public boolean apply(ProtocolLeadOrganization input) {
            return input.equals(leadOrganization);
        }
    });
}