Example usage for java.util Set retainAll

List of usage examples for java.util Set retainAll

Introduction

In this page you can find the example usage for java.util Set retainAll.

Prototype

boolean retainAll(Collection<?> c);

Source Link

Document

Retains only the elements in this set that are contained in the specified collection (optional operation).

Usage

From source file:org.apache.falcon.security.DefaultAuthorizationProvider.java

protected boolean isUserInAdminGroups(UserGroupInformation proxyUgi) {
    final Set<String> groups = getGroupNames(proxyUgi);
    groups.retainAll(adminGroups);
    return !groups.isEmpty();
}

From source file:org.apache.cassandra.CassandraServiceController.java

/** TODO: Move to CassandraService? */
protected void callOnHosts(List<InetAddress> hosts, String functionName, String... functionArgs) {
    final Set<String> hostset = new HashSet<String>();

    for (InetAddress host : hosts)
        hostset.add(host.getHostAddress());

    StatementBuilder statementBuilder = new StatementBuilder();
    statementBuilder.addStatement(Statements.call(functionName, functionArgs));
    Credentials credentials = new Credentials(clusterSpec.getClusterUser(), clusterSpec.getPrivateKey());

    Map<? extends NodeMetadata, ExecResponse> results;
    try {//from   w  ww .  j a v a2 s.co  m
        results = computeService.runScriptOnNodesMatching(new Predicate<NodeMetadata>() {
            public boolean apply(NodeMetadata node) {
                Set<String> intersection = new HashSet<String>(hostset);
                intersection.retainAll(node.getPublicAddresses());
                return !intersection.isEmpty();
            }
        }, statementBuilder, RunScriptOptions.Builder.overrideCredentialsWith(credentials)
                .wrapInInitScript(false).runAsRoot(false));
    } catch (RunScriptOnNodesException e) {
        throw new RuntimeException(e);
    }

    if (results.size() != hostset.size()) {
        throw new RuntimeException(results.size() + " hosts matched " + hostset + ": " + results);
    }

    for (ExecResponse response : results.values()) {
        if (response.getExitCode() != 0) {
            throw new RuntimeException(
                    "Call " + functionName + " failed on at least one of " + hostset + ": " + results.values());
        }
    }
}

From source file:ubic.pubmedgate.interactions.evaluation.LoadInteractionSpreadsheet.java

public Set<String> compareToOther(LoadInteractionSpreadsheet other, String position) throws Exception {
    // find intersecting rows
    Set<String> bothAnnotated = (Set<String>) Util.intersect(getAllPairs(), other.getAllPairs());
    if (bothAnnotated.size() == 0)
        return new HashSet<String>();

    System.out.println("Comparison between " + name + " and " + other.name);
    System.out.println(" Done by both:" + bothAnnotated.size());

    Set<String> aNonBlankPairs = getNonBlankPairs(position);
    aNonBlankPairs.retainAll(bothAnnotated);
    Set<String> bNonBlankPairs = other.getNonBlankPairs(position);
    bNonBlankPairs.retainAll(bothAnnotated);

    Set<String> bothNonBlank = (Set<String>) Util.intersect(aNonBlankPairs, bNonBlankPairs);
    bothNonBlank.retainAll(bothAnnotated);

    System.out.println(" Both non blank for " + position + ":" + bothNonBlank.size());
    int aMarkedNotB = Util.subtract(aNonBlankPairs, bNonBlankPairs).size();
    System.out.println(" " + aMarkedNotB + " marked by " + name + " ("
            + convertToPercent(aMarkedNotB, aNonBlankPairs.size()) + ") but not by " + other.name);
    int bMarkedNotA = Util.subtract(bNonBlankPairs, aNonBlankPairs).size();
    System.out.println(" " + bMarkedNotA + " marked by " + other.name + " ("
            + convertToPercent(bMarkedNotA, bNonBlankPairs.size()) + ") but not by " + name);

    Set<String> bothBlank = (Set<String>) Util.intersect(getBlankPairs(position),
            other.getBlankPairs(position));
    bothBlank.retainAll(bothAnnotated);/* w  w w .j av a  2  s.  com*/
    System.out.println(" Both blank for " + position + ":" + bothBlank.size());
    System.out.println(
            " Agreement:" + convertToPercent(bothBlank.size() + bothNonBlank.size(), bothAnnotated.size()));
    System.out.println();

    Set<String> disagreements = new HashSet<String>(bothAnnotated);
    disagreements.removeAll(bothNonBlank);
    disagreements.removeAll(bothBlank);
    return disagreements;
}

From source file:pt.ist.bennu.core.domain.groups.IntersectionGroup.java

@Override
public Set<User> getMembers() {
    final Set<User> users = new HashSet<User>();
    if ((!getPersistentGroupsSet().isEmpty())) {
        users.addAll(getPersistentGroupsSet().iterator().next().getMembers());
        for (final PersistentGroup persistentGroup : getPersistentGroupsSet()) {
            users.retainAll(persistentGroup.getMembers());
        }//w w w  .ja v a 2  s .  co  m
    }
    return users;
}

From source file:ch.astina.hesperid.web.components.security.IfRole.java

/**
 * Find the common authorities between the current authentication's {@link
 * GrantedAuthority} and the ones that have been specified in the tag's
 * ifAny, ifNot or ifAllGranted attributes.
 * //w w w .j a va  2s  . c om
 * <p>
 * We need to manually iterate over both collections, because the granted
 * authorities might not implement {@link Object#equals(Object)} and
 * {@link Object#hashCode()} in the same way as {@link
 * GrantedAuthorityImpl}, thereby invalidating {@link
 * Collection#retainAll(java.util.Collection)} results.
 * </p>
 * 
 * <p>
 * <strong>CAVEAT</strong>: This method <strong>will not</strong> work if
 * the granted authorities returns a <code>null</code> string as the
 * return value of {@link GrantedAuthority#getAuthority()}.
 * </p>
 * 
 * <p>
 * Reported by rawdave, on Fri Feb 04, 2005 2:11 pm in the Spring Security
 * System for Spring forums.
 * </p>
 * 
 * @param granted
 *            The authorities granted by the authentication. May be any
 *            implementation of {@link GrantedAuthority} that does
 *            <strong>not</strong> return <code>null</code> from {@link GrantedAuthority#getAuthority()}.
 * @param required
 *            A {@link Set} of {@link GrantedAuthorityImpl}s that have been
 *            built using ifAny, ifAll or ifNotGranted.
 * 
 * @return A set containing only the common authorities between <var>granted</var>
 *         and <var>required</var>.
 * 
 */
@SuppressWarnings("unchecked")
private Set retainAll(final Collection granted, final Set required) {
    Set grantedRoles = authoritiesToRoles(granted);
    Set requiredRoles = authoritiesToRoles(required);
    grantedRoles.retainAll(requiredRoles);

    return rolesToAuthorities(grantedRoles, granted);
}

From source file:net.audumla.scheduler.camel.SchedulerComponent.java

@Override
protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters)
        throws Exception {
    // Get couple of scheduler settings
    Integer startDelayedSeconds = getAndRemoveParameter(parameters, "startDelayedSeconds", Integer.class);
    if (startDelayedSeconds != null) {
        if (getStartDelayedSeconds() != 0 && !(getStartDelayedSeconds() == startDelayedSeconds)) {
            logger.warn(/*from  w  w w.ja  v a 2 s .  c o  m*/
                    "A Quartz job is already configured with a different 'startDelayedSeconds' configuration! "
                            + "All Quartz jobs must share the same 'startDelayedSeconds' configuration! Cannot apply the 'startDelayedSeconds' configuration!");
        } else {
            setStartDelayedSeconds(startDelayedSeconds);
        }
    }

    Boolean autoStartScheduler = getAndRemoveParameter(parameters, "autoStartScheduler", Boolean.class);
    if (autoStartScheduler != null) {
        setAutoStartScheduler(autoStartScheduler);
    }

    Boolean prefixJobNameWithEndpointId = getAndRemoveParameter(parameters, "prefixJobNameWithEndpointId",
            Boolean.class);
    if (prefixJobNameWithEndpointId != null) {
        this.prefixJobNameWithEndpointId = prefixJobNameWithEndpointId;
    }

    DefaultSchedulerEndpoint result = null;
    // Create quartz endpoint
    for (Class<? extends DefaultSchedulerEndpoint> clazz : registeredSchedulers.keySet()) {
        Map<String, String> params = registeredSchedulers.get(clazz);
        Set<String> subset = new TreeSet<String>(parameters.keySet());
        // see if any of the parameters match with a scheduler.
        subset.retainAll(params.keySet());
        if (subset.size() > 0) {
            boolean found = true;
            for (String key : subset) {
                String value = params.get(key);
                if (value != null) {
                    Pattern pattern = Pattern.compile(value);
                    if (!pattern.matcher(parameters.get(key).toString()).find()) {
                        found = false;
                        break;
                    }
                }

            }
            if (found) {
                try {
                    result = (DefaultSchedulerEndpoint) ConstructorUtils.invokeConstructor(clazz,
                            new Object[] { uri, this });
                } catch (Exception ex) {
                    logger.error("Failed to create Scheduler - {}", uri, ex);
                    return null;
                }
            }
        }
    }
    if (result == null) {
        result = new SimpleScheduleEndpoint(uri, this);
    }
    // Extract [trigger].XXX and job.XXX properties to be set on endpoint below
    Map<String, Object> triggerParameters = IntrospectionSupport.extractProperties(parameters,
            result.getParameterPrefix() + ".");
    Map<String, Object> jobParameters = IntrospectionSupport.extractProperties(parameters, "job.");

    TriggerKey triggerKey = createTriggerKey(uri, remaining, result);
    result.setTriggerKey(triggerKey);
    result.setTriggerParameters(triggerParameters);
    result.setJobParameters(jobParameters);
    return result;
}

From source file:org.dllearner.learningproblems.PosNegLPStrict.java

@Override
public ScorePosNeg computeScore(OWLClassExpression concept) {
    if (isUseRetrievalForClassification()) {
        SortedSet<OWLIndividual> posClassified = getReasoner().getIndividuals(concept);
        SortedSet<OWLIndividual> negClassified = getReasoner()
                .getIndividuals(dataFactory.getOWLObjectComplementOf(concept));
        Set<OWLIndividual> neutClassified = new TreeSet<>(
                Sets.intersection(getReasoner().getIndividuals(), posClassified));
        neutClassified.retainAll(negClassified);
        return new ScoreThreeValued(OWLClassExpressionUtils.getLength(concept), accuracyPenalty, errorPenalty,
                penaliseNeutralExamples, getPercentPerLengthUnit(), posClassified, neutClassified,
                negClassified, positiveExamples, neutralExamples, negativeExamples);
    } else {/* ww w .ja v a  2s .co  m*/
        if (getReasoner().getReasonerType().isOWLAPIReasoner()) {
            if (penaliseNeutralExamples)
                throw new Error("It does not make sense to use single instance checks when"
                        + "neutral examples are penalized. Use Retrievals instead.");

            // TODO: umschreiben in instance checks
            SortedSet<OWLIndividual> posClassified = new TreeSet<>();
            SortedSet<OWLIndividual> negClassified = new TreeSet<>();
            // Beispiele durchgehen
            // TODO: Implementierung ist ineffizient, da man hier schon in Klassen wie
            // posAsNeut, posAsNeg etc. einteilen koennte; so wird das extra in der Score-Klasse
            // gemacht; bei wichtigen Benchmarks des 3-wertigen Lernproblems muesste man das
            // umstellen
            // pos => pos
            for (OWLIndividual example : positiveExamples) {
                if (getReasoner().hasType(concept, example))
                    posClassified.add(example);
            }
            // neg => pos
            for (OWLIndividual example : negativeExamples) {
                if (getReasoner().hasType(concept, example))
                    posClassified.add(example);
            }

            OWLClassExpression negatedConcept = dataFactory.getOWLObjectComplementOf(concept);

            // pos => neg
            for (OWLIndividual example : positiveExamples) {
                if (getReasoner().hasType(negatedConcept, example))
                    negClassified.add(example);
            }
            // neg => neg
            for (OWLIndividual example : negativeExamples) {
                if (getReasoner().hasType(negatedConcept, example))
                    negClassified.add(example);
            }

            Set<OWLIndividual> neutClassified = new TreeSet<>(
                    Sets.intersection(getReasoner().getIndividuals(), posClassified));
            neutClassified.retainAll(negClassified);
            return new ScoreThreeValued(OWLClassExpressionUtils.getLength(concept), accuracyPenalty,
                    errorPenalty, penaliseNeutralExamples, getPercentPerLengthUnit(), posClassified,
                    neutClassified, negClassified, positiveExamples, neutralExamples, negativeExamples);
        } else
            throw new Error("score cannot be computed in this configuration");
    }
}

From source file:edu.cornell.med.icb.goby.modes.AnnotationPenaltyMode.java

/**
 * Run the mode./*from w ww . ja  v  a2  s. co m*/
 *
 * @throws java.io.IOException error reading / writing
 */
@Override
public void execute() throws IOException {
    score = 0d;
    lastPos = -1;

    System.out.println("Reading official gene annotations from " + geneAnnotFile);
    final Object2ObjectMap<String, ObjectList<Annotation>> allGeneAnnots = readAnnotations(geneAnnotFile);
    System.out.println("Reading official proposal annotations from " + proposalAnnotFile);
    final Object2ObjectMap<String, ObjectList<Annotation>> allProposalAnnots = readAnnotations(
            proposalAnnotFile);

    //Find the references (chromosomes) common in both annotation files
    final Set<String> allGeneChroms = allGeneAnnots.keySet();
    final Set<String> allProposalChroms = allProposalAnnots.keySet();
    final Set<String> intersect = allGeneChroms;
    intersect.retainAll(allProposalChroms);
    final Iterator<String> commonChromsIt = intersect.iterator();

    //Find the overlapping differences between the official gene annotation and the proposed one.
    while (commonChromsIt.hasNext()) {
        lastPos = 0;
        final String chromosome = commonChromsIt.next();

        final ObjectList<Annotation> geneAnnotations = allGeneAnnots.get(chromosome);
        final ObjectList<Annotation> proposalAnnotations = allProposalAnnots.get(chromosome);
        //Sort to allow fast comparison
        Collections.sort(geneAnnotations);
        Collections.sort(proposalAnnotations);

        final ObjectIterator<Annotation> geneAnnotIt = geneAnnotations.iterator();
        final ObjectIterator<Annotation> propAnnotIt = proposalAnnotations.iterator();

        Annotation geneAnnot = getNextAnnotation(geneAnnotIt);
        Annotation propAnnot = getNextAnnotation(propAnnotIt);

        while ((geneAnnot != null) || (propAnnot != null)) {
            if ((geneAnnot != null) && (propAnnot != null)) {
                //check to see if they overlap
                if (!geneAnnot.overlap(propAnnot)) {
                    //determine which sortedPositionIterator to increment
                    if (geneAnnot.getStart() > propAnnot.getStart()) {
                        addPenalty(propAnnot);
                        propAnnot = getNextAnnotation(propAnnotIt);
                    } else {
                        addPenalty(geneAnnot);
                        geneAnnot = getNextAnnotation(geneAnnotIt);
                    }
                } else {
                    //They do overlap
                    //Need to determine which annotation is the shorter sequence and advance it's sortedPositionIterator
                    addPenalty(geneAnnot, propAnnot);
                    if (geneAnnot.getEnd() < propAnnot.getEnd()) {
                        geneAnnot = getNextAnnotation(geneAnnotIt);
                    } else {
                        propAnnot = getNextAnnotation(propAnnotIt);
                    }
                }
            } else if (geneAnnot == null) {
                //simply add the cost of all remaining propAnnot
                addPenalty(propAnnot);
                propAnnot = getNextAnnotation(propAnnotIt);
            } else if (propAnnot == null) {
                //simply add the cost of all remaining geneAnnot
                addPenalty(geneAnnot);
                geneAnnot = getNextAnnotation(geneAnnotIt);
            }
        }
    }
    System.out.println("Score = " + score);
}

From source file:com.mirth.connect.server.controllers.DefaultContextFactoryController.java

private void reloadResources(Set<String> resourceIds, boolean startup) throws Exception {
    for (String resourceId : resourceIds) {
        getLibraries(new HashSet<String>(Collections.singleton(resourceId)), true, startup);
    }/* w w  w  .ja v a2  s  .c  o  m*/

    for (Set<String> libraryResourceIds : contextFactoryMap.keySet()
            .toArray(new Set[contextFactoryMap.size()])) {
        Set<String> intersection = new LinkedHashSet<String>(libraryResourceIds);
        if (resourceIds != null) {
            intersection.retainAll(resourceIds);
        }

        if (CollectionUtils.isNotEmpty(intersection)) {
            MirthContextFactory contextFactory = contextFactoryMap.get(libraryResourceIds);

            if (contextFactory != null) {
                resetContextFactory(libraryResourceIds, startup);
            }
        }
    }
}

From source file:org.lilyproject.indexer.engine.Indexer.java

protected void setIndexAllVTags(Set<String> vtagsToIndex, Map<String, Long> vtags, IndexCase indexCase,
        Record record) {//  w  ww  .  j a v  a2 s .  co m
    if (record.getVersion() != null) {
        Set<String> tmp = new HashSet<String>();
        tmp.addAll(indexCase.getVersionTags());
        tmp.retainAll(vtags.keySet()); // only keep the vtags which exist in the document
        vtagsToIndex.addAll(tmp);
    } else if (indexCase.getIndexVersionless()) {
        vtagsToIndex.add(VersionTag.VERSIONLESS_TAG);
    }
}