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.elk.layered.compound.CompoundGraphPostprocessor.java

/**
 * {@inheritDoc}/* ww  w  .ja  v a2  s .  com*/
 */
public void process(final LGraph graph, final IElkProgressMonitor monitor) {
    monitor.begin("Compound graph postprocessor", 1);

    // whether bend points should be added whenever crossing a hierarchy boundary
    boolean addUnnecessaryBendpoints = graph.getProperty(Properties.ADD_UNNECESSARY_BENDPOINTS);

    // restore the cross-hierarchy map that was built by the preprocessor
    Multimap<LEdge, CrossHierarchyEdge> crossHierarchyMap = graph
            .getProperty(InternalProperties.CROSS_HIERARCHY_MAP);

    // remember all dummy edges we encounter; these need to be removed at the end
    Set<LEdge> dummyEdges = Sets.newHashSet();

    // iterate over all original edges
    for (LEdge origEdge : crossHierarchyMap.keySet()) {
        List<CrossHierarchyEdge> crossHierarchyEdges = new ArrayList<CrossHierarchyEdge>(
                crossHierarchyMap.get(origEdge));

        // put the cross-hierarchy edges in proper order from source to target
        Collections.sort(crossHierarchyEdges, new CrossHierarchyEdgeComparator(graph));
        LPort sourcePort = crossHierarchyEdges.get(0).getActualSource();
        LPort targetPort = crossHierarchyEdges.get(crossHierarchyEdges.size() - 1).getActualTarget();
        origEdge.getBendPoints().clear();

        // determine the reference graph for all bend points
        LNode referenceNode = sourcePort.getNode();
        LGraph referenceGraph;
        if (LGraphUtil.isDescendant(targetPort.getNode(), referenceNode)) {
            referenceGraph = referenceNode.getProperty(InternalProperties.NESTED_LGRAPH);
        } else {
            referenceGraph = referenceNode.getGraph();
        }

        // check whether there are any junction points
        KVectorChain junctionPoints = origEdge.getProperty(LayoutOptions.JUNCTION_POINTS);
        if (Iterables.any(crossHierarchyEdges, HAS_JUNCTION_POINTS_PREDICATE)) {
            // if so, make sure the original edge has an empty non-null junction point list
            if (junctionPoints == null) {
                junctionPoints = new KVectorChain();
                origEdge.setProperty(LayoutOptions.JUNCTION_POINTS, junctionPoints);
            } else {
                junctionPoints.clear();
            }
        } else if (junctionPoints != null) {
            origEdge.setProperty(LayoutOptions.JUNCTION_POINTS, null);
        }

        // apply the computed layouts to the cross-hierarchy edge
        KVector lastPoint = null;
        for (CrossHierarchyEdge chEdge : crossHierarchyEdges) {
            // transform all coordinates from the graph of the dummy edge to the reference graph
            KVector offset = new KVector();
            LGraphUtil.changeCoordSystem(offset, chEdge.getGraph(), referenceGraph);

            LEdge ledge = chEdge.getEdge();
            KVectorChain bendPoints = new KVectorChain();
            bendPoints.addAllAsCopies(0, ledge.getBendPoints());
            bendPoints.offset(offset);

            // Note: if an NPE occurs here, that means KLay Layered has replaced the original edge
            KVector sourcePoint = new KVector(ledge.getSource().getAbsoluteAnchor());
            KVector targetPoint = new KVector(ledge.getTarget().getAbsoluteAnchor());
            sourcePoint.add(offset);
            targetPoint.add(offset);

            if (lastPoint != null) {
                KVector nextPoint;
                if (bendPoints.isEmpty()) {
                    nextPoint = targetPoint;
                } else {
                    nextPoint = bendPoints.getFirst();
                }

                // we add the source point as a bend point to properly connect the hierarchy levels
                // either if the last point of the previous hierarchy edge segment is a certain
                // level of tolerance away or if we are required to add unnecessary bend points
                boolean xDiffEnough = Math
                        .abs(lastPoint.x - nextPoint.x) > OrthogonalRoutingGenerator.TOLERANCE;
                boolean yDiffEnough = Math
                        .abs(lastPoint.y - nextPoint.y) > OrthogonalRoutingGenerator.TOLERANCE;

                if ((!addUnnecessaryBendpoints && xDiffEnough && yDiffEnough)
                        || (addUnnecessaryBendpoints && (xDiffEnough || yDiffEnough))) {

                    origEdge.getBendPoints().add(sourcePoint);
                }
            }

            origEdge.getBendPoints().addAll(bendPoints);

            if (bendPoints.isEmpty()) {
                lastPoint = sourcePoint;
            } else {
                lastPoint = bendPoints.getLast();
            }

            // copy junction points
            KVectorChain ledgeJPs = ledge.getProperty(LayoutOptions.JUNCTION_POINTS);
            if (ledgeJPs != null) {
                KVectorChain jpCopies = new KVectorChain();
                jpCopies.addAllAsCopies(0, ledgeJPs);
                jpCopies.offset(offset);

                junctionPoints.addAll(jpCopies);
            }

            // add offset to target port with a special property
            if (chEdge.getActualTarget() == targetPort) {
                if (targetPort.getNode().getGraph() != chEdge.getGraph()) {
                    // the target port is in a different coordinate system -- recompute the offset
                    offset = new KVector();
                    LGraphUtil.changeCoordSystem(offset, targetPort.getNode().getGraph(), referenceGraph);
                }
                origEdge.setProperty(InternalProperties.TARGET_OFFSET, offset);
            }

            // copy labels back to the original edge
            Iterator<LLabel> labelIterator = ledge.getLabels().listIterator();
            while (labelIterator.hasNext()) {
                LLabel currLabel = labelIterator.next();
                if (currLabel.getProperty(InternalProperties.ORIGINAL_LABEL_EDGE) != origEdge) {
                    continue;
                }

                LGraphUtil.changeCoordSystem(currLabel.getPosition(), ledge.getSource().getNode().getGraph(),
                        referenceGraph);
                labelIterator.remove();
                origEdge.getLabels().add(currLabel);
            }

            // remember the dummy edge for later removal (dummy edges may be in use by several
            // different original edges, which is why we cannot just go and remove it now)
            dummyEdges.add(ledge);
        }

        // restore the original source port and target port
        origEdge.setSource(sourcePort);
        origEdge.setTarget(targetPort);
    }

    // remove the dummy edges from the graph (dummy ports and dummy nodes are retained)
    for (LEdge dummyEdge : dummyEdges) {
        dummyEdge.setSource(null);
        dummyEdge.setTarget(null);
    }

    monitor.done();
}

From source file:com.palantir.common.collect.IterableView.java

public boolean any(Predicate<? super T> predicate) {
    return Iterables.any(delegate(), predicate);
}

From source file:com.mycelium.paymentrequest.PaymentRequestInformation.java

public static PaymentRequestInformation fromRawPaymentRequest(byte[] rawPaymentRequest, KeyStore keyStore,
        final NetworkParameters networkParameters) {

    if (rawPaymentRequest.length > MAX_MESSAGE_SIZE) {
        throw new PaymentRequestException("payment request too large");
    }/* ww  w .jav  a2s .  co m*/

    try {
        Wire wire = new Wire();

        PaymentRequest paymentRequest = wire.parseFrom(rawPaymentRequest, PaymentRequest.class);
        if (paymentRequest == null) {
            throw new PaymentRequestException("unable to parse the payment request");
        }

        Integer version = Wire.get(paymentRequest.payment_details_version,
                PaymentRequest.DEFAULT_PAYMENT_DETAILS_VERSION);
        if (version != 1) {
            throw new PaymentRequestException("unsupported payment details version " + version);
        }

        PaymentDetails paymentDetails = wire.parseFrom(paymentRequest.serialized_payment_details.toByteArray(),
                PaymentDetails.class);
        if (paymentDetails == null) {
            throw new PaymentRequestException("unable to parse the payment details");
        }

        // check if its for the correct bitcoin network (testnet/prodnet)
        if (MAIN_NET_MONIKER
                .equals(Wire.get(paymentDetails.network, PaymentDetails.DEFAULT_NETWORK)) != networkParameters
                        .isProdnet()) {
            throw new PaymentRequestException(
                    "wrong network: " + Wire.get(paymentDetails.network, PaymentDetails.DEFAULT_NETWORK));
        }

        if (Wire.get(paymentDetails.outputs, PaymentDetails.DEFAULT_OUTPUTS).size() == 0) {
            throw new PaymentRequestException("no outputs specified");
        }

        // check if we are able to parse all output scripts
        // we might need to improve this later on to provide some flexibility, but until there is are use-cases
        // prevent users from sending coins to maybe unspendable outputs
        OutputList transactionOutputs = getTransactionOutputs(paymentDetails);
        boolean containsStrangeOutput = Iterables.any(transactionOutputs, new Predicate<TransactionOutput>() {
            @Override
            public boolean apply(TransactionOutput input) {
                // search if we got a strange output or a null address as destination
                return input.script instanceof ScriptOutputStrange || input.script.getAddress(networkParameters)
                        .equals(Address.getNullAddress(networkParameters));
            }
        });

        if (containsStrangeOutput) {
            throw new PaymentRequestException("unable to parse one of the output scripts");
        }

        X509Certificates certificates;
        String pki_type = Wire.get(paymentRequest.pki_type, PaymentRequest.DEFAULT_PKI_TYPE);
        if (!PKI_NONE.equals(pki_type)) {
            if (!(pki_type.equals(PKI_X509_SHA256) || pki_type.equals(PKI_X509_SHA1))) {
                throw new PaymentRequestException("unsupported pki type " + pki_type);
            }

            if (paymentRequest.pki_data == null || paymentRequest.pki_data.size() == 0) {
                throw new PaymentRequestException("no pki data available");
            }

            if (paymentRequest.signature == null || paymentRequest.signature.size() == 0) {
                throw new PaymentRequestException("no signature available");
            }

            certificates = wire.parseFrom(paymentRequest.pki_data.toByteArray(), X509Certificates.class);
            PkiVerificationData pkiVerificationData = verifySignature(paymentRequest, certificates, keyStore);
            return new PaymentRequestInformation(paymentRequest, paymentDetails, pkiVerificationData,
                    rawPaymentRequest);

        } else {
            return new PaymentRequestInformation(paymentRequest, paymentDetails, null, rawPaymentRequest);
        }

    } catch (IOException e) {
        throw new PaymentRequestException("invalid formatted payment request", e);
    }
}

From source file:org.eclipse.sirius.diagram.ui.tools.internal.commands.ToggleFoldingStateCommand.java

private void addFilterType(DDiagramElement element, GraphicalFilter filter) {
    if (!Iterables.any(element.getGraphicalFilters(), Predicates.instanceOf(filter.getClass()))) {
        element.getGraphicalFilters().add(filter);
    }/*from   www  .  jav  a2 s .c  o m*/
}

From source file:org.opentestsystem.authoring.testauth.publish.AdministrationPublisherHelper.java

@Override
public TestSpecification<Administration> createTestSpec(final Assessment assessment, final DateTime publishDate,
        final String version, final Purpose purpose,
        final TestSpecification<? extends PurposeBaseContent> seedingTestSpec) {
    final long start = System.currentTimeMillis();
    long dataRetrieval = System.currentTimeMillis(), itemPoolCreation = System.currentTimeMillis(),
            blueprintCreation = System.currentTimeMillis();
    long formCreation = System.currentTimeMillis(), segmentCreation = System.currentTimeMillis(),
            poolCreation = System.currentTimeMillis(),
            blueprintReferenceMapCreation = System.currentTimeMillis();

    final TestSpecification<Administration> testSpec = doGeneralTestSpecificationSetup(assessment, publishDate,
            version, purpose, Administration.class);

    final boolean seedIsComplete = seedingTestSpec != null && seedingTestSpec.getComplete() != null;
    final Administration specContent = seedIsComplete ? new Administration(seedingTestSpec.getComplete())
            : new Administration();
    if (!seedIsComplete) {
        final String assessmentId = assessment.getId();
        final List<Item> itemList = retrieveItemsForAssessment(assessmentId);
        final List<Segment> segmentList = retrieveSegmentList(assessmentId);
        final List<BlueprintElement> blueprintElementList = getActiveBlueprintElements(assessmentId);
        specContent.setBlueprintElementList(blueprintElementList);
        final List<AffinityGroup> affinityGroupList = getActiveAffinityGroups(assessmentId);
        dataRetrieval = System.currentTimeMillis();
        final Map<BlueprintReferenceType, Map<String, String>> blueprintReferenceMap = buildBlueprintReferenceMap(
                assessment, segmentList, blueprintElementList, affinityGroupList);
        specContent.setBlueprintReferenceMap(blueprintReferenceMap);
        blueprintReferenceMapCreation = System.currentTimeMillis();

        // ITEMPOOL
        specContent//from  w w  w.  j  a v a2 s .  com
                .setItemPool(setupItemPoolData(assessment, itemList, segmentList, affinityGroupList, version));
        final Map<String, TestItem> testItemMap = buildTestItemMap(specContent.getItemPool().getTestItemList());
        itemPoolCreation = System.currentTimeMillis();

        // BLUEPRINT (counts, different levels of the hierarchy)
        specContent.setTestBlueprintList(
                setupBlueprintData(assessment, itemList, segmentList, blueprintElementList, affinityGroupList));
        blueprintCreation = System.currentTimeMillis();

        // SEGMENT
        specContent.setAdministrationSegmentList(setupAdminSegmentData(assessment, itemList, segmentList,
                specContent.getTestBlueprintList(), blueprintElementList, affinityGroupList));
        segmentCreation = System.currentTimeMillis();

        // FORM
        formCreation = segmentCreation;
        if (Iterables.any(segmentList, FIXEDFORM_SEGMENT_FILTER)) {
            specContent.setTestFormList(setupTestFormData(assessment, segmentList, itemList, testItemMap));
            formCreation = System.currentTimeMillis();
        }

        // top-level pool property
        specContent.setPoolPropertyList(
                buildTopLevelPoolPropertyList(assessmentId, itemList, segmentList, testItemMap));
        poolCreation = System.currentTimeMillis();
    }

    testSpec.setContent(specContent);
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("data retrieval: " + (dataRetrieval - start) + "ms\n" + "reference map creation: "
                + (blueprintReferenceMapCreation - dataRetrieval) + "ms\n" + "item pool: "
                + (itemPoolCreation - blueprintReferenceMapCreation) + "ms\n" + "blueprint: "
                + (blueprintCreation - itemPoolCreation) + "ms\n" + "admin segment: "
                + (segmentCreation - blueprintCreation) + "ms\n" + "form: " + (formCreation - segmentCreation)
                + "ms\n" + "test poolproperty: " + (poolCreation - formCreation) + "ms\n" + "total time: "
                + (System.currentTimeMillis() - start) + "ms");
    }
    return testSpec;
}

From source file:org.pantsbuild.tools.junit.impl.Util.java

public static boolean isTestClass(final Class<?> clazz) {
    // Must be a public concrete class to be a runnable junit Test.
    if (clazz.isInterface() || Modifier.isAbstract(clazz.getModifiers())
            || !Modifier.isPublic(clazz.getModifiers())) {
        return false;
    }//ww w  . j  av  a 2  s. c om

    // The class must have some public constructor to be instantiated by the runner being used
    if (!Iterables.any(Arrays.asList(clazz.getConstructors()), IS_PUBLIC_CONSTRUCTOR)) {
        return false;
    }

    if (isJunit3Test(clazz)) {
        return true;
    }

    // Support classes using junit 4.x custom runners.
    if (isUsingCustomRunner(clazz)) {
        return true;
    }

    if (ScalaTestUtil.isScalaTestTest(clazz)) {
        return true;
    }

    // Support junit 4.x @Test annotated methods.
    return Iterables.any(Arrays.asList(clazz.getMethods()), IS_ANNOTATED_TEST_METHOD);
}

From source file:com.puppetlabs.geppetto.pp.dsl.tests.utils.DiagnosticsAsserter.java

public void assertAny(Iterable<Diagnostic> asserted, DiagnosticPredicate... predicates) {
    for (DiagnosticPredicate predicate : predicates)
        if (Iterables.any(asserted, predicate))
            return;
    throw new ComparisonFailure("No predicate (any expected) matches diagnostics", Arrays.toString(predicates),
            diagnosticsToString(asserted));

}

From source file:org.calrissian.mango.collect.FluentCloseableIterable.java

/**
 * Returns {@code true} if any element in this fluent iterable satisfies the predicate.
 *//*from w  w  w .  jav a 2  s.  co  m*/
public final boolean anyMatch(Predicate<? super T> predicate) {
    return Iterables.any(this, predicate);
}

From source file:org.killbill.billing.payment.core.sm.control.DefaultControlCompleted.java

private boolean isUnknownTransaction() {
    if (paymentStateContext.getCurrentTransaction() != null) {
        return paymentStateContext.getCurrentTransaction().getTransactionStatus() == TransactionStatus.UNKNOWN;
    } else {/*  ww  w . j av  a  2  s .c o  m*/
        final List<PaymentTransactionModelDao> transactions = retryablePaymentAutomatonRunner.getPaymentDao()
                .getPaymentTransactionsByExternalKey(paymentStateContext.getPaymentTransactionExternalKey(),
                        paymentStateContext.getInternalCallContext());
        return Iterables.any(transactions, new Predicate<PaymentTransactionModelDao>() {
            @Override
            public boolean apply(final PaymentTransactionModelDao input) {
                return input.getTransactionStatus() == TransactionStatus.UNKNOWN &&
                // Not strictly required
                // (Note, we don't match on AttemptId as it is risky, the row on disk would match the first attempt, not necessarily the current one)
                input.getAccountRecordId()
                        .equals(paymentStateContext.getInternalCallContext().getAccountRecordId());
            }
        });
    }
}

From source file:com.google.template.soy.types.aggregate.UnionType.java

/** Returns true if the union includes the null type. */
public boolean isNullable() {
    return Iterables.any(members, IS_NULL);
}