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

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

Introduction

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

Prototype

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

Source Link

Document

Returns a Collection containing the intersection of the given Collection s.

Usage

From source file:org.openmrs.module.webservices.rest.web.v1_0.resource.openmrs1_8.LocationResource1_8.java

/**
 * @see org.openmrs.module.webservices.rest.web.resource.impl.DelegatingCrudResource#doSearch(org.openmrs.module.webservices.rest.web.RequestContext)
  *//w  w  w  .  j av  a 2 s.c o  m
  * A query string and/or a tag uuid can be passed in; if both are passed in, returns an intersection of the results; excludes retired locations
 */
@Override
protected PageableResult doSearch(RequestContext context) {

    LocationService locationService = Context.getLocationService();

    String tagUuid = context.getParameter("tag");
    String query = context.getParameter("q");

    List<Location> locationsByTag = null;
    List<Location> locationsByQuery = null;

    if (tagUuid != null) {
        LocationTag locationTag = locationService.getLocationTagByUuid(tagUuid);
        locationsByTag = locationService.getLocationsByTag(locationTag);
    }

    if (query != null) {
        locationsByQuery = locationService.getLocations(query);
    }

    if (locationsByTag == null) {
        return new NeedsPaging<Location>(locationsByQuery, context);
    } else if (locationsByQuery == null) {
        return new NeedsPaging<Location>(locationsByTag, context);
    } else {
        return new NeedsPaging<Location>(
                (List<Location>) CollectionUtils.intersection(locationsByQuery, locationsByTag), context);
    }
}

From source file:org.openvpms.web.workspace.workflow.checkin.CheckInWorkflowTestCase.java

/**
 * Performs a check in, one day after a patient was invoiced but using the same invoice.
 * <p/>//from   w w w.j a  v  a2s. c  om
 * This verifies the fix for OVPMS-1302.
 */
@Test
public void testCheckInWithInProgressInvoice() {
    // Two visits should be created, one on date1, the other on date2
    Date date1 = getDatetime("2012-01-01 10:00:00");
    Date date2 = getDatetime("2012-01-02 12:00:00");

    // Invoice the customer for a medication1 for the patient on 1/1/2012.
    // Leave the invoice IN_PROGRESS
    Product medication1 = TestHelper.createProduct();
    FinancialAct charge = (FinancialAct) create(CustomerAccountArchetypes.INVOICE);
    charge.setActivityStartTime(date1);

    context.setCustomer(customer);
    context.setPatient(patient);
    context.setPractice(getPractice());
    context.setClinician(clinician);
    LayoutContext layoutContext = new DefaultLayoutContext(context, new HelpContext("foo", null));

    TestChargeEditor editor = new TestChargeEditor(charge, layoutContext, false);
    editor.getComponent();
    CustomerChargeActItemEditor itemEditor1 = editor.addItem();
    itemEditor1.setStartTime(date1); // otherwise will default to now
    setItem(editor, itemEditor1, patient, medication1, BigDecimal.TEN, editor.getQueue());

    assertTrue(SaveHelper.save(editor));

    // Verify that an event has been created, linked to the charge
    Act item1 = (Act) itemEditor1.getObject();
    ActBean bean = new ActBean(item1);
    Act event1 = bean.getSourceAct(PatientArchetypes.CLINICAL_EVENT_CHARGE_ITEM);
    assertNotNull(event1);
    assertEquals(date1, event1.getActivityStartTime());
    assertEquals(ActStatus.IN_PROGRESS, event1.getStatus());

    // complete the event. This will force a new event to be created on subsequent check-in
    event1.setActivityEndTime(getDatetime("2012-01-01 11:30:00"));
    event1.setStatus(ActStatus.COMPLETED);
    save(event1);

    Act appointment = createAppointment(date2, customer, patient, clinician);
    CheckInWorkflowRunner workflow = new CheckInWorkflowRunner(appointment, getPractice(), context);
    workflow.setArrivalTime(date2);

    runCheckInToVisit(workflow);

    // Add another invoice item.
    Product medication2 = TestHelper.createProduct();
    VisitChargeItemEditor itemEditor2 = workflow.addVisitInvoiceItem(patient, clinician, medication2);

    // close the dialog
    PopupDialog eventDialog = workflow.editVisit();
    fireDialogButton(eventDialog, PopupDialog.OK_ID);
    Act event2 = workflow.checkEvent(patient, clinician, ActStatus.IN_PROGRESS);
    workflow.checkComplete(true, customer, patient, context);

    // verify the second item is linked to event2
    Act item2 = (Act) itemEditor2.getObject();
    ActBean bean2 = new ActBean(item2);
    assertEquals(event2, bean2.getSourceAct(PatientArchetypes.CLINICAL_EVENT_CHARGE_ITEM));

    // verify the second event is not the same as the first, and that none of the acts in the second event
    // are the same as those in the first
    assertNotEquals(event1, event2);
    ActBean event1Bean = new ActBean(event1);
    ActBean event2Bean = new ActBean(event2);
    List<Act> event1Items = event1Bean.getActs();
    List<Act> event2Items = event2Bean.getActs();
    Collection inBoth = CollectionUtils.intersection(event1Items, event2Items);
    assertTrue(inBoth.isEmpty());
}

From source file:org.orbeon.oxf.processor.pipeline.ast.ASTNodeContainer.java

public IdInfo getIdInfo() {
    class IdInfoASTHandler extends ASTSimpleHandler {

        final IdInfo idInfo = new IdInfo();

        /**/*from   www.  ja v a2 s .c  o  m*/
         * Returns the id collected after this walked went through an AST.
         */
        public IdInfo getIdInfo() {
            return idInfo;
        }

        public void hrefId(ASTHrefId hrefId) {
            idInfo.getInputRefs().add(hrefId.getId());
        }

        public void output(ASTOutput output) {
            if (output.getId() != null)
                idInfo.getOutputIds().add(output.getId());
            if (output.getRef() != null) {
                if (idInfo.getOutputRefs().contains(output.getRef()))
                    throw new ValidationException(
                            "Output id '" + output.getRef() + "' can be referenced only once",
                            output.getLocationData());
                idInfo.getOutputRefs().add(output.getRef());
            }
        }

        public boolean startChoose(ASTChoose choose) {
            choose.getHref().walk(this);

            // Get idInfo for each branch
            final IdInfo[] whenIdInfos;
            {
                List whens = choose.getWhen();
                whenIdInfos = new IdInfo[whens.size()];
                int count = 0;
                for (Iterator i = whens.iterator(); i.hasNext();) {
                    ASTWhen astWhen = (ASTWhen) i.next();
                    IdInfoASTHandler idInfoASTHandler = new IdInfoASTHandler();
                    astWhen.walk(idInfoASTHandler);
                    whenIdInfos[count] = idInfoASTHandler.getIdInfo();
                    Collection intersection = CollectionUtils.intersection(whenIdInfos[count].getInputRefs(),
                            whenIdInfos[count].getOutputIds());
                    whenIdInfos[count].getInputRefs().removeAll(intersection);
                    whenIdInfos[count].getOutputIds().removeAll(intersection);
                    count++;
                }
            }

            // Make sure the output ids and output refs are the same for every branch
            if (whenIdInfos.length > 1) {
                for (int i = 1; i < whenIdInfos.length; i++) {
                    if (!CollectionUtils.isEqualCollection(whenIdInfos[0].getOutputIds(),
                            whenIdInfos[i].getOutputIds()))
                        throw new ValidationException("ASTChoose branch number " + (i + 1)
                                + " does not declare the same ids " + whenIdInfos[0].getOutputIds().toString()
                                + " as the previous branches " + whenIdInfos[i].getOutputIds().toString(),
                                choose.getLocationData());
                    if (!CollectionUtils.isEqualCollection(whenIdInfos[0].getOutputRefs(),
                            whenIdInfos[i].getOutputRefs()))
                        throw new ValidationException("ASTChoose branch number " + (i + 1)
                                + " does not declare the same ids " + whenIdInfos[0].getOutputRefs().toString()
                                + " as the previous branches " + whenIdInfos[i].getOutputRefs().toString(),
                                choose.getLocationData());
                }
            }

            // Add ids from all the branches
            for (int i = 0; i < whenIdInfos.length; i++)
                idInfo.getInputRefs().addAll(whenIdInfos[i].getInputRefs());

            // Add output ids and output refs from first branch (they are the same for each branch)
            idInfo.getOutputIds().addAll(whenIdInfos[0].getOutputIds());
            idInfo.getOutputRefs().addAll(whenIdInfos[0].getOutputRefs());

            return false;
        }

        public boolean startForEach(ASTForEach forEach) {
            // Add contribution from <p:for-each> attributes
            forEach.getHref().walk(this);
            if (forEach.getRef() != null)
                idInfo.getOutputRefs().add(forEach.getRef());
            if (forEach.getId() != null)
                idInfo.getOutputIds().add(forEach.getId());
            forEach.getHref().walk(this);

            // Collect idInfo for all the statements
            final IdInfo statementsIdInfo;
            {
                IdInfoASTHandler statementsIdInfoASTHandler = new IdInfoASTHandler();
                statementsIdInfoASTHandler.getIdInfo().getOutputIds()
                        .add(AbstractForEachProcessor.FOR_EACH_CURRENT_INPUT);
                for (Iterator i = forEach.getStatements().iterator(); i.hasNext();) {
                    ASTStatement statement = (ASTStatement) i.next();
                    statement.walk(statementsIdInfoASTHandler);
                }
                statementsIdInfo = statementsIdInfoASTHandler.getIdInfo();
                Collection intersection = CollectionUtils.intersection(statementsIdInfo.getInputRefs(),
                        statementsIdInfo.getOutputIds());
                statementsIdInfo.getInputRefs().removeAll(intersection);
                statementsIdInfo.getOutputIds().removeAll(intersection);
            }

            // Check the refs
            if (forEach.getId() == null && forEach.getRef() == null) {
                if (statementsIdInfo.getOutputRefs().size() != 0)
                    throw new ValidationException(
                            "The statements in a <for-each> cannot have output ref; they reference "
                                    + statementsIdInfo.getOutputRefs().toString(),
                            forEach.getLocationData());
            } else if (statementsIdInfo.getOutputRefs().size() != 1) {
                throw new ValidationException(
                        "The statements in a <for-each> must have exactly one output ref; "
                                + (statementsIdInfo.getOutputRefs().isEmpty() ? "this <for-each> has none"
                                        : "this <for-each> defined: "
                                                + statementsIdInfo.getOutputRefs().toString()),
                        forEach.getLocationData());
            } else {
                String statementsRef = (String) statementsIdInfo.getOutputRefs().iterator().next();
                if (forEach.getId() != null) {
                    if (!forEach.getId().equals(statementsRef))
                        throw new ValidationException("The statements in a <for-each> referenced the id '"
                                + statementsRef + "' but the id declared on the <for-each> is '"
                                + forEach.getId() + "'", forEach.getLocationData());
                } else if (!forEach.getRef().equals(statementsRef)) {
                    throw new ValidationException(
                            "The statements in a <for-each> referenced the id '" + statementsRef
                                    + "' but the ref declared on the <for-each> is '" + forEach.getRef() + "'",
                            forEach.getLocationData());
                }
            }

            // Add ids referenced inside <for-each>
            idInfo.getInputRefs().addAll(statementsIdInfo.getInputRefs());

            return false;
        }
    }

    // Run the handler declared above on this node
    IdInfoASTHandler idInfoASTHandler = new IdInfoASTHandler();
    walk(idInfoASTHandler);
    return idInfoASTHandler.getIdInfo();
}

From source file:org.ow2.clif.jenkins.PreviewZipAction.java

@SuppressWarnings("unchecked")
PreviewZipAction diff() throws IOException {
    List<String> newPlans = zip.entries(pattern);
    String dir = zip.basedir();/*from w  ww . j  a v a2  s  .  c  o  m*/

    List<String> oldPlans = Lists.newArrayList();
    for (Item item : jenkins.getAllItems()) {
        String name = item.getName();
        if (name.startsWith(dir + "-")) {
            oldPlans.add(Jobs.toPlan(name));
        }
    }

    installs = newArrayList();
    uninstalls = newArrayList();
    upgrades = newArrayList();

    installs.addAll(CollectionUtils.subtract(newPlans, oldPlans));
    uninstalls.addAll(CollectionUtils.subtract(oldPlans, newPlans));
    upgrades.addAll(CollectionUtils.intersection(newPlans, oldPlans));

    return this;
}

From source file:org.patientview.patientview.logon.PatientAddInputAction.java

public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    UserManager userManager = LegacySpringUtils.getUserManager();
    UnitManager unitManager = LegacySpringUtils.getUnitManager();
    User user = LegacySpringUtils.getUserManager().getLoggedInUser();
    List items = unitManager.getAll(null, new String[] { "renalunit" });

    if (userManager.getCurrentSpecialtyRole(user).equals("superadmin")) {
        request.getSession().setAttribute("units", items);
    } else if (userManager.getCurrentSpecialtyRole(user).equals("unitadmin")) {
        List userUnits = unitManager.getLoggedInUsersUnits();
        Collection units = CollectionUtils.intersection(userUnits, items);
        request.getSession().setAttribute("units", units);
    }/*from w  ww .  ja va 2  s  .c  om*/

    return LogonUtils.logonChecks(mapping, request);
}

From source file:org.patientview.patientview.unit.UnitUtils.java

/**
 * this method will search units depend on login user's role and 'renalunit' unit
 * superadmin will get all 'renalunit' units, unitadmin will get all 'renalunit' units which he belongs to,
 * other role user won't get any unit, like radaradmin.
 * searching result will be as a attribute in request.
 * @param request//from  w w w.jav a2s . c  om
 */
public static void setUserRenalUnits(HttpServletRequest request) {
    UserManager userManager = LegacySpringUtils.getUserManager();
    UnitManager unitManager = LegacySpringUtils.getUnitManager();
    User user = LegacySpringUtils.getUserManager().getLoggedInUser();
    List items = unitManager.getAll(null, new String[] { "renalunit" });
    if (userManager.getCurrentSpecialtyRole(user).equals("superadmin")) {
        request.setAttribute("units", items);
    } else if (userManager.getCurrentSpecialtyRole(user).equals("unitadmin")) {
        List userUnits = unitManager.getLoggedInUsersUnits();
        Collection units = CollectionUtils.intersection(userUnits, items);
        request.setAttribute("units", units);
    }
}

From source file:org.paxml.core.Context.java

/**
 * Set a bunch of consts into the current context.
 * //  w  ww .  j av a2  s. c  o  m
 * @param map
 *            the map containing the consts
 * @param rootTags
 *            the root tags for the map parameter.
 * @param checkConflict
 *            true to assert no ids conflicts before setting, false not to
 *            assert.
 */
public void setConsts(Map<String, Object> map, Map<String, String> rootTags, boolean checkConflict) {
    if (checkConflict) {
        Collection<String> overlap = CollectionUtils.intersection(map.keySet(), idConstsMap.keySet());
        if (overlap.size() > 0) {
            throw new PaxmlRuntimeException("The followng id conflicts detected: " + overlap);
        }
    }
    idConstsMap.putAll(map);
    if (rootTags != null) {
        idToTagName.putAll(rootTags);
    }
}

From source file:org.silverpeas.accesscontrol.SimpleDocumentAccessController.java

/**
 * @param isNodeAttachmentCase/*from   www .j  av  a 2  s. co m*/
 * @param userId
 * @param object
 * @param context
 * @param userRoles
 * @param foreignUserAuthor corresponds to the user id that is the contribution author
 * @return
 */
private boolean isUserAuthorizedByContext(final boolean isNodeAttachmentCase, String userId,
        SimpleDocument object, final AccessControlContext context, Set<SilverpeasRole> userRoles,
        String foreignUserAuthor) {
    boolean authorized = true;
    boolean isRoleVerificationRequired = false;

    // Checking the versions
    if (object.isVersioned() && !object.isPublic()) {
        isRoleVerificationRequired = true;
    }

    // Verifying download is possible
    if (context.getOperations().contains(AccessControlOperation.download)
            && !object.isDownloadAllowedForReaders()) {
        authorized = object.isDownloadAllowedForRoles(userRoles);
        isRoleVerificationRequired = authorized;
    }

    // Verifying sharing is possible
    if (context.getOperations().contains(AccessControlOperation.sharing)) {
        authorized = getComponentAccessController().isSharingEnabled(object.getInstanceId());
        isRoleVerificationRequired = authorized;
    }

    // Verifying persist actions are possible
    if (authorized && !CollectionUtils
            .intersection(AccessControlOperation.PERSIST_ACTIONS, context.getOperations()).isEmpty()) {
        isRoleVerificationRequired = true;
    }

    // Verifying roles if necessary
    if (isRoleVerificationRequired) {
        SilverpeasRole greaterUserRole = SilverpeasRole.getGreaterFrom(userRoles);
        if (isNodeAttachmentCase) {
            if (context.getOperations().contains(AccessControlOperation.download)) {
                authorized = greaterUserRole.isGreaterThan(SilverpeasRole.writer);
            } else {
                authorized = greaterUserRole.isGreaterThanOrEquals(SilverpeasRole.admin);
            }
        } else {
            if (context.getOperations().contains(AccessControlOperation.sharing)) {
                return greaterUserRole.isGreaterThanOrEquals(SilverpeasRole.admin);
            }
            if (SilverpeasRole.writer.equals(greaterUserRole)) {
                authorized = userId.equals(foreignUserAuthor)
                        || getComponentAccessController().isCoWritingEnabled(object.getInstanceId());
            } else {
                authorized = greaterUserRole.isGreaterThan(SilverpeasRole.writer);
            }
        }
    }
    return authorized;
}

From source file:org.silverpeas.attachment.repository.SimpleDocumentMatcher.java

private boolean equals(SimpleDocument other) {

    if (document.getPk() != other.getPk()
            && (document.getPk() == null || !document.getPk().equals(other.getPk()))) {
        return false;
    }/* w w w .j  av a  2 s .co m*/
    if ((document.getForeignId() == null) ? (other.getForeignId() != null)
            : !document.getForeignId().equals(other.getForeignId())) {
        return false;
    }
    if (document.getOrder() != other.getOrder()) {
        return false;
    }
    if (document.isVersioned() != other.isVersioned()) {
        return false;
    }
    if ((document.getEditedBy() == null) ? (other.getEditedBy() != null)
            : !document.getEditedBy().equals(other.getEditedBy())) {
        return false;
    }
    if (document.getReservation() != other.getReservation() && (document.getReservation() == null
            || !document.getReservation().equals(other.getReservation()))) {
        return false;
    }
    if (document.getAlert() != other.getAlert()
            && (document.getAlert() == null || !document.getAlert().equals(other.getAlert()))) {
        return false;
    }
    if (document.getExpiry() != other.getExpiry()
            && (document.getExpiry() == null || !document.getExpiry().equals(other.getExpiry()))) {
        return false;
    }
    if (document.getAttachment() != other.getAttachment()
            && (document.getAttachment() == null || !document.getAttachment().equals(other.getAttachment()))) {
        return false;
    }
    if ((document.getForbiddenDownloadForRoles() == null && other.getForbiddenDownloadForRoles() != null)
            || (document.getForbiddenDownloadForRoles() != null && other.getForbiddenDownloadForRoles() == null)
            || (document.getForbiddenDownloadForRoles() != null && other.getForbiddenDownloadForRoles() != null
                    && document.getForbiddenDownloadForRoles().size() == other.getForbiddenDownloadForRoles()
                            .size()
                    && CollectionUtils
                            .intersection(document.getForbiddenDownloadForRoles(),
                                    other.getForbiddenDownloadForRoles())
                            .size() != document.getForbiddenDownloadForRoles().size())) {
        return false;
    }
    return true;
}

From source file:org.silverpeas.core.security.authorization.AccessControlOperation.java

/**
 * Indicates if it exists a persist action from the given collection.
 * @param accessControlOperations actions.
 * @return true if it exists at least one of persist action, false otherwise.
 *//*from  w w  w. ja  v  a2s.  c o m*/
public static boolean isPersistActionFrom(Collection<AccessControlOperation> accessControlOperations) {
    return CollectionUtil.isNotEmpty(accessControlOperations) && !CollectionUtils
            .intersection(AccessControlOperation.PERSIST_ACTIONS, accessControlOperations).isEmpty();
}