Example usage for org.apache.commons.collections CollectionUtils disjunction

List of usage examples for org.apache.commons.collections CollectionUtils disjunction

Introduction

In this page you can find the example usage for org.apache.commons.collections CollectionUtils disjunction.

Prototype

public static Collection disjunction(final Collection a, final Collection b) 

Source Link

Document

Returns a Collection containing the exclusive disjunction (symmetric difference) of the given Collection s.

Usage

From source file:jp.aegif.nemaki.businesslogic.impl.ContentServiceImpl.java

@SuppressWarnings("unchecked")
@Override/*from   ww  w . j a va 2  s . c  om*/
public List<Relationship> getRelationsipsOfObject(String repositoryId, String objectId,
        RelationshipDirection relationshipDirection) {
    // Set default (according to the specification)
    relationshipDirection = (relationshipDirection == null) ? RelationshipDirection.SOURCE
            : relationshipDirection;
    switch (relationshipDirection) {
    case SOURCE:
        return contentDaoService.getRelationshipsBySource(repositoryId, objectId);
    case TARGET:
        return contentDaoService.getRelationshipsByTarget(repositoryId, objectId);
    case EITHER:
        List<Relationship> sources = contentDaoService.getRelationshipsBySource(repositoryId, objectId);
        List<Relationship> targets = contentDaoService.getRelationshipsByTarget(repositoryId, objectId);
        return (List<Relationship>) CollectionUtils.disjunction(sources, targets);
    default:
        return null;
    }
}

From source file:com.dotcms.content.elasticsearch.business.ESMappingAPIImpl.java

public List<String> dependenciesLeftToReindex(Contentlet con)
        throws DotStateException, DotDataException, DotSecurityException {
    List<String> dependenciesToReindex = new ArrayList<String>();

    ContentletAPI conAPI = APILocator.getContentletAPI();

    String relatedSQL = "select tree.* from tree where parent = ? or child = ? order by tree_order";
    DotConnect db = new DotConnect();
    db.setSQL(relatedSQL);// www  .  java 2s .  c o  m
    db.addParam(con.getIdentifier());
    db.addParam(con.getIdentifier());
    ArrayList<HashMap<String, String>> relatedContentlets = db.loadResults();

    if (relatedContentlets.size() > 0) {

        List<Relationship> relationships = RelationshipFactory
                .getAllRelationshipsByStructure(con.getStructure());

        for (Relationship rel : relationships) {

            List<Contentlet> oldDocs = new ArrayList<Contentlet>();

            String q = "";
            boolean isSameStructRelationship = rel.getParentStructureInode()
                    .equalsIgnoreCase(rel.getChildStructureInode());

            if (isSameStructRelationship)
                q = "+type:content +(" + rel.getRelationTypeValue() + "-parent:" + con.getIdentifier() + " "
                        + rel.getRelationTypeValue() + "-child:" + con.getIdentifier() + ") ";
            else
                q = "+type:content +" + rel.getRelationTypeValue() + ":" + con.getIdentifier();

            oldDocs = conAPI.search(q, -1, 0, null, APILocator.getUserAPI().getSystemUser(), false);

            List<String> oldRelatedIds = new ArrayList<String>();
            if (oldDocs.size() > 0) {
                for (Contentlet oldDoc : oldDocs) {
                    oldRelatedIds.add(oldDoc.getIdentifier());
                }
            }

            List<String> newRelatedIds = new ArrayList<String>();
            for (HashMap<String, String> relatedEntry : relatedContentlets) {
                String childId = relatedEntry.get("child");
                String parentId = relatedEntry.get("parent");
                if (relatedEntry.get("relation_type").equals(rel.getRelationTypeValue())) {
                    if (con.getIdentifier().equalsIgnoreCase(childId)) {
                        newRelatedIds.add(parentId);
                        oldRelatedIds.remove(parentId);
                    } else {
                        newRelatedIds.add(childId);
                        oldRelatedIds.remove(childId);
                    }
                }
            }

            //Taking the disjunction of both collections will give the old list of dependencies that need to be removed from the
            //re-indexation and the list of new dependencies no re-indexed yet
            dependenciesToReindex.addAll(CollectionUtils.disjunction(oldRelatedIds, newRelatedIds));
        }
    }
    return dependenciesToReindex;
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.phd.academicAdminOffice.PhdIndividualProgramProcessDA.java

private List<PhdIndividualProgramProcess> getStudentOtherProcesses(final PhdIndividualProgramProcess process) {
    List<PhdIndividualProgramProcess> result = new ArrayList<PhdIndividualProgramProcess>();
    result.addAll(CollectionUtils.disjunction(process.getPerson().getPhdIndividualProgramProcessesSet(),
            Collections.singletonList(process)));

    return result;
}

From source file:net.sourceforge.fenixedu.domain.Person.java

public Collection<ExecutionCourse> getExecutionCoursesWithRegentInquiriesToAnswer() {
    final Set<ExecutionCourse> result = new HashSet<ExecutionCourse>();
    final List<ExecutionCourse> allExecutionCourses = new ArrayList<ExecutionCourse>();
    final RegentInquiryTemplate currentTemplate = RegentInquiryTemplate.getCurrentTemplate();
    if (currentTemplate != null) {
        for (final Professorship professorship : getProfessorships(currentTemplate.getExecutionPeriod())) {
            final boolean isToAnswer = hasToAnswerRegentInquiry(professorship);
            if (isToAnswer) {
                allExecutionCourses.add(professorship.getExecutionCourse());
                if (professorship.getInquiryRegentAnswer() == null
                        || professorship.getInquiryRegentAnswer().hasRequiredQuestionsToAnswer(currentTemplate)
                        || professorship.hasMandatoryCommentsToMakeAsResponsible()) {
                    result.add(professorship.getExecutionCourse());
                }// w  w w .j ava  2 s  .  co  m
            }
        }
        final Collection<ExecutionCourse> disjunctionEC = CollectionUtils.disjunction(result,
                allExecutionCourses);
        for (final ExecutionCourse executionCourse : disjunctionEC) {
            if (hasMandatoryCommentsToMakeAsRegentInUC(executionCourse)) {
                result.add(executionCourse);
            }
        }
    }
    return result;
}

From source file:org.apache.jackrabbit.core.query.lucene.SQL2IndexingAggregateTest.java

/**
 * //from  w ww  .  j a v a2 s.c om
 * this test is very similar to
 * {@link SQL2IndexingAggregateTest#testNtFileAggregate()
 * testNtFileAggregate} but checks embedded index aggregates.
 * 
 * The aggregation hierarchy is defined in
 * src/test/repository/workspaces/indexing-test/indexing-configuration.xml
 * 
 * basically a folder aggregates other folders and files that aggregate a
 * stream of content.
 * 
 * see <a href="https://issues.apache.org/jira/browse/JCR-2989">JCR-2989</a>
 * 
 * nt:folder: recursive="true" recursiveLimit="10"
 * 
 */
@SuppressWarnings("unchecked")
public void testDeepHierarchy() throws Exception {

    // this parameter IS the 'recursiveLimit' defined in the index
    // config file
    int definedRecursiveLimit = 10;
    int levelsDeep = 14;

    List<Node> allNodes = new ArrayList<Node>();
    List<Node> updatedNodes = new ArrayList<Node>();
    List<Node> staleNodes = new ArrayList<Node>();

    String sqlBase = "SELECT * FROM [nt:folder] as f WHERE ";
    String sqlCat = sqlBase + " CONTAINS (f.*, 'cat')";
    String sqlDog = sqlBase + " CONTAINS (f.*, 'dog')";

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    Writer writer = new OutputStreamWriter(out, "UTF-8");
    writer.write("the quick brown fox jumps over the lazy dog.");
    writer.flush();

    Node folderRoot = testRootNode.addNode("myFolder", "nt:folder");
    Node folderChild = folderRoot;
    allNodes.add(folderChild);

    for (int i = 0; i < levelsDeep; i++) {
        folderChild.addNode("0" + i + "-dummy", "nt:folder");
        folderChild = folderChild.addNode("0" + i, "nt:folder");
        allNodes.add(folderChild);

        // -2 because:
        // 1 because 'i' starts at 0,
        // +
        // 1 because we are talking about same node type aggregation levels
        // extra to the current node that is updated
        if (i > levelsDeep - definedRecursiveLimit - 2) {
            updatedNodes.add(folderChild);
        }
    }
    staleNodes.addAll(CollectionUtils.disjunction(allNodes, updatedNodes));

    Node file = folderChild.addNode("myFile", "nt:file");
    Node resource = file.addNode("jcr:content", "nt:resource");
    resource.setProperty("jcr:lastModified", Calendar.getInstance());
    resource.setProperty("jcr:encoding", "UTF-8");
    resource.setProperty("jcr:mimeType", "text/plain");
    resource.setProperty("jcr:data",
            session.getValueFactory().createBinary(new ByteArrayInputStream(out.toByteArray())));

    testRootNode.getSession().save();

    // because of the optimizations, the first save is expected to update
    // ALL nodes
    // executeSQL2Query(sqlDog, allNodes.toArray(new Node[] {}));

    // update jcr:data
    out.reset();
    writer.write("the quick brown fox jumps over the lazy cat.");
    writer.flush();
    resource.setProperty("jcr:data",
            session.getValueFactory().createBinary(new ByteArrayInputStream(out.toByteArray())));
    testRootNode.getSession().save();
    executeSQL2Query(sqlDog, staleNodes.toArray(new Node[] {}));
    executeSQL2Query(sqlCat, updatedNodes.toArray(new Node[] {}));

    // replace jcr:content with unstructured
    resource.remove();
    Node unstrContent = file.addNode("jcr:content", "nt:unstructured");
    Node foo = unstrContent.addNode("foo");
    foo.setProperty("text", "the quick brown fox jumps over the lazy dog.");
    testRootNode.getSession().save();
    executeSQL2Query(sqlDog, allNodes.toArray(new Node[] {}));
    executeSQL2Query(sqlCat, new Node[] {});

    // remove foo
    foo.remove();
    testRootNode.getSession().save();
    executeSQL2Query(sqlDog, staleNodes.toArray(new Node[] {}));
    executeSQL2Query(sqlCat, new Node[] {});

}

From source file:org.apache.maven.plugin.dependency.analyze.AnalyzeDuplicateMojo.java

private Set<String> findDuplicateDependencies(List<Dependency> modelDependencies) {
    List<String> modelDependencies2 = new ArrayList<String>();
    for (Dependency dep : modelDependencies) {
        modelDependencies2.add(dep.getManagementKey());
    }//from  www  .  ja v a 2 s.  c o  m

    return new HashSet<String>(
            CollectionUtils.disjunction(modelDependencies2, new HashSet<String>(modelDependencies2)));
}

From source file:org.betaconceptframework.astroboa.engine.jcr.util.PopulateComplexCmsProperty.java

private void populateAspects() throws Exception {

    if (complexPropertyNode.isNodeType(CmsBuiltInItem.StructuredContentObject.getJcrName())
            && complexProperty instanceof ComplexCmsRootProperty) {

        //Populate Aspects
        List<String> newAspects = ((ComplexCmsRootProperty) complexProperty).getAspects();

        boolean newAspectsExist = CollectionUtils.isNotEmpty(newAspects);
        if (newAspectsExist) {
            for (String aspect : newAspects) {
                //Retrieve aspect definition
                ComplexCmsPropertyDefinition aspectDefinition = contentDefinitionDao
                        .getAspectDefinition(aspect);

                if (aspectDefinition == null)
                    throw new CmsException("Aspect " + aspect + " does not have a definition");

                populateAccordingToChildPropertyDefinition(aspect, aspectDefinition);

            }//from  w w w. jav a  2s  . com
        }

        // Check which aspects should be removed
        Value[] existingAspects = null;
        if (complexPropertyNode.hasProperty(CmsBuiltInItem.Aspects.getJcrName())) {
            existingAspects = complexPropertyNode.getProperty(CmsBuiltInItem.Aspects.getJcrName()).getValues();
        }

        Map<String, Node> aspectNodesToBeRemoved = new HashMap<String, Node>();

        if (!ArrayUtils.isEmpty(existingAspects)) {
            for (Value existingAspect : existingAspects) {
                //If aspect list is empty or it does not contain existing aspect, remove aspect node
                String existingAspectName = existingAspect.getString();

                //Remove existing aspect only if it has been removed by the user
                if (!newAspects.contains(existingAspectName)) {

                    if (((ComplexCmsPropertyImpl) complexProperty)
                            .cmsPropertyHasBeenLoadedAndRemoved(existingAspectName)) {

                        //Node may have already been removed
                        if (complexPropertyNode.hasNode(existingAspectName)) {
                            aspectNodesToBeRemoved.put(existingAspectName,
                                    complexPropertyNode.getNode(existingAspectName));
                        }
                    } else {
                        if (newAspectsExist) {
                            logger.warn("Property " + existingAspectName
                                    + " is not included in the aspect list '" + newAspects
                                    + "' of the content object " + contentObjectNodeUUID
                                    + " but it has not removed properly from the content object. This is probably a bug, however property will not be removed from the repository.");
                        }
                        //Load Aspect again
                        ((ComplexCmsRootPropertyImpl) complexProperty).loadAspectDefinition(existingAspectName);
                    }
                }
            }
        }

        //Remove deleted aspects
        if (MapUtils.isNotEmpty(aspectNodesToBeRemoved)) {
            ComplexCmsPropertyNodeRemovalVisitor aspectNodeRemovalVisitor = prototypeFactory
                    .newComplexCmsPropertyNodeRemovalVisitor();
            aspectNodeRemovalVisitor.setParentNode(complexPropertyNode, complexPropertyNode);
            aspectNodeRemovalVisitor.setSession(session);

            for (Node aspectNodeToBeRemoved : aspectNodesToBeRemoved.values()) {

                //Find aspect definition
                String aspectName = aspectNodeToBeRemoved.getName();

                ComplexCmsPropertyDefinition aspectDefinition = contentDefinitionDao
                        .getAspectDefinition(aspectName);

                if (aspectDefinition == null)
                    throw new CmsException("Unable to find definition for aspect " + aspectName
                            + ". Aspect jcr node " + aspectNodeToBeRemoved.getPath()
                            + " will not be removed from content object jcr node");
                else {
                    aspectNodeRemovalVisitor.loadChildNodesToBeDeleted(aspectName);

                    aspectDefinition.accept(aspectNodeRemovalVisitor);

                    aspectNodeToBeRemoved.remove();
                }
            }
        }

        //Finally it may be the case that an aspect has been specified but finally
        //no jcr equivalent node exists. For example one provided an aspect but without
        //any value for at least one of its child properties. In that case repository
        //has chosen to delete any previous jcr node for this aspect, or not to create 
        //a jcr node if the aspect was not there at first place.
        List<String> aspectsToBeRemoved = new ArrayList<String>();
        for (String finalAspect : newAspects) {
            if (!complexPropertyNode.hasNode(finalAspect)) {
                aspectsToBeRemoved.add(finalAspect);
            }
        }

        if (aspectsToBeRemoved.size() > 0) {
            newAspects = (List<String>) CollectionUtils.disjunction(newAspects, aspectsToBeRemoved);

            //Also remove them from complex property
            for (String aspectToBeRemoved : aspectsToBeRemoved) {
                if (((ComplexCmsRootProperty) complexProperty).hasAspect(aspectToBeRemoved)) {
                    ((ComplexCmsRootProperty) complexProperty).removeChildProperty(aspectToBeRemoved);
                }
            }
        }

        //Update aspects jcr property with new values
        JcrNodeUtils.addMultiValueProperty(complexPropertyNode, CmsBuiltInItem.Aspects, SaveMode.UPDATE,
                newAspects, ValueType.String, session.getValueFactory());
    }

}

From source file:org.dkpro.tc.fstore.simple.DenseFeatureStore.java

@Override
public void addInstance(Instance instance) throws TextClassificationException {
    if (featureNames == null) {
        featureNames = new TreeSet<String>();
        for (Feature feature : instance.getFeatures()) {
            String name = feature.getName();
            if (featureNames.contains(name)) {
                throw new TextClassificationException(
                        "Feature with name '" + name + "' is defined multiple times.");
            }/*from   w w  w  .  ja va  2 s .co  m*/
            featureNames.add(name);
        }
    }

    HashSet<String> instanceFeatureNames = new HashSet<String>();
    for (Feature f : instance.getFeatures()) {
        instanceFeatureNames.add(f.getName());
    }
    @SuppressWarnings("unchecked")
    String[] symDiff = new ArrayList<String>(CollectionUtils.disjunction(instanceFeatureNames, featureNames))
            .toArray(new String[] {});
    if (symDiff.length > 0) {
        throw new TextClassificationException(
                "One or more, but not all of your instances return the following feature(s): "
                        + StringUtils.join(symDiff, " and "));
    }

    instanceList.add(instance);

}

From source file:org.fenixedu.academic.domain.inquiries.RegentInquiryTemplate.java

public static Collection<ExecutionCourse> getExecutionCoursesWithRegentInquiriesToAnswer(Person person) {
    final Set<ExecutionCourse> result = new HashSet<ExecutionCourse>();
    final List<ExecutionCourse> allExecutionCourses = new ArrayList<ExecutionCourse>();
    final RegentInquiryTemplate currentTemplate = getCurrentTemplate();
    if (currentTemplate != null) {
        for (final Professorship professorship : person
                .getProfessorships(currentTemplate.getExecutionPeriod())) {
            final boolean isToAnswer = hasToAnswerRegentInquiry(professorship);
            if (isToAnswer) {
                allExecutionCourses.add(professorship.getExecutionCourse());
                if (professorship.getInquiryRegentAnswer() == null
                        || professorship.getInquiryRegentAnswer().hasRequiredQuestionsToAnswer(currentTemplate)
                        || InquiryResultComment.hasMandatoryCommentsToMakeAsResponsible(professorship)) {
                    result.add(professorship.getExecutionCourse());
                }/*from ww  w .  ja va  2 s .c  o  m*/
            }
        }
        final Collection<ExecutionCourse> disjunctionEC = CollectionUtils.disjunction(result,
                allExecutionCourses);
        for (final ExecutionCourse executionCourse : disjunctionEC) {
            if (InquiryResultComment.hasMandatoryCommentsToMakeAsRegentInUC(person, executionCourse)) {
                result.add(executionCourse);
            }
        }
    }
    return result;
}

From source file:org.gluu.oxtrust.ldap.service.EntityIDMonitoringService.java

@Observer(OxTrustConstants.EVENT_METADATA_ENTITY_ID_UPDATE)
@Asynchronous/*from w w w.  ja v a 2  s. c o  m*/
public void process() {
    log.trace("Starting entityId monitoring process.");
    if (this.isActive) {
        log.trace("EVENT_METADATA_ENTITY_ID_UPDATE Active");
        return;
    }
    log.trace("EVENT_METADATA_ENTITY_ID_UPDATE Starting");
    try {
        this.isActive = true;
        for (GluuSAMLTrustRelationship tr : TrustService.instance().getAllTrustRelationships()) {
            log.trace("Evaluating TR " + tr.getDn());
            boolean meatadataAvailable = tr.getSpMetaDataFN() != null
                    && StringHelper.isNotEmpty(tr.getSpMetaDataFN());
            log.trace("meatadataAvailable:" + meatadataAvailable);
            boolean correctType = tr.getContainerFederation() == null;
            log.trace("correctType:" + correctType);
            boolean isValidated = GluuValidationStatus.VALIDATION_SUCCESS.equals(tr.getValidationStatus());
            log.trace("isValidated:" + isValidated);
            if (meatadataAvailable && correctType && isValidated) {
                String idpMetadataFolder = applicationConfiguration.getShibboleth2IdpRootDir() + File.separator
                        + Shibboleth2ConfService.SHIB2_IDP_METADATA_FOLDER + File.separator;
                File metadataFile = new File(idpMetadataFolder + tr.getSpMetaDataFN());
                List<String> entityIds = Shibboleth2ConfService.instance()
                        .getEntityIdFromMetadataFile(metadataFile);

                log.trace("entityIds from metadata: " + Utils.iterableToString(entityIds));
                Set<String> entityIdSet = new TreeSet<String>();

                if (entityIds != null && !entityIds.isEmpty()) {
                    Set<String> duplicatesSet = new TreeSet<String>();
                    for (String entityId : entityIds) {
                        if (!entityIdSet.add(entityId)) {
                            duplicatesSet.add(entityId);
                        }
                    }
                }

                log.trace("unique entityIds: " + Utils.iterableToString(entityIdSet));
                Collection<String> disjunction = CollectionUtils.disjunction(entityIdSet, tr.getGluuEntityId());
                log.trace("entityIds disjunction: " + Utils.iterableToString(disjunction));

                if (!disjunction.isEmpty()) {
                    log.trace("entityIds disjunction is not empty. Somthing has changed. Processing further.");
                    tr.setGluuEntityId(entityIdSet);
                    if (tr.isFederation()) {
                        List<GluuSAMLTrustRelationship> parts = TrustService.instance()
                                .getDeconstructedTrustRelationships(tr);
                        for (GluuSAMLTrustRelationship part : parts) {
                            log.trace("Processing TR part: " + part.getDn());
                            boolean isActive = part.getStatus() != null
                                    && GluuStatus.ACTIVE.equals(part.getStatus());
                            log.trace("isActive:" + isActive);
                            boolean entityIdPresent = entityIdSet != null
                                    && entityIdSet.contains(part.getEntityId());
                            log.trace("entityIdPresent:" + entityIdPresent);
                            boolean previouslyDisabled = part.getValidationLog() != null
                                    && part.getValidationLog()
                                            .contains(ENTITY_ID_VANISHED_MESSAGE + " : " + part.getEntityId());
                            log.trace("previouslyDisabled:" + previouslyDisabled);
                            if (isActive && !entityIdPresent) {
                                log.trace("no entityId found for part : " + part.getDn());
                                part.setStatus(GluuStatus.INACTIVE);
                                List<String> log = new ArrayList<String>();
                                log.add(ENTITY_ID_VANISHED_MESSAGE + " : " + part.getEntityId());
                                part.setValidationLog(log);
                                TrustService.instance().updateTrustRelationship(part);
                            }
                            if (entityIdPresent && previouslyDisabled) {
                                log.trace("entityId found for part : " + part.getDn());
                                part.setStatus(GluuStatus.ACTIVE);
                                List<String> log = part.getValidationLog();
                                List<String> updatedLog = new ArrayList<String>(log);
                                updatedLog.remove(ENTITY_ID_VANISHED_MESSAGE + " : " + part.getEntityId());
                                if (updatedLog.isEmpty()) {
                                    updatedLog = null;
                                }
                                part.setValidationLog(updatedLog);
                                TrustService.instance().updateTrustRelationship(part);
                            }
                        }
                    }

                    TrustService.instance().updateTrustRelationship(tr);
                }
            }
        }

    } catch (Throwable ex) {
        log.error("Exception happened while checking LDAP connections", ex);
    } finally {
        this.isActive = false;
    }
}