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

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

Introduction

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

Prototype

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

Source Link

Document

Returns a new Collection containing a - b.

Usage

From source file:org.onebusaway.nyc.transit_data_manager.siri.NycSiriService.java

public void handleServiceDeliveries(SituationExchangeResults result, ServiceDelivery delivery)
        throws Exception {
    Set<String> incomingAgencies = collectAgencies(delivery);
    List<String> preAlertIds = getExistingAlertIds(incomingAgencies);

    for (SituationExchangeDeliveryStructure s : delivery.getSituationExchangeDelivery()) {
        SiriEndpointDetails endpointDetails = new SiriEndpointDetails();
        handleServiceDelivery(delivery, s, ESiriModuleType.SITUATION_EXCHANGE, endpointDetails, result,
                preAlertIds);/* w ww  . j  a v  a 2 s.  c om*/
    }

    List<String> postAlertIds = getExistingAlertIds(incomingAgencies);
    @SuppressWarnings("unchecked")
    Collection<String> deletedIds = CollectionUtils.subtract(preAlertIds, postAlertIds);
    postServiceDeliveryActions(result, deletedIds);

}

From source file:org.openconcerto.utils.change.CollectionChangeEvent.java

public Collection getItemsAdded() {
    return CollectionUtils.subtract((Collection) this.getNewValue(), (Collection) this.getOldValue());
}

From source file:org.openconcerto.utils.change.CollectionChangeEvent.java

public Collection getItemsRemoved() {
    return CollectionUtils.subtract((Collection) this.getOldValue(), (Collection) this.getNewValue());
}

From source file:org.openmrs.module.auditlog.api.db.hibernate.interceptor.HibernateAuditLogInterceptor.java

private void handleUpdatedCollection(Object currentCollOrMap, Object previousCollOrMap, Object owningObject,
        String role) {// ww w  .j  av a  2s. c o  m

    String propertyName = role.substring(role.lastIndexOf('.') + 1);

    if (objectChangesMap.get().peek().get(owningObject) == null) {
        objectChangesMap.get().peek().put(owningObject, new HashMap<String, String[]>());
    }

    String previousSerializedItems = null;
    String newSerializedItems = null;
    if (Collection.class.isAssignableFrom(currentCollOrMap.getClass())) {
        Collection cColl = (Collection) currentCollOrMap;
        Collection pColl = (Collection) previousCollOrMap;
        previousSerializedItems = AuditLogUtil.serializeCollection(pColl);
        newSerializedItems = AuditLogUtil.serializeCollection(cColl);

        //Track removed items so that when we create logs for them,
        //and link them to the parent's log
        Set<Object> removedItems = new HashSet<Object>();
        removedItems.addAll(CollectionUtils.subtract(pColl, cColl));
        if (!removedItems.isEmpty()) {
            if (entityRemovedChildrenMap.get().peek().get(owningObject) == null) {
                entityRemovedChildrenMap.get().peek().put(owningObject, new HashSet<Object>());
            }
            for (Object removedItem : removedItems) {
                entityRemovedChildrenMap.get().peek().get(owningObject).add(removedItem);
            }
        }
    } else if (Map.class.isAssignableFrom(currentCollOrMap.getClass())) {
        //For some reason hibernate ends calling onCollectionUpdate even when the map has
        //no changes. I think it uses object equality for the map entries and assumes the map has
        //changes. Noticed this happens for user.userProperties and added a unit test to prove it
        if (previousCollOrMap.equals(currentCollOrMap)) {
            return;
        }
        previousSerializedItems = AuditLogUtil.serializeMap((Map) previousCollOrMap);
        newSerializedItems = AuditLogUtil.serializeMap((Map) currentCollOrMap);
    }

    updates.get().peek().add(owningObject);
    objectChangesMap.get().peek().get(owningObject).put(propertyName,
            new String[] { newSerializedItems, previousSerializedItems });
}

From source file:org.openmrs.module.coreapps.htmlformentry.EncounterDiagnosesByObsElement.java

@Override
public void handleSubmission(FormEntrySession formEntrySession, HttpServletRequest request) {
    DiagnosisMetadata diagnosisMetadata = emrApiProperties.getDiagnosisMetadata();
    String submitted = request.getParameter("encounterDiagnoses");

    // if we are in edit mode, we need to map the submitted diagnoses to their existing obs
    Map<Integer, Obs> existingDiagnosisObs = getExistingDiagnosisObs(formEntrySession.getContext(),
            diagnosisMetadata);/*from  www  . j  a v  a 2 s  .  co  m*/

    FormSubmissionActions submissionActions = formEntrySession.getSubmissionActions();
    try {
        Set<Integer> resubmittedObs = new HashSet<Integer>(); // we need to void any existing that isn't resubmitted

        List<Diagnosis> diagnoses = parseDiagnoses(submitted, existingDiagnosisObs);
        for (Diagnosis diagnosis : diagnoses) {
            if (diagnosis.getExistingObs() != null) {
                resubmittedObs.add(diagnosis.getExistingObs().getId());
            }
            Obs obsGroup = diagnosisMetadata.buildDiagnosisObsGroup(diagnosis);
            createObsGroup(submissionActions, obsGroup);
        }

        if (formEntrySession.getContext().getMode().equals(FormEntryContext.Mode.EDIT)) {
            // void any diagnosis that wasn't resubmitted
            Collection<Integer> obsToVoid = CollectionUtils.subtract(existingDiagnosisObs.keySet(),
                    resubmittedObs);
            for (Integer obsId : obsToVoid) {
                submissionActions.modifyObs(existingDiagnosisObs.get(obsId), null, null, null, null, null);
            }
        }
    } catch (IOException e) {
        throw new IllegalStateException(e);
    } catch (InvalidActionException e) {
        throw new IllegalStateException(e);
    }
}

From source file:org.openmrs.module.odkconnector.web.controller.concept.ManageConceptController.java

@RequestMapping(value = "/module/odkconnector/concept/manageConcept", method = RequestMethod.POST)
public void process(final @RequestParam(value = "conceptUuids", required = true) String conceptUuids,
        final @RequestParam(value = "configurationUuid", required = true) String configurationUuid,
        final Model model, final HttpServletRequest request) {

    ConnectorService service = Context.getService(ConnectorService.class);
    ConceptConfiguration conceptConfiguration = service.getConceptConfigurationByUuid(configurationUuid);

    // the uuids coming from the web page. might contains new uuid and will not contains retired uuid
    Set<String> createdConceptUuidValues = new LinkedHashSet<String>(
            Arrays.asList(StringUtils.split(StringUtils.defaultString(conceptUuids), ",")));
    // the saved uuids. might contains retired uuid and will not contains new uuid
    Set<String> savedConceptUuidValues = new LinkedHashSet<String>();
    for (ConfiguredConcept configuredConcept : conceptConfiguration.getConfiguredConcepts()) {
        if (!configuredConcept.isRetired()) {
            Concept concept = configuredConcept.getConcept();
            savedConceptUuidValues.add(concept.getUuid());
        }/*from  w  w w .j  a v a 2 s  .  co m*/
    }

    Collection intersectedUuids = CollectionUtils.intersection(createdConceptUuidValues,
            savedConceptUuidValues);
    Collection retiredConceptUuids = CollectionUtils.subtract(savedConceptUuidValues, intersectedUuids);
    Collection createdConceptUuids = CollectionUtils.subtract(createdConceptUuidValues, intersectedUuids);

    for (ConfiguredConcept configuredConcept : conceptConfiguration.getConfiguredConcepts()) {
        Concept concept = configuredConcept.getConcept();
        if (retiredConceptUuids.contains(concept.getUuid())) {
            configuredConcept.setRetired(Boolean.TRUE);
            configuredConcept.setRetiredBy(Context.getAuthenticatedUser());
            configuredConcept.setDateRetired(new Date());
        }
    }

    for (Object conceptUuid : createdConceptUuids) {
        Concept concept = Context.getConceptService().getConceptByUuid(String.valueOf(conceptUuid));
        if (concept != null) {
            ConfiguredConcept configuredConcept = new ConfiguredConcept();
            configuredConcept.setConcept(concept);
            configuredConcept.setConceptConfiguration(conceptConfiguration);
            conceptConfiguration.addConfiguredConcept(configuredConcept);
        }
    }
    service.saveConceptConfiguration(conceptConfiguration);

    Set<Concept> concepts = ConnectorUtils.getConcepts(conceptConfiguration.getConfiguredConcepts());
    model.addAttribute("configuration", conceptConfiguration);
    model.addAttribute("concepts", concepts);
    model.addAttribute("conceptUuids", ConnectorUtils.convertString(ConnectorUtils.getConceptUuids(concepts)));
}

From source file:org.openmrs.module.webservices.rest.web.resource.impl.BaseDelegatingResource.java

/**
 * @param delegate//from  ww w .ja  v a2  s. c  o  m
 * @param propertyMap
 * @param description
 * @param mustIncludeRequiredProperties
 * @throws ResponseException
 * @should allow setting a null value
 */
public void setConvertedProperties(T delegate, Map<String, Object> propertyMap,
        DelegatingResourceDescription description, boolean mustIncludeRequiredProperties)
        throws ConversionException {
    Map<String, Property> allowedProperties = new LinkedHashMap<String, Property>(description.getProperties());

    Map<String, Object> propertiesToSet = new HashMap<String, Object>(propertyMap);
    propertiesToSet.keySet().removeAll(propertiesIgnoredWhenUpdating);

    // Apply properties in the order specified in the resource description (necessary e.g. so the obs resource
    // can apply "concept" before "value"); we have already excluded unchanged and ignored properties.
    // Because some resources (e.g. any AttributeResource) require some properties to be set before others can
    // be fetched, we apply each property in its iteration, rather than testing everything first and applying later.
    for (String property : allowedProperties.keySet()) {
        if (!propertiesToSet.containsKey(property)) {
            continue;
        }
        if (propertiesToSet.containsKey(property)) {
            // Ignore any properties that were not actually changed, also covering the case where you post back an
            // incomplete rep of a complex property
            Object oldValue = getProperty(delegate, property);
            Object newValue = propertiesToSet.get(property);
            if (unchangedValue(oldValue, newValue)) {
                propertiesToSet.remove(property);
                continue;
            }

            setProperty(delegate, property, propertiesToSet.get(property));
        }
    }

    // If any non-settable properties remain after the above logic, fail
    Collection<String> notAllowedProperties = CollectionUtils.subtract(propertiesToSet.keySet(),
            allowedProperties.keySet());
    // Do allow posting back an unchanged value to an unchangeable property
    for (Iterator<String> iterator = notAllowedProperties.iterator(); iterator.hasNext();) {
        String property = iterator.next();
        Object oldValue = getProperty(delegate, property);
        Object newValue = propertiesToSet.get(property);
        if (unchangedValue(oldValue, newValue)) {
            iterator.remove();
        }
    }
    if (!notAllowedProperties.isEmpty()) {
        throw new ConversionException(
                "Some properties are not allowed to be set: " + StringUtils.join(notAllowedProperties, ", "));
    }

    if (mustIncludeRequiredProperties) {
        Set<String> missingProperties = new HashSet<String>();
        for (Entry<String, Property> prop : allowedProperties.entrySet()) {
            if (prop.getValue().isRequired() && !propertyMap.containsKey(prop.getKey())) {
                missingProperties.add(prop.getKey());
            }
        }
        if (!missingProperties.isEmpty()) {
            throw new ConversionException(
                    "Some required properties are missing: " + StringUtils.join(missingProperties, ", "));
        }
    }
}

From source file:org.openmrs.web.dwr.DWRObservationServiceTest.java

/**
 * @see org.openmrs.web.dwr.DWRObsService#createObs(Integer, Integer, Integer, String, String)
 *///w  w  w.j a va  2  s .co  m
@Test
@Verifies(value = "should pass test on saving observation with coded concepts", method = "createObs(Integer, Integer,Integer, String, String)")
public void createObservation_shouldCreateObservationWithCodedConcept() throws Exception {
    DWRObsService dwrService = new DWRObsService();
    ConceptService conceptService = Context.getConceptService();
    ObsService obsService = Context.getObsService();
    Person person = Context.getPersonService().getPerson(2);
    Concept concept = conceptService.getConcept(21);
    List<Obs> obsListBefore = obsService.getObservationsByPersonAndConcept(person, concept);
    dwrService.createObs(2, null, 21, "7", "1/12/2014");
    List<Obs> obsListAfter = obsService.getObservationsByPersonAndConcept(person, concept);
    assertEquals(obsListBefore.size() + 1, obsListAfter.size());
    Concept answerConcept = conceptService.getConcept(7);
    Obs addedObs = (Obs) CollectionUtils.subtract(obsListAfter, obsListBefore).iterator().next();
    assertNotNull(addedObs);
    assertNotNull(addedObs.getValueCoded());
    assertEquals(answerConcept, addedObs.getValueCoded());
}

From source file:org.openmrs.web.dwr.DWRObservationServiceTest.java

/**
 * @see org.openmrs.web.dwr.DWRObsService#createObs(Integer, Integer, Integer, String, String)
 *///  www. ja v  a  2  s . c o m
@Test
@Verifies(value = "should pass test on saving observation with boolean concepts with value yes", method = "createObs(Integer, Integer, Integer, String, String)")
public void createObservation_shouldCreateObservationWithBooleanConceptWithValueYes() throws Exception {
    DWRObsService dwrService = new DWRObsService();
    ConceptService conceptService = Context.getConceptService();
    ObsService obsService = Context.getObsService();
    AdministrationService administrationService = Context.getAdministrationService();
    Person person = Context.getPersonService().getPerson(2);
    Concept concept = conceptService.getConcept(18);
    List<Obs> obsListBefore = obsService.getObservationsByPersonAndConcept(person, concept);
    int obsListSizeBeforeSaveObs = obsListBefore.size();
    String obsDateTime = "1/12/2014";
    dwrService.createObs(2, null, 18, "Yes", obsDateTime);
    List<Obs> obsListAfter = obsService.getObservationsByPersonAndConcept(person, concept);
    assertEquals(obsListSizeBeforeSaveObs + 1, obsListAfter.size());
    String booleanConceptId = administrationService.getGlobalProperty("concept.true");
    Concept booleanConcept = Context.getConceptService().getConcept(Integer.parseInt(booleanConceptId));
    Obs addedObs = (Obs) CollectionUtils.subtract(obsListAfter, obsListBefore).iterator().next();
    assertNotNull(addedObs);
    assertNotNull(addedObs.getValueCoded());
    assertEquals(booleanConcept, addedObs.getValueCoded());
}

From source file:org.openmrs.web.dwr.DWRObservationServiceTest.java

/**
 * @see org.openmrs.web.dwr.DWRObsService#createObs(Integer, Integer, Integer, String, String)
 *///from  w  w  w. ja  v  a  2 s.  com
@Test
@Verifies(value = "should pass test on saving observation with boolean concepts with value no", method = "createObs(Integer, Integer, Integer, String, String)")
public void createObservation_shouldCreateObservationWithBooleanConceptWithValueNo() throws Exception {
    DWRObsService dwrService = new DWRObsService();
    ConceptService conceptService = Context.getConceptService();
    ObsService obsService = Context.getObsService();
    AdministrationService administrationService = Context.getAdministrationService();
    Person person = Context.getPersonService().getPerson(2);
    Concept concept = conceptService.getConcept(18);
    List<Obs> obsListBefore = obsService.getObservationsByPersonAndConcept(person, concept);
    int obsListSizeBeforeSaveObs = obsListBefore.size();
    String obsDateTime = "2/12/2014";
    dwrService.createObs(2, null, 18, "No", obsDateTime);
    List<Obs> obsListAfter = obsService.getObservationsByPersonAndConcept(person, concept);
    assertEquals(obsListSizeBeforeSaveObs + 1, obsListAfter.size());
    String booleanConceptId = administrationService.getGlobalProperty("concept.false");
    Concept booleanConcept = Context.getConceptService().getConcept(Integer.parseInt(booleanConceptId));
    Obs addedObs = (Obs) CollectionUtils.subtract(obsListAfter, obsListBefore).iterator().next();
    assertNotNull(addedObs);
    assertNotNull(addedObs.getValueCoded());
    assertEquals(booleanConcept, addedObs.getValueCoded());
}