Example usage for java.util Collection contains

List of usage examples for java.util Collection contains

Introduction

In this page you can find the example usage for java.util Collection contains.

Prototype

boolean contains(Object o);

Source Link

Document

Returns true if this collection contains the specified element.

Usage

From source file:de.iteratec.iteraplan.businesslogic.exchange.common.vbb.impl.RecursiveCluster.java

/**
 * Creates a {@link Predicate} which filters out all instances whose ID is not contained in the {@code ids} collection.
 *//*from  ww  w  .j  ava2 s.  c om*/
private static Predicate<UniversalModelExpression> createFilterPredicate(final Collection<BigInteger> ids) {
    return new Predicate<UniversalModelExpression>() {
        public boolean apply(UniversalModelExpression input) {
            return ids.contains(input.getValue(UniversalTypeExpression.ID_PROPERTY));
        }
    };
}

From source file:javadepchecker.Main.java

private static boolean depNeeded(String pkg, Collection<String> deps) throws IOException {
    Collection<String> jars = getPackageJars(pkg);
    // We have a virtual with VM provider here
    if (jars.size() == 0) {
        return true;
    }/*from ww  w. j a  v  a2 s.com*/
    for (String jarName : jars) {
        JarFile jar = new JarFile(jarName);
        for (Enumeration<JarEntry> e = jar.entries(); e.hasMoreElements();) {
            String name = e.nextElement().getName();
            if (deps.contains(name)) {
                return true;
            }
        }
    }
    return false;
}

From source file:podd.util.PoddWebappTestUtil.java

public static <T> void checkMembers(Collection<T> collection, T... instances) {
    if (null == instances) {
        assertTrue(collection.isEmpty());
    } else {//from   w  w w .  java 2s . co  m
        assertEquals(instances.length, collection.size());
        for (T bundle : instances) {
            assertTrue(collection.contains(bundle));
        }
    }
}

From source file:net.mojodna.sprout.support.SproutUtils.java

/**
 * Bean initialization method.  Uses reflection to determine properties
 * for which auto-wiring may be appropriate.  Subsequently attempts to
 * retrieve appropriate beans from the WebApplicationContext and set them
 * locally./*from w ww . j  a  va  2 s  .c om*/
 * 
 * @param bean Bean to initialize.
 * @param context WebApplicationContext containing Spring beans.
 * @param clazz Type of Sprout.  This is used to determine which declared
 * methods are candidates for auto-wiring.
 */
public static void initialize(final Object bean, final WebApplicationContext context, final Class clazz) {
    final Collection<Method> methods = SproutUtils.getDeclaredMethods(bean.getClass(), clazz);

    final PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(bean.getClass());
    for (final PropertyDescriptor descriptor : descriptors) {
        final Class type = descriptor.getPropertyType();

        // beans should never be of type String
        // there must be a write method present
        // the write method must exist within the relevant subset of declared methods
        if (!type.equals(String.class) && null != descriptor.getWriteMethod()
                && methods.contains(descriptor.getWriteMethod())) {
            final Object serviceBean = context.getBean(descriptor.getName());
            if (null != serviceBean) {
                try {
                    log.debug("Wiring property '" + descriptor.getName() + "' with bean of type "
                            + serviceBean.getClass().getName());
                    PropertyUtils.setProperty(bean, descriptor.getName(), serviceBean);
                } catch (final IllegalAccessException e) {
                    throw new RuntimeException(e);
                } catch (final InvocationTargetException e) {
                    throw new RuntimeException(e);
                } catch (final NoSuchMethodException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    /**
     * TODO additional lifecycle interface callbacks as defined in BeanFactory
     * should be implemented here
     * @see org.springframework.beans.factory.BeanFactory
     */

    // InitializingBean callback
    if (bean instanceof InitializingBean) {
        try {
            ((InitializingBean) bean).afterPropertiesSet();
        } catch (final Exception e) {
            log.warn("Exception while running afterPropertiesSet() on an InitializingBean: " + e.getMessage(),
                    e);
        }
    }
}

From source file:gate.Utils.java

/** 
 * This method can be used to check if a ProcessingResource has 
 * a chance to be run in the given controller with the current settings.
 * <p>//from ww  w  .j a v a 2s . c om
 * That means that for a non-conditional controller, the method will return
 * true if the PR is part of the controller. For a conditional controller,
 * the method will return true if it is part of the controller and at least
 * once (if the same PR is contained multiple times) it is not disabled.
 * 
 * @param controller 
 * @param pr
 * @return true or false depending on the conditions explained above.
 */
public static boolean isEnabled(Controller controller, ProcessingResource pr) {
    Collection<ProcessingResource> prs = controller.getPRs();
    if (!prs.contains(pr)) {
        return false;
    }
    if (controller instanceof ConditionalSerialController) {
        Collection<RunningStrategy> rss = ((ConditionalSerialController) controller).getRunningStrategies();
        for (RunningStrategy rs : rss) {
            // if we find at least one occurrence of the PR that is not disabled
            // return true
            if (rs.getPR().equals(pr) && rs.getRunMode() != RunningStrategy.RUN_NEVER) {
                return true;
            }
        }
        // if we get here, no occurrence of the PR has found or none that
        // is not disabled, so return false
        return false;
    }
    return true;
}

From source file:hr.fer.spocc.automaton.fsm.DefaultNondeterministicFiniteAutomatonTest.java

private static <T> void checkTransitions(NondeterministicFiniteAutomaton<T> nfa,
        Transition<T>... expectedTransitions) {
    Validate.isTrue(expectedTransitions.length > 0, "Moras dat bar jedan prijelaz, inace nema smisla");
    Collection<Transition<T>> transitions = nfa.getTransitions();
    for (Transition<T> transition : expectedTransitions) {
        Assert.assertTrue(transitions.contains(transition));
    }//from w  w  w.jav a2 s. c  o m
}

From source file:com.iggroup.oss.restdoclet.doclet.util.DocTypeUtils.java

/**
 * Returns as a string a list of attributes plus comments for the given
 * iggroup complex type (or empty string if not iggroup), formatted in an
 * HTML table. This method will recurse if attributes are iggroup complex
 * types/*from w  w  w.ja v a  2  s.  c o  m*/
 * 
 * @param type
 * @param processedTypes
 * @param leafType
 * @return
 */
private static String getTypeDoc(final Type type, HashMap<String, String> processedTypes, Boolean leafType) {

    LOG.info("getTypeDoc " + type + " leafType=" + leafType);

    String typeInfo = "";

    if (isRelevantType(type)) {

        ClassDoc typeDoc = type.asClassDoc();
        typeInfo = processedTypes.get(type.toString());
        if (typeInfo != null) {
            LOG.debug("Found cached typedoc for " + type.typeName() + " - " + typeInfo);
        }
        if (typeInfo == null && typeDoc != null) {

            typeInfo = "";

            // if this is a generic type then recurse with the first type argument
            if (isParameterisedType(type)) {

                LOG.debug("Parameterised type");
                if (type.asClassDoc() != null) {
                    typeInfo = getTypeDoc(
                            type.asParameterizedType()
                                    .typeArguments()[type.asParameterizedType().typeArguments().length - 1],
                            processedTypes, true);
                }

            } else {

                logType(type);

                // put placeholder to stop recursion for self-referential types
                LOG.debug("Starting to cache: " + type.typeName());
                processedTypes.put(type.toString(), "");

                LOG.debug(typeDoc.commentText() + "  " + leafType);
                if (leafType && !typeDoc.commentText().isEmpty()) {
                    typeInfo += "<tr><span class=\"javadoc-header\">" + typeDoc.commentText() + "</span></tr>";
                    LOG.debug(typeInfo);
                }

                if (typeDoc.isEnum()) {

                    LOG.debug("Enum type");
                    typeInfo += getEnumDoc(type);

                } else { // class

                    LOG.debug("Class");
                    // first do base class
                    if (typeDoc.superclass() != null) {

                        LOG.debug("base type = " + typeDoc.superclass().qualifiedName());

                        String baseTypeDoc = getTypeDoc(type.asClassDoc().superclassType(), processedTypes,
                                false);
                        if (!baseTypeDoc.isEmpty()) {
                            LOG.debug("base type DOC = " + baseTypeDoc);
                            typeInfo += baseTypeDoc;
                        }
                    }

                    typeInfo += getPublicConstantDoc(type);

                    Collection<String> getterNames = getGetterNames(type);

                    for (MethodDoc method : typeDoc.methods()) {

                        if (method.isPublic() && getterNames.contains(method.name()) && !ignore(method)) {

                            String attributeInfo = "";
                            String attributeType = method.returnType().simpleTypeName();

                            // check if is this a parameterised type
                            ParameterizedType pt = method.returnType().asParameterizedType();
                            if (pt != null && pt.typeArguments().length > 0) {

                                attributeType += "[";
                                for (int i = 0; i < pt.typeArguments().length; i++) {
                                    attributeType += pt.typeArguments()[i].simpleTypeName();
                                    if (i < pt.typeArguments().length - 1) {
                                        attributeType += ", ";
                                    }
                                }
                                attributeType += "]";

                            }

                            // Check if this is an array
                            attributeType += method.returnType().dimension();

                            final String attributeName = getAttributeNameFromMethod(method.name());

                            attributeInfo += "<td>" + attributeType + " " + attributeName + "</td>";

                            // If type or parameterised type then recurse
                            LOG.debug("Generating attribute doc for " + method.returnType());
                            String attributeTypeDoc = getTypeDoc(method.returnType(), processedTypes, true);
                            if (!attributeTypeDoc.isEmpty()) {
                                LOG.debug("Found attribute doc for " + method.returnType());
                                attributeInfo += "<td>" + attributeTypeDoc + "</td>";

                            } else { // no useful type information, so use whatever's on the attribute doc
                                LOG.debug("Found no attribute doc for " + method.returnType());

                                String fieldDoc = getFieldDoc(type, attributeName, method.commentText());
                                attributeInfo += "<td>" + fieldDoc + "</td>";

                            }

                            if (!attributeInfo.isEmpty()) {
                                typeInfo += "<tr>" + attributeInfo + "</tr>";
                            }

                        }
                    }
                }

                // Wrap in a table tag if this is concrete type
                if (leafType && !typeInfo.isEmpty()) {
                    typeInfo = "<table>" + typeInfo + "</table>";
                }
            }

        }

        LOG.debug("Caching: " + type);
        processedTypes.put(type.toString(), typeInfo);

    }

    if (typeInfo == null) {
        typeInfo = "";
    }
    LOG.debug("XXX " + type.typeName() + " XXX " + typeInfo);
    return typeInfo;

}

From source file:musite.ProteinsUtil.java

/**
 * //from w w  w.  j a va  2  s .com
 * @param pro1
 * @param pro2
 * @param operationOnSites
 * @return
 */
public static Protein mergeProteins(final Protein pro1, final Protein pro2,
        final MergeOperation operationOnSites) {
    if (pro1 == null && pro2 == null)
        return null;

    if (pro2 == null) {
        Protein pro = new ProteinImpl(pro1);
        if (operationOnSites == MergeOperation.INTERSECTION) {
            ResidueAnnotationUtil.removeAnnotations(pro);
        }
        return pro;
    }

    if (pro1 == null) {
        Protein pro = new ProteinImpl(pro2);
        if (operationOnSites == MergeOperation.INTERSECTION || operationOnSites == MergeOperation.DIFFERENCE) {
            ResidueAnnotationUtil.removeAnnotations(pro);
        }
        return pro;
    }

    Protein pro = new ProteinImpl(pro1);
    //        ResidueAnnotationUtil.removeAnnotations(pro);
    //Protein pro = new ProteinImpl(pro1, musite.util.CollectionUtil
    //        .getSet(Protein.ACCESSION, Protein.SEQUENCE)); // common sites

    // merge sequence
    String seq = pro2.getSequence();
    if (seq != null) {
        String currSeq = pro.getSequence();
        if (currSeq == null) {
            pro.setSequence(seq);
        }
        //            else {
        //                if (!currSeq.equalsIgnoreCase(seq)) {
        //                    return pro2;
        //                }
        //            }
    }

    // merge residue annotations
    Set<String> anntypes = ResidueAnnotationUtil.getAnnotationTypes(pro2);
    if (anntypes != null) {
        for (String anntype : anntypes) {
            final MultiMap<Integer, Map<String, Object>> mm = ResidueAnnotationUtil.extractAnnotation(pro2,
                    anntype);
            if (operationOnSites == MergeOperation.UNION) {
                for (Map.Entry<Integer, Collection<Map<String, Object>>> entry : mm.entrySet()) {
                    int site = entry.getKey();
                    Collection<Map<String, Object>> current = ResidueAnnotationUtil.extractAnnotation(pro, site,
                            anntype);
                    for (Map<String, Object> m : entry.getValue()) {
                        if (current == null || !current.contains(m)) // remove redundant annotations
                            ResidueAnnotationUtil.annotate(pro, site, anntype, m);
                    }
                }
            } else {
                ResidueAnnotationUtil.removeAnnotations(pro, anntype,
                        new ResidueAnnotationUtil.AnnotationFilter() {
                            public boolean filter(int loc, Map<String, Object> annotation) {
                                Collection<Map<String, Object>> anns2 = mm.get(loc);
                                return (anns2 != null && anns2.contains(
                                        annotation)) == (operationOnSites == MergeOperation.DIFFERENCE);
                            }
                        });
            }
        }
    }

    Set<String> info = new HashSet<String>(pro2.getInfoMap().keySet());
    info.remove(ResidueAnnotationUtil.RESIDUE_ANNOTATION);
    pro.copyFrom(pro2, false, info); // copy all fields except RESIDUE_ANNOTATION without replacement

    return pro;
}

From source file:de.unisb.cs.st.javalanche.mutation.runtime.testDriver.junit.Junit4Util.java

private static Runner getMethodsRunner(String testMethods) throws ClassNotFoundException, InitializationError {
    String[] testMethodsSplit = testMethods.split(":");
    final Multimap<String, String> methods = getMethodMap(testMethodsSplit);
    RunnerBuilder runnerBuilder = new RunnerBuilder() {
        @Override/*  www.  jav a 2s .  com*/
        public Runner runnerForClass(Class<?> testClass) throws Throwable {
            Request aClass = Request.aClass(testClass);
            final Collection<String> methodNames = methods.get(testClass.getName());
            Request filtered = aClass.filterWith(new Filter() {

                @Override
                public String describe() {
                    return "Javalanche test filter";
                }

                @Override
                public boolean shouldRun(Description description) {
                    String name = description.getClassName() + "." + description.getMethodName();
                    logger.debug("Testname: " + name);
                    boolean var = methodNames.contains(name);
                    return var;
                }
            });
            return filtered.getRunner();
        }
    };
    Class<?>[] classes = getClasses(methods);
    return new Suite(runnerBuilder, classes);
}

From source file:com.anhth12.lambda.app.ml.als.Evaluation.java

/**
 * Compute AUC (area under the ROC curve) as a recommender evaluation
 *
 * @param sparkContext//from  w w  w. j a  v  a2 s. co  m
 * @param mfModel
 * @param positiveData
 * @return
 */
static double areaUnderCurve(JavaSparkContext sparkContext, MatrixFactorizationModel mfModel,
        JavaRDD<Rating> positiveData) {

    JavaPairRDD<Integer, Integer> positiveUserProducts = positiveData
            .mapToPair(new PairFunction<Rating, Integer, Integer>() {

                @Override
                public Tuple2<Integer, Integer> call(Rating t) throws Exception {
                    return new Tuple2<>(t.user(), t.product());
                }
            });

    JavaPairRDD<Integer, Iterable<Rating>> positivePredictions = predictAll(mfModel, positiveData,
            positiveUserProducts);

    final Broadcast<List<Integer>> allItemIDsBC = sparkContext
            .broadcast(positiveUserProducts.values().distinct().collect());

    JavaPairRDD<Integer, Integer> negativeUserProducts = positiveUserProducts.groupByKey()
            .flatMapToPair(new PairFlatMapFunction<Tuple2<Integer, Iterable<Integer>>, Integer, Integer>() {
                private final RandomGenerator random = RandomManager.getRandom();

                @Override
                public Iterable<Tuple2<Integer, Integer>> call(
                        Tuple2<Integer, Iterable<Integer>> userIDsAndItemIDs) throws Exception {
                    Integer userID = userIDsAndItemIDs._1;
                    Collection<Integer> positiveItemIDs = Sets.newHashSet(userIDsAndItemIDs._2());
                    int numPositive = positiveItemIDs.size();

                    Collection<Tuple2<Integer, Integer>> negative = new ArrayList<>(numPositive);

                    List<Integer> allItemIDs = allItemIDsBC.value();

                    int numItems = allItemIDs.size();

                    for (int i = 0; i < numItems && negative.size() < numPositive; i++) {
                        Integer itemID = allItemIDs.get(random.nextInt(numItems));
                        if (!positiveItemIDs.contains(itemID)) {
                            negative.add(new Tuple2<>(userID, itemID));
                        }
                    }

                    return negative;
                }
            });

    JavaPairRDD<Integer, Iterable<Rating>> negativePredictions = predictAll(mfModel, positiveData,
            negativeUserProducts);

    return positivePredictions.join(negativePredictions).values()
            .mapToDouble(new DoubleFunction<Tuple2<Iterable<Rating>, Iterable<Rating>>>() {

                @Override
                public double call(Tuple2<Iterable<Rating>, Iterable<Rating>> t) throws Exception {
                    //AUC is also the probability that random positive examples
                    //ranking higher than random examples at large. Heare wer compare all random negative
                    //examples to all positive exampls and rapost the totals as an alternative 
                    //computatioin for AUC
                    long correct = 0;
                    long total = 0;

                    for (Rating positive : t._1()) {
                        for (Rating negative : t._2()) {
                            if (positive.rating() > negative.rating()) {
                                correct++;
                            }
                            total++;
                        }
                    }

                    return (double) correct / total;
                }
            }).mean();

}