Example usage for org.springframework.context.support MessageSourceAccessor getMessage

List of usage examples for org.springframework.context.support MessageSourceAccessor getMessage

Introduction

In this page you can find the example usage for org.springframework.context.support MessageSourceAccessor getMessage.

Prototype

public String getMessage(MessageSourceResolvable resolvable) throws NoSuchMessageException 

Source Link

Document

Retrieve the given MessageSourceResolvable (e.g.

Usage

From source file:org.openmrs.web.controller.person.PersonFormController.java

/**
 * @see org.springframework.web.servlet.mvc.AbstractFormController#processFormSubmission(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse, java.lang.Object,
 *      org.springframework.validation.BindException)
 *///from   w  w  w  . jav  a2s  . c  om
protected ModelAndView processFormSubmission(HttpServletRequest request, HttpServletResponse response,
        Object obj, BindException errors) throws Exception {
    if (!Context.isAuthenticated()) {
        errors.reject("auth.invalid");
    }

    if (errors.hasErrors()) {
        return showForm(request, response, errors);
    }

    Person person = (Person) obj;

    MessageSourceAccessor msa = getMessageSourceAccessor();
    String action = request.getParameter("action");

    if (action.equals(msa.getMessage("Person.save"))) {
        updatePersonAddresses(request, person, errors);

        updatePersonNames(request, person);

        updatePersonAttributes(request, errors, person);
    }

    if (errors.hasErrors()) {
        return showForm(request, response, errors);
    }

    return super.processFormSubmission(request, response, person, errors);
}

From source file:org.openmrs.module.personalhr.web.controller.NewPatientFormController.java

@Override
protected ModelAndView processFormSubmission(final HttpServletRequest request,
        final HttpServletResponse response, final Object obj, final BindException errors) throws Exception {

    this.newIdentifiers = new HashSet<PatientIdentifier>();

    final ShortPatientModel shortPatient = (ShortPatientModel) obj;

    this.log.debug(
            "\nNOW GOING THROUGH PROCESSFORMSUBMISSION METHOD.......................................\n\n");

    if (Context.isAuthenticated()) {
        final PatientService ps = Context.getPatientService();
        final MessageSourceAccessor msa = getMessageSourceAccessor();

        final String action = request.getParameter("action");
        if ((action == null) || action.equals(msa.getMessage("general.save"))) {

            final String[] identifiers = request.getParameterValues("identifier");
            final String[] types = request.getParameterValues("identifierType");
            final String[] locs = request.getParameterValues("location");
            this.pref = request.getParameter("preferred");
            if (this.pref == null) {
                this.pref = "";
            }/*from w w  w. j av  a 2s.c om*/

            if (this.log.isDebugEnabled()) {
                this.log.debug("identifiers: " + identifiers);
                if (identifiers != null) {
                    for (final String s : identifiers) {
                        this.log.debug(s);
                    }
                }

                this.log.debug("types: " + types);
                if (types != null) {
                    for (final String s : types) {
                        this.log.debug(s);
                    }
                }

                this.log.debug("locations: " + locs);
                if (locs != null) {
                    for (final String s : locs) {
                        this.log.debug(s);
                    }
                }

                this.log.debug("preferred: " + this.pref);
            }

            // loop over the identifiers to create the patient.identifiers set
            if (identifiers != null) {
                for (int i = 0; i < identifiers.length; i++) {
                    // arguments for the spring error messages
                    final String id = identifiers[i].trim();
                    final String[] args = { id };

                    // add the new identifier only if they put in some identifier string
                    if (id.length() > 0) {

                        // set up the actual identifier java object
                        PatientIdentifierType pit = null;
                        if ((types[i] == null) || types[i].equals("")) {
                            final String msg = getMessageSourceAccessor()
                                    .getMessage("PatientIdentifier.identifierType.null", args);
                            errors.reject(msg);
                        } else {
                            pit = ps.getPatientIdentifierType(Integer.valueOf(types[i]));
                        }

                        Location loc = null;
                        if ((locs[i] == null) || locs[i].equals("")) {
                            final String msg = getMessageSourceAccessor()
                                    .getMessage("PatientIdentifier.location.null", args);
                            errors.reject(msg);
                        } else {
                            loc = Context.getLocationService().getLocation(Integer.valueOf(locs[i]));
                        }

                        final PatientIdentifier pi = new PatientIdentifier(id, pit, loc);
                        pi.setPreferred(this.pref.equals(id + types[i]));
                        this.newIdentifiers.add(pi);

                        if (this.log.isDebugEnabled()) {
                            this.log.debug("Creating patient identifier with identifier: " + id);
                            this.log.debug("and type: " + types[i]);
                            this.log.debug("and location: " + locs[i]);
                        }

                    }
                }
            }
        }

    }

    // skip calling super.processFormSubmission so that setting up the page is done
    // again in the onSubmit method

    return onSubmit(request, response, shortPatient, errors);
}

From source file:org.openmrs.web.controller.person.PersonFormController.java

@Override
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command,
        BindException errors) throws Exception {
    if (!Context.isAuthenticated()) {
        errors.reject("auth.invalid");
    }/* www  . j  av a2s . c o m*/

    if (errors.hasErrors()) {
        return showForm(request, response, errors);
    }

    HttpSession httpSession = request.getSession();

    Person person = (Person) command;

    MessageSourceAccessor msa = getMessageSourceAccessor();
    String action = request.getParameter("action");
    PersonService ps = Context.getPersonService();

    StringBuilder linkedProviders = new StringBuilder();
    if (action.equals(msa.getMessage("Person.delete")) || action.equals(msa.getMessage("Person.void"))) {
        Collection<Provider> providerCollection = Context.getProviderService().getProvidersByPerson(person);
        if (providerCollection != null && !providerCollection.isEmpty()) {
            for (Provider provider : providerCollection) {
                linkedProviders.append(provider.getName() + ", ");
            }
            linkedProviders = new StringBuilder(linkedProviders.substring(0, linkedProviders.length() - 2));
        }
    }
    String linkedProvidersString = linkedProviders.toString();
    if (action.equals(msa.getMessage("Person.delete"))) {
        try {
            if (!linkedProvidersString.isEmpty()) {
                errors.reject(
                        Context.getMessageSourceService().getMessage("Person.cannot.delete.linkedTo.providers")
                                + " " + linkedProviders);
            }

            Collection<User> userCollection = Context.getUserService().getUsersByPerson(person, true);
            String linkedUsers = "";
            if (userCollection != null && !userCollection.isEmpty()) {
                for (User user : userCollection) {
                    linkedUsers = linkedUsers + user.getSystemId() + ", ";
                }
                linkedUsers = linkedUsers.substring(0, linkedUsers.length() - 2);
            }
            if (!linkedUsers.isEmpty()) {
                errors.reject(
                        Context.getMessageSourceService().getMessage("Person.cannot.delete.linkedTo.users")
                                + " " + linkedUsers);
            }

            if (errors.hasErrors()) {
                return showForm(request, response, errors);
            } else {
                ps.purgePerson(person);
                httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Person.deleted");

                return new ModelAndView(new RedirectView("index.htm"));
            }
        } catch (DataIntegrityViolationException e) {
            log.error("Unable to delete person because of database FK errors: " + person, e);
            httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Person.cannot.delete");

            return new ModelAndView(
                    new RedirectView(getSuccessView() + "?personId=" + person.getPersonId().toString()));
        }
    } else if (action.equals(msa.getMessage("Person.void"))) {
        String voidReason = request.getParameter("voidReason");
        if (StringUtils.isBlank(voidReason)) {
            voidReason = msa.getMessage("PersonForm.default.voidReason", null, "Voided from person form",
                    Context.getLocale());
        }
        if (linkedProvidersString.isEmpty()) {
            ps.voidPerson(person, voidReason);
            httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Person.voided");
        } else {
            httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                    Context.getMessageSourceService().getMessage("Person.cannot.void.linkedTo.providers") + " "
                            + linkedProviders);
        }
        return new ModelAndView(new RedirectView(getSuccessView() + "?personId=" + person.getPersonId()));
    } else if (action.equals(msa.getMessage("Person.unvoid"))) {
        ps.unvoidPerson(person);
        httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Person.unvoided");

        return new ModelAndView(new RedirectView(getSuccessView() + "?personId=" + person.getPersonId()));
    } else {
        ps.savePerson(person);

        // If person is dead
        if (person.getDead()) {
            log.debug("Person is dead, so let's make sure there's an Obs for it");
            // need to make sure there is an Obs that represents the patient's cause of death, if applicable

            String causeOfDeathConceptId = Context.getAdministrationService()
                    .getGlobalProperty("concept.causeOfDeath");
            Concept causeOfDeath = Context.getConceptService().getConcept(causeOfDeathConceptId);

            if (causeOfDeath != null) {
                List<Obs> obssDeath = Context.getObsService().getObservationsByPersonAndConcept(person,
                        causeOfDeath);
                if (obssDeath != null) {
                    if (obssDeath.size() > 1) {
                        log.error("Multiple causes of death (" + obssDeath.size() + ")?  Shouldn't be...");
                    } else {
                        Obs obsDeath = null;
                        if (obssDeath.size() == 1) {
                            // already has a cause of death - let's edit it.
                            log.debug("Already has a cause of death, so changing it");

                            obsDeath = obssDeath.iterator().next();

                        } else {
                            // no cause of death obs yet, so let's make one
                            log.debug("No cause of death yet, let's create one.");

                            obsDeath = new Obs();
                            obsDeath.setPerson(person);
                            obsDeath.setConcept(causeOfDeath);
                            Location location = Context.getLocationService().getDefaultLocation();
                            // TODO person healthcenter //if ( loc == null ) loc = patient.getHealthCenter();
                            if (location != null) {
                                obsDeath.setLocation(location);
                            } else {
                                log.error(
                                        "Could not find a suitable location for which to create this new Obs");
                            }
                        }

                        // put the right concept and (maybe) text in this obs
                        Concept currCause = person.getCauseOfDeath();
                        if (currCause == null) {
                            // set to NONE
                            log.debug("Current cause is null, attempting to set to NONE");
                            String noneConcept = Context.getAdministrationService()
                                    .getGlobalProperty("concept.none");
                            currCause = Context.getConceptService().getConcept(noneConcept);
                        }

                        if (currCause != null) {
                            log.debug("Current cause is not null, setting to value_coded");
                            obsDeath.setValueCoded(currCause);
                            obsDeath.setValueCodedName(currCause.getName()); // ABKTODO: presume current locale?

                            Date dateDeath = person.getDeathDate();
                            if (dateDeath == null) {
                                dateDeath = new Date();
                            }

                            obsDeath.setObsDatetime(dateDeath);

                            // check if this is an "other" concept - if so, then we need to add value_text
                            String otherConcept = Context.getAdministrationService()
                                    .getGlobalProperty("concept.otherNonCoded");
                            Concept conceptOther = Context.getConceptService().getConcept(otherConcept);
                            boolean deathReasonChanged = false;
                            if (conceptOther != null) {
                                String otherInfo = ServletRequestUtils.getStringParameter(request,
                                        "causeOfDeath_other", "");
                                if (conceptOther.equals(currCause)) {
                                    // seems like this is an other concept - let's try to get the "other" field info
                                    deathReasonChanged = !otherInfo.equals(obsDeath.getValueText());
                                    log.debug("Setting value_text as " + otherInfo);
                                    obsDeath.setValueText(otherInfo);
                                } else {
                                    // non empty text value implies concept changed from OTHER NON CODED to NONE
                                    deathReasonChanged = !otherInfo.equals("");
                                    log.debug("New concept is NOT the OTHER concept, so setting to blank");
                                    obsDeath.setValueText("");
                                }
                            } else {
                                log.debug("Don't seem to know about an OTHER concept, so deleting value_text");
                                obsDeath.setValueText("");
                            }
                            boolean shouldSaveObs = (null == obsDeath.getId()) || deathReasonChanged;
                            if (shouldSaveObs) {
                                if (null == obsDeath.getVoidReason()) {
                                    obsDeath.setVoidReason("Changed in patient demographics editor");
                                }
                                Context.getObsService().saveObs(obsDeath, obsDeath.getVoidReason());
                            }
                        } else {
                            log.debug("Current cause is still null - aborting mission");
                        }
                    }
                }
            } else {
                log.debug(
                        "Cause of death is null - should not have gotten here without throwing an error on the form.");
            }

        }

        String view = getSuccessView();
        httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Person.saved");
        view = view + "?personId=" + person.getPersonId();

        return new ModelAndView(new RedirectView(view));
    }
}

From source file:org.openmrs.module.personalhr.web.controller.NewPatientFormController.java

/**
 * The onSubmit function receives the form/command object that was modified by the input form
 * and saves it to the db// w  w w  . jav  a2s. c  om
 * 
 * @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse, java.lang.Object,
 *      org.springframework.validation.BindException)
 */
@Override
@SuppressWarnings("unchecked")
protected ModelAndView onSubmit(final HttpServletRequest request, final HttpServletResponse response,
        final Object obj, final BindException errors) throws Exception {

    final HttpSession httpSession = request.getSession();
    request.getSession().setAttribute(WebConstants.OPENMRS_HEADER_USE_MINIMAL, "true");

    this.log.debug("\nNOW GOING THROUGH ONSUBMIT METHOD.......................................\n\n");

    if (Context.isAuthenticated()) {
        final PatientService ps = Context.getPatientService();
        final PersonService personService = Context.getPersonService();

        final ShortPatientModel shortPatient = (ShortPatientModel) obj;
        final String view = getFormView();
        boolean isError = errors.hasErrors(); // account for possible errors in the processFormSubmission method

        if (isError) {
            httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, errors.getFieldError().getCode());
        }

        final String action = request.getParameter("action");
        final MessageSourceAccessor msa = getMessageSourceAccessor();
        if ((action != null) && action.equals(msa.getMessage("general.cancel"))) {
            httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "general.canceled");
            return new ModelAndView(new RedirectView("addPerson.htm?personType=patient"));
        }

        Patient patient = null;
        if (shortPatient.getPatientId() != null) {
            patient = ps.getPatient(shortPatient.getPatientId());
            if (patient == null) {
                try {
                    final Person p = personService.getPerson(shortPatient.getPatientId());
                    Context.clearSession(); // so that this Person doesn't cause hibernate to think the new Patient is in the cache already (only needed until #725 is fixed)
                    patient = new Patient(p);
                } catch (final ObjectRetrievalFailureException noUserEx) {
                    // continue;
                }
            }
        }

        if (patient == null) {
            patient = new Patient();
        }

        boolean duplicate = false;
        final PersonName newName = shortPatient.getName();

        if (this.log.isDebugEnabled()) {
            this.log.debug("Checking new name: " + newName.toString());
        }

        for (final PersonName pn : patient.getNames()) {
            if ((((pn.getGivenName() == null) && (newName.getGivenName() == null))
                    || OpenmrsUtil.nullSafeEquals(pn.getGivenName(), newName.getGivenName()))
                    && (((pn.getMiddleName() == null) && (newName.getMiddleName() == null))
                            || OpenmrsUtil.nullSafeEquals(pn.getMiddleName(), newName.getMiddleName()))
                    && (((pn.getFamilyName() == null) && (newName.getFamilyName() == null))
                            || OpenmrsUtil.nullSafeEquals(pn.getFamilyName(), newName.getFamilyName()))) {
                duplicate = true;
            }
        }

        // if this is a new name, add it to the patient
        if (!duplicate) {
            // set the current name to "non-preferred"
            if (patient.getPersonName() != null) {
                patient.getPersonName().setPreferred(false);
            }

            // add the new name
            newName.setPersonNameId(null);
            newName.setPreferred(true);
            newName.setUuid(null);
            patient.addName(newName);
        }

        if (this.log.isDebugEnabled()) {
            this.log.debug("The address to add/check: " + shortPatient.getAddress());
        }

        if ((shortPatient.getAddress() != null) && !shortPatient.getAddress().isBlank()) {
            duplicate = false;
            for (final PersonAddress pa : patient.getAddresses()) {
                if (pa.toString().equals(shortPatient.getAddress().toString())) {
                    duplicate = true;
                    pa.setPreferred(true);
                } else {
                    pa.setPreferred(false);
                }
            }

            if (this.log.isDebugEnabled()) {
                this.log.debug("The duplicate address:  " + duplicate);
            }

            if (!duplicate) {
                final PersonAddress newAddress = (PersonAddress) shortPatient.getAddress().clone();
                newAddress.setPersonAddressId(null);
                newAddress.setPreferred(true);
                newAddress.setUuid(null);
                patient.addAddress(newAddress);
            }
        }
        if (this.log.isDebugEnabled()) {
            this.log.debug("patient addresses: " + patient.getAddresses());
        }

        // set or unset the preferred bit for the old identifiers if needed
        if (patient.getIdentifiers() == null) {
            patient.setIdentifiers(new LinkedHashSet<PatientIdentifier>());
        }

        for (final PatientIdentifier pi : patient.getIdentifiers()) {
            pi.setPreferred(
                    this.pref.equals(pi.getIdentifier() + pi.getIdentifierType().getPatientIdentifierTypeId()));
        }

        String email = null;
        // look for person attributes in the request and save to patient
        for (final PersonAttributeType type : personService.getPersonAttributeTypes(PERSON_TYPE.PATIENT,
                ATTR_VIEW_TYPE.VIEWING)) {
            final String paramName = type.getPersonAttributeTypeId().toString();
            final String value = request.getParameter(paramName);

            this.log.debug("paramName=" + paramName);
            if ("9".equalsIgnoreCase(paramName)) {
                if (PersonalhrUtil.isNullOrEmpty(value)) {
                    //errors.reject("Email address cannot be empty!");
                    httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Email address cannot be empty!");
                    isError = true;
                } else if (!PersonalhrUtil.isValidEmail(value)) {
                    //errors.reject("Invalid email address: " + value);
                    httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                            "Invalid email address: " + value);
                    isError = true;
                } else {
                    //store email address to messaging_addresses table
                    email = value;
                }
            }

            // if there is an error displaying the attribute, the value will be null
            if (!isError) {
                final PersonAttribute attribute = new PersonAttribute(type, value);
                try {
                    final Object hydratedObject = attribute.getHydratedObject();
                    if ((hydratedObject == null) || "".equals(hydratedObject.toString())) {
                        // if null is returned, the value should be blanked out
                        attribute.setValue("");
                    } else if (hydratedObject instanceof Attributable) {
                        attribute.setValue(((Attributable) hydratedObject).serialize());
                    } else if (!hydratedObject.getClass().getName().equals(type.getFormat())) {
                        // if the classes doesn't match the format, the hydration failed somehow
                        // TODO change the PersonAttribute.getHydratedObject() to not swallow all errors?
                        throw new APIException();
                    }
                } catch (final APIException e) {
                    errors.rejectValue("attributeMap[" + type.getName() + "]",
                            "Invalid value for " + type.getName() + ": '" + value + "'");
                    this.log.warn("Got an invalid value: " + value + " while setting personAttributeType id #"
                            + paramName, e);

                    // setting the value to empty so that the user can reset the value to something else
                    attribute.setValue("");

                }
                patient.addAttribute(attribute);
            }
        }

        if (this.newIdentifiers.isEmpty()) {
            final PatientIdentifier ident = new PatientIdentifier();
            ident.setIdentifier(PersonalhrUtil.getRandomIdentifer());
            ident.setIdentifierType(new PatientIdentifierType(1));
            ident.setLocation(new Location(1));
            this.newIdentifiers.add(ident);
        }
        // add the new identifiers.  First remove them so that things like
        // changes to preferred status and location are persisted
        for (final PatientIdentifier identifier : this.newIdentifiers) {
            identifier.setPatient(patient);
            for (final PatientIdentifier currentIdentifier : patient.getActiveIdentifiers()) {
                patient.removeIdentifier(currentIdentifier);
            }
        }

        patient.addIdentifiers(this.newIdentifiers);

        // find which identifiers they removed and void them
        // must create a new list so that the updated identifiers in
        // the newIdentifiers list are hashed correctly
        final List<PatientIdentifier> newIdentifiersList = new Vector<PatientIdentifier>();
        newIdentifiersList.addAll(this.newIdentifiers);
        for (final PatientIdentifier identifier : patient.getIdentifiers()) {
            if (!newIdentifiersList.contains(identifier)) {
                // mark the "removed" identifiers as voided
                identifier.setVoided(true);
                identifier.setVoidReason("Removed from new patient screen");
            }
        }

        // set the other patient attributes
        patient.setBirthdate(shortPatient.getBirthdate());
        patient.setBirthdateEstimated(shortPatient.getBirthdateEstimated());
        patient.setGender(shortPatient.getGender());

        patient.setDead(shortPatient.getDead());
        if (patient.isDead()) {
            patient.setDeathDate(shortPatient.getDeathDate());
            patient.setCauseOfDeath(shortPatient.getCauseOfDeath());
        } else {
            patient.setDeathDate(null);
            patient.setCauseOfDeath(null);
        }

        Patient newPatient = null;

        if (!isError) {
            // save or add the patient
            try {
                newPatient = ps.savePatient(patient);
            } catch (final InvalidIdentifierFormatException iife) {
                this.log.error(iife);
                patient.removeIdentifier(iife.getPatientIdentifier());
                httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                        "PatientIdentifier.error.formatInvalid");
                //errors = new BindException(new InvalidIdentifierFormatException(msa.getMessage("PatientIdentifier.error.formatInvalid")), "givenName");
                isError = true;
            } catch (final InvalidCheckDigitException icde) {
                this.log.error(icde);
                patient.removeIdentifier(icde.getPatientIdentifier());
                httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "PatientIdentifier.error.checkDigit");
                //errors = new BindException(new InvalidCheckDigitException(msa.getMessage("PatientIdentifier.error.checkDigit")), "givenName");
                isError = true;
            } catch (final IdentifierNotUniqueException inue) {
                this.log.error(inue);
                patient.removeIdentifier(inue.getPatientIdentifier());
                httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "PatientIdentifier.error.notUnique");
                //errors = new BindException(new IdentifierNotUniqueException(msa.getMessage("PatientIdentifier.error.notUnique")), "givenName");
                isError = true;
            } catch (final DuplicateIdentifierException die) {
                this.log.error(die);
                patient.removeIdentifier(die.getPatientIdentifier());
                httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "PatientIdentifier.error.duplicate");
                //errors = new BindException(new DuplicateIdentifierException(msa.getMessage("PatientIdentifier.error.duplicate")), "givenName");
                isError = true;
            } catch (final InsufficientIdentifiersException iie) {
                this.log.error(iie);
                patient.removeIdentifier(iie.getPatientIdentifier());
                httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                        "PatientIdentifier.error.insufficientIdentifiers");
                //errors = new BindException(new InsufficientIdentifiersException(msa.getMessage("PatientIdentifier.error.insufficientIdentifiers")), "givenName");
                isError = true;
            } catch (final PatientIdentifierException pie) {
                this.log.error(pie);
                patient.removeIdentifier(pie.getPatientIdentifier());
                httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, pie.getMessage());
                //errors = new BindException(new PatientIdentifierException(msa.getMessage("PatientIdentifier.error.general")), "givenName");
                isError = true;
            }

            // update the death reason
            if (patient.getDead()) {
                this.log.debug("Patient is dead, so let's make sure there's an Obs for it");
                // need to make sure there is an Obs that represents the patient's cause of death, if applicable

                final String codProp = Context.getAdministrationService()
                        .getGlobalProperty("concept.causeOfDeath");
                final Concept causeOfDeath = Context.getConceptService().getConcept(codProp);

                if (causeOfDeath != null) {
                    final List<Obs> obssDeath = Context.getObsService()
                            .getObservationsByPersonAndConcept(patient, causeOfDeath);
                    if (obssDeath != null) {
                        if (obssDeath.size() > 1) {
                            this.log.error(
                                    "Multiple causes of death (" + obssDeath.size() + ")?  Shouldn't be...");
                        } else {
                            Obs obsDeath = null;
                            if (obssDeath.size() == 1) {
                                // already has a cause of death - let's edit it.
                                this.log.debug("Already has a cause of death, so changing it");

                                obsDeath = obssDeath.iterator().next();

                            } else {
                                // no cause of death obs yet, so let's make one
                                this.log.debug("No cause of death yet, let's create one.");

                                obsDeath = new Obs();
                                obsDeath.setPerson(patient);
                                obsDeath.setConcept(causeOfDeath);

                                // Get default location
                                final Location loc = Context.getLocationService().getDefaultLocation();

                                // TODO person healthcenter if ( loc == null ) loc = patient.getHealthCenter();
                                if (loc != null) {
                                    obsDeath.setLocation(loc);
                                } else {
                                    this.log.error(
                                            "Could not find a suitable location for which to create this new Obs");
                                }
                            }

                            // put the right concept and (maybe) text in this obs
                            Concept currCause = patient.getCauseOfDeath();
                            if (currCause == null) {
                                // set to NONE
                                this.log.debug("Current cause is null, attempting to set to NONE");
                                final String noneConcept = Context.getAdministrationService()
                                        .getGlobalProperty("concept.none");
                                currCause = Context.getConceptService().getConcept(noneConcept);
                            }

                            if (currCause != null) {
                                this.log.debug("Current cause is not null, setting to value_coded");
                                obsDeath.setValueCoded(currCause);
                                obsDeath.setValueCodedName(currCause.getName()); // ABKTODO: presume current locale?

                                Date dateDeath = patient.getDeathDate();
                                if (dateDeath == null) {
                                    dateDeath = new Date();
                                }
                                obsDeath.setObsDatetime(dateDeath);

                                // check if this is an "other" concept - if so, then we need to add value_text
                                final String otherConcept = Context.getAdministrationService()
                                        .getGlobalProperty("concept.otherNonCoded");
                                final Concept conceptOther = Context.getConceptService()
                                        .getConcept(otherConcept);
                                if (conceptOther != null) {
                                    if (conceptOther.equals(currCause)) {
                                        // seems like this is an other concept - let's try to get the "other" field info
                                        final String otherInfo = ServletRequestUtils.getStringParameter(request,
                                                "causeOfDeath_other", "");
                                        this.log.debug("Setting value_text as " + otherInfo);
                                        obsDeath.setValueText(otherInfo);
                                    } else {
                                        this.log.debug(
                                                "New concept is NOT the OTHER concept, so setting to blank");
                                        obsDeath.setValueText("");
                                    }
                                } else {
                                    this.log.debug(
                                            "Don't seem to know about an OTHER concept, so deleting value_text");
                                    obsDeath.setValueText("");
                                }

                                if (!StringUtils.hasText(obsDeath.getVoidReason())) {
                                    obsDeath.setVoidReason(Context.getMessageSourceService()
                                            .getMessage("general.default.changeReason"));
                                }
                                Context.getObsService().saveObs(obsDeath, obsDeath.getVoidReason());
                            } else {
                                this.log.debug("Current cause is still null - aborting mission");
                            }
                        }
                    }
                } else {
                    this.log.debug(
                            "Cause of death is null - should not have gotten here without throwing an error on the form.");
                }

            }

        }

        // save the relationships to the database
        if (!isError && !errors.hasErrors()) {
            final Map<String, Relationship> relationships = getRelationshipsMap(patient, request);
            for (final Relationship relationship : relationships.values()) {
                // if the user added a person to this relationship, save it
                if ((relationship.getPersonA() != null) && (relationship.getPersonB() != null)) {
                    personService.saveRelationship(relationship);
                }
            }

            //save email to messaging_addresses table
            Integer addressId = saveEmail(newPatient, email);
            //set default messaging alert address
            boolean shouldAlert = true;
            PersonalhrUtil.setMessagingAlertSettings(newPatient, shouldAlert, addressId);

        }

        // redirect if an error occurred
        if (isError || errors.hasErrors()) {
            this.log.error("Had an error during processing. Redirecting to " + this.getSuccessView());

            final Map<String, Object> model = new HashMap<String, Object>();
            model.put(getCommandName(), new ShortPatientModel(patient));

            // evict from session so that nothing temporarily added here is saved
            Context.evictFromSession(patient);

            httpSession.setAttribute(WebConstants.OPENMRS_HEADER_USE_MINIMAL, "false");

            return this.showForm(request, response, errors, model);
            //return new ModelAndView(new RedirectView("findPatient.htm"));
        } else {
            httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Patient.saved");
            this.log.debug("Patient saved! Redirect to " + this.getSuccessView() + "?patientId="
                    + newPatient.getPatientId());
            request.getSession().setAttribute(WebConstants.OPENMRS_HEADER_USE_MINIMAL, "false");
            return new ModelAndView(
                    new RedirectView(this.getSuccessView() + "?patientId=" + newPatient.getPatientId()));
        }

    } else {
        return new ModelAndView(new RedirectView(getFormView()));
    }
}

From source file:org.openmrs.module.sync.web.controller.SettingsController.java

@Override
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse reponse, Object obj,
        BindException errors) throws Exception {

    log.debug("in processFormSubmission");

    ModelAndView result = new ModelAndView(new RedirectView(getSuccessView()));

    if (!Context.isAuthenticated())
        throw new APIAuthenticationException("Not authenticated!");

    HttpSession httpSession = request.getSession();
    String success = "";
    String error = "";
    MessageSourceAccessor msa = getMessageSourceAccessor();
    String action = ServletRequestUtils.getStringParameter(request, "action", "");
    log.debug("action is " + action);
    if ("saveGeneral".equals(action)) {
        String serverName = ServletRequestUtils.getStringParameter(request, "serverName", "");
        String adminEmail = ServletRequestUtils.getStringParameter(request, "adminEmail", "");
        Context.getService(SyncService.class).saveServerName(serverName);
        Context.getService(SyncService.class).saveAdminEmail(adminEmail);

        String[] startedParams = request.getParameterValues("started");
        boolean started = false;
        if (startedParams != null) {
            for (String startedParam : startedParams) {
                if (startedParam.equals("true"))
                    started = true;//from  w w w.  j av  a  2 s  . c o m
            }
        }
        Integer repeatInterval = ServletRequestUtils.getIntParameter(request, "repeatInterval", 0) * 60;

        if (started) {
            started = false;
            repeatInterval = null;
            error = msa.getMessage("NzeyiSynchronizationConfig.server.error.disabledSyncSchedule");
        }
        if (started && repeatInterval < 1)
            error = msa.getMessage("SynchronizationConfig.server.error.invalidRepeat");

        if (error.length() == 0) {
            RemoteServer parent = Context.getService(SyncService.class).getParentServer();
            if (parent != null) {
                if (parent.getServerId() != null) {
                    Integer serverId = parent.getServerId();
                    TaskDefinition serverSchedule = null;
                    Collection<TaskDefinition> tasks = Context.getSchedulerService().getRegisteredTasks();
                    if (tasks != null) {
                        for (TaskDefinition task : tasks) {
                            if (task.getTaskClass().equals(SyncConstants.SCHEDULED_TASK_CLASS)) {
                                if (serverId.toString().equals(
                                        task.getProperty(SyncConstants.SCHEDULED_TASK_PROPERTY_SERVER_ID))) {
                                    serverSchedule = task;
                                } else {
                                    log.warn("not equal comparing " + serverId + " to " + task
                                            .getProperty(SyncConstants.SCHEDULED_TASK_PROPERTY_SERVER_ID));
                                }
                            } else {
                                log.warn("not equal comparing " + task.getTaskClass() + " to "
                                        + SyncConstants.SCHEDULED_TASK_CLASS);
                            }
                        }
                    } else {
                        log.warn("tasks is null");
                    }
                    Map<String, String> props = new HashMap<String, String>();
                    props.put(SyncConstants.SCHEDULED_TASK_PROPERTY_SERVER_ID, serverId.toString());
                    if (serverSchedule != null) {
                        if (log.isInfoEnabled())
                            log.info("Sync scheduled task exists, and started is " + started
                                    + " and interval is " + repeatInterval);
                        try {
                            Context.getSchedulerService().shutdownTask(serverSchedule);
                        } catch (Exception e) {
                            log.warn(
                                    "Sync task had run wild, couldn't stop it because it wasn't really running",
                                    e);
                        }
                        serverSchedule.setStarted(started);
                        serverSchedule.setRepeatInterval((long) repeatInterval);
                        serverSchedule.setStartOnStartup(started);
                        serverSchedule.setProperties(props);
                        if (started) {
                            serverSchedule.setStartTime(new Date());
                        }
                        Context.getSchedulerService().saveTask(serverSchedule);
                        if (started) {
                            Context.getSchedulerService().scheduleTask(serverSchedule);
                        }
                    } else {
                        if (log.isInfoEnabled())
                            log.info("Sync scheduled task does not exists, and started is " + started
                                    + " and interval is " + repeatInterval);
                        if (started) {
                            serverSchedule = new TaskDefinition();
                            serverSchedule.setName(parent.getNickname() + " "
                                    + msa.getMessage("SynchronizationConfig.server.scheduler"));
                            serverSchedule.setDescription(
                                    msa.getMessage("SynchronizationConfig.server.scheduler.description"));
                            serverSchedule.setRepeatInterval((long) repeatInterval);
                            serverSchedule.setStartTime(new Date());
                            serverSchedule.setTaskClass(SyncConstants.SCHEDULED_TASK_CLASS);
                            serverSchedule.setStarted(started);
                            serverSchedule.setStartOnStartup(started);
                            serverSchedule.setProperties(props);
                            Context.getSchedulerService().saveTask(serverSchedule);
                            Context.getSchedulerService().scheduleTask(serverSchedule);
                        }
                    }

                }
            }
            success = msa.getMessage("SynchronizationConfig.server.saved");
        }
    } else if ("deleteServer".equals(action)) {
        // check to see if the user is trying to delete a server, react
        // accordingly
        Integer serverId = ServletRequestUtils.getIntParameter(request, "serverId", 0);
        String serverName = "Server " + serverId.toString();

        SyncService ss = Context.getService(SyncService.class);

        if (serverId > 0) {
            RemoteServer deleteServer = ss.getRemoteServer(serverId);
            serverName = deleteServer.getNickname();

            try {
                ss.deleteRemoteServer(deleteServer);
                Object[] args = { serverName };
                success = msa.getMessage("SynchronizationConfig.server.deleted", args);
            } catch (Exception e) {
                Object[] args = { serverName };
                error = msa.getMessage("SynchronizationConfig.server.deleteFailed", args);
            }
        } else {
            error = msa.getMessage("SynchronizationConfig.server.notDeleted");
        }

    } else if ("saveClasses".equals(action)) {
        String[] classIdsTo = ServletRequestUtils.getRequiredStringParameters(request, "toDefault");
        String[] classIdsFrom = ServletRequestUtils.getRequiredStringParameters(request, "fromDefault");
        Set<String> idsTo = new HashSet<String>();
        Set<String> idsFrom = new HashSet<String>();
        if (classIdsTo != null)
            idsTo.addAll(Arrays.asList(classIdsTo));
        if (classIdsFrom != null)
            idsFrom.addAll(Arrays.asList(classIdsFrom));

        List<SyncClass> syncClasses = Context.getService(SyncService.class).getSyncClasses();
        if (syncClasses != null) {
            // log.warn("SYNCCLASSES IS SIZE: " + syncClasses.size());
            for (SyncClass syncClass : syncClasses) {
                if (idsTo.contains(syncClass.getSyncClassId().toString()))
                    syncClass.setDefaultSendTo(true);
                else
                    syncClass.setDefaultSendTo(false);
                if (idsFrom.contains(syncClass.getSyncClassId().toString()))
                    syncClass.setDefaultReceiveFrom(true);
                else
                    syncClass.setDefaultReceiveFrom(false);
                Context.getService(SyncService.class).saveSyncClass(syncClass);
            }
        }

        success = msa.getMessage("SynchronizationConfig.classes.saved");
    }
    if (!success.equals(""))
        httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, success);
    if (!error.equals(""))
        httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, error);

    return result;
}

From source file:org.openmrs.module.restrictbyuser.web.controller.RestrictByUserFormController.java

/**
 * The onSubmit function receives the form/command object that was modified
 * by the input form and saves it to the db
 * /*from w  w w .  j ava2 s  . co m*/
 * @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse, java.lang.Object,
 *      org.springframework.validation.BindException)
 */
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object obj,
        BindException errors) throws Exception {

    HttpSession httpSession = request.getSession();
    MessageSourceAccessor msa = getMessageSourceAccessor();
    String userId = request.getParameter("userId");
    String view = getSuccessView();

    if (Context.isAuthenticated()
            && Context.getAuthenticatedUser().hasPrivilege(ModConstants.MANAGE_USER_RESTRICTIONS)) {
        String patientId = ServletRequestUtils.getStringParameter(request, "patientId");

        /* Assign proxy privileges needed for the operations */
        try {
            Context.addProxyPrivilege(PrivilegeConstants.VIEW_USERS);
            Context.addProxyPrivilege(PrivilegeConstants.EDIT_USERS);

            if (StringUtils.hasText(userId)) {
                UserService us = Context.getService(UserService.class);
                PatientService ps = Context.getPatientService();
                String message = "";
                String success = "";
                String error = "";

                User u = (User) us.getUser(Integer.parseInt(userId));
                String remove = request.getParameter("remove");

                /* Remove patients in the list */
                if (remove != null) {
                    String[] patientList = ServletRequestUtils.getStringParameters(request, "patientId");
                    if (patientList.length > 0) {
                        for (String p : patientList) {
                            u.removePatient(ps.getPatient(Integer.parseInt(p)));
                        }
                        message = WebConstants.OPENMRS_MSG_ATTR;
                        success = msa.getMessage("restrictbyuser.form.success.remove");
                    } else {
                        message = WebConstants.OPENMRS_ERROR_ATTR;
                        error = msa.getMessage("restrictbyuser.form.error.noPatient");
                    }
                    /* If a valid patient is selected, add it to the object */
                } else if (patientId != "") {
                    Patient p = ps.getPatient(Integer.parseInt(patientId));
                    if (u.getPatients().contains(p)) {
                        message = WebConstants.OPENMRS_ERROR_ATTR;
                        error = msa.getMessage("restrictbyuser.form.error.duplicate");
                    } else {
                        u.addPatient(ps.getPatient(Integer.parseInt(patientId)));
                        message = WebConstants.OPENMRS_MSG_ATTR;
                        success = msa.getMessage("restrictbyuser.form.success.add");
                    }
                    /*
                     * If an invalide patient is selected, set display error
                     * message
                     */
                } else if (patientId == "") {
                    error = msa.getMessage("restrictbyuser.form.error.invalidPatient");
                }

                /* Dispaly error message and save changes */
                if (message == WebConstants.OPENMRS_ERROR_ATTR) {
                    httpSession.setAttribute(message, error);
                } else {
                    u = (User) us.saveUser(u, null);
                    httpSession.setAttribute(message, success);
                }
            } else {
                httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                        msa.getMessage("restrictbyuser.form.error"));
            }
        } finally {
            Context.removeProxyPrivilege(PrivilegeConstants.VIEW_USERS);
            Context.removeProxyPrivilege(PrivilegeConstants.EDIT_USERS);
        }

    }

    return new ModelAndView(new RedirectView(view + "?userId=" + request.getParameter("userId")));
}

From source file:org.openmrs.web.controller.ConceptStatsFormController.java

/**
 * Called prior to form display. Allows for data to be put in the request to be used in the view
 *
 * @see org.springframework.web.servlet.mvc.SimpleFormController#referenceData(javax.servlet.http.HttpServletRequest)
 *//*from ww w .j a  va  2  s  .co  m*/
protected Map<String, Object> referenceData(HttpServletRequest request) throws Exception {

    Map<String, Object> map = new HashMap<String, Object>();
    if (!Context.hasPrivilege("View Observations")) {
        return map;
    }

    MessageSourceAccessor msa = getMessageSourceAccessor();
    Locale locale = Context.getLocale();
    ConceptService cs = Context.getConceptService();
    String conceptId = request.getParameter("conceptId");
    //List<Obs> obs = new Vector<Obs>();
    //List<Obs> obsAnswered = new Vector<Obs>();

    if (conceptId != null) {
        Concept concept = cs.getConcept(Integer.valueOf(conceptId));
        ObsService obsService = Context.getObsService();

        if (concept != null) {

            // previous/next ids for links
            map.put("previousConcept", cs.getPrevConcept(concept));
            map.put("nextConcept", cs.getNextConcept(concept));

            //obs = obsService.getObservations(concept, "valueNumeric, obsId");
            //obsAnswered = obsService.getObservationsAnsweredByConcept(concept);

            if (ConceptDatatype.NUMERIC.equals(concept.getDatatype().getHl7Abbreviation())) {
                map.put("displayType", "numeric");

                List<Obs> numericAnswers = obsService.getObservations(null, null,
                        Collections.singletonList(concept), null,
                        Collections.singletonList(OpenmrsConstants.PERSON_TYPE.PERSON), null,
                        Collections.singletonList("valueNumeric"), null, null, null, null, false);

                if (numericAnswers.size() > 0) {
                    Double min = numericAnswers.get(0).getValueNumeric();
                    Double max = (Double) numericAnswers.get(numericAnswers.size() - 1).getValueNumeric();
                    Double median = (Double) numericAnswers.get(numericAnswers.size() / 2).getValueNumeric();

                    Map<Double, Integer> counts = new HashMap<Double, Integer>(); // counts for the histogram
                    Double total = 0.0; // sum of values. used for mean

                    // dataset setup for lineChart
                    TimeSeries timeSeries = new TimeSeries(concept.getName().getName(), Day.class);
                    TimeSeriesCollection timeDataset = new TimeSeriesCollection();
                    Calendar calendar = Calendar.getInstance();

                    // array for histogram
                    double[] obsNumerics = new double[(numericAnswers.size())];

                    Integer i = 0;
                    for (Obs obs : numericAnswers) {
                        Date date = (Date) obs.getObsDatetime();
                        Double value = (Double) obs.getValueNumeric();

                        // for mean calculation
                        total += value;

                        // for histogram
                        obsNumerics[i++] = value;
                        Integer count = counts.get(value);
                        counts.put(value, count == null ? 1 : count + 1);

                        // for line chart
                        calendar.setTime(date);
                        Day day = new Day(calendar.get(Calendar.DAY_OF_MONTH), calendar.get(Calendar.MONTH) + 1, // January = 0 
                                calendar.get(Calendar.YEAR) < 1900 ? 1900 : calendar.get(Calendar.YEAR) // jfree chart doesn't like the 19th century
                        );
                        timeSeries.addOrUpdate(day, value);
                    }

                    Double size = new Double(numericAnswers.size());
                    Double mean = total / size;

                    map.put("size", numericAnswers.size());
                    map.put("min", min);
                    map.put("max", max);
                    map.put("mean", mean);
                    map.put("median", median);

                    // create histogram chart
                    HistogramDataset histDataset = new HistogramDataset(); // dataset for histogram
                    histDataset.addSeries(concept.getName().getName(), obsNumerics, counts.size());

                    JFreeChart histogram = ChartFactory.createHistogram(concept.getName().getName(),
                            msa.getMessage("Concept.stats.histogramDomainAxisTitle"),
                            msa.getMessage("Concept.stats.histogramRangeAxisTitle"), histDataset,
                            PlotOrientation.VERTICAL, false, true, false);
                    map.put("histogram", histogram);

                    if (size > 25) {
                        // calculate 98th percentile of the data:
                        Double x = 0.98;
                        Integer xpercentile = (int) (x * size);
                        Double upperQuartile = numericAnswers.get(xpercentile).getValueNumeric();
                        Double lowerQuartile = numericAnswers.get((int) (size - xpercentile)).getValueNumeric();
                        Double innerQuartile = upperQuartile - lowerQuartile;
                        Double innerQuartileLimit = innerQuartile * 1.5; // outliers will be greater than this from the upper/lower quartile
                        Double upperQuartileLimit = upperQuartile + innerQuartileLimit;
                        Double lowerQuartileLimit = lowerQuartile - innerQuartileLimit;

                        List<Obs> outliers = new Vector<Obs>();

                        // move outliers to the outliers list
                        // removing lower quartile outliers
                        for (i = 0; i < size - xpercentile; i++) {
                            Obs possibleOutlier = numericAnswers.get(i);
                            if (possibleOutlier.getValueNumeric() >= lowerQuartileLimit) {
                                break; // quit if this value is greater than the lower limit
                            }
                            outliers.add(possibleOutlier);
                        }

                        // removing upper quartile outliers
                        for (i = size.intValue() - 1; i >= xpercentile; i--) {
                            Obs possibleOutlier = numericAnswers.get(i);
                            if (possibleOutlier.getValueNumeric() <= upperQuartileLimit) {
                                break; // quit if this value is less than the upper limit
                            }
                            outliers.add(possibleOutlier);
                        }
                        numericAnswers.removeAll(outliers);

                        double[] obsNumericsOutliers = new double[(numericAnswers.size())];
                        i = 0;
                        counts.clear();
                        for (Obs values : numericAnswers) {
                            Double value = values.getValueNumeric();
                            obsNumericsOutliers[i++] = value;
                            Integer count = counts.get(value);
                            counts.put(value, count == null ? 1 : count + 1);
                        }

                        // create outlier histogram chart
                        HistogramDataset outlierHistDataset = new HistogramDataset();
                        outlierHistDataset.addSeries(concept.getName().getName(), obsNumericsOutliers,
                                counts.size());

                        JFreeChart histogramOutliers = ChartFactory.createHistogram(concept.getName().getName(),
                                msa.getMessage("Concept.stats.histogramDomainAxisTitle"),
                                msa.getMessage("Concept.stats.histogramRangeAxisTitle"), outlierHistDataset,
                                PlotOrientation.VERTICAL, false, true, false);
                        map.put("histogramOutliers", histogramOutliers);
                        map.put("outliers", outliers);

                    }

                    // create line graph chart
                    timeDataset.addSeries(timeSeries);
                    JFreeChart lineChart = ChartFactory.createTimeSeriesChart(concept.getName().getName(),
                            msa.getMessage("Concept.stats.lineChartDomainAxisLabel"),
                            msa.getMessage("Concept.stats.lineChartRangeAxisLabel"), timeDataset, false, true,
                            false);
                    map.put("timeSeries", lineChart);

                }
            } else if (ConceptDatatype.BOOLEAN.equals(concept.getDatatype().getHl7Abbreviation())) {
                // create bar chart for boolean answers
                map.put("displayType", "boolean");

                List<Obs> obs = obsService.getObservations(null, null, Collections.singletonList(concept), null,
                        Collections.singletonList(OpenmrsConstants.PERSON_TYPE.PERSON), null, null, null, null,
                        null, null, false);

                DefaultPieDataset pieDataset = new DefaultPieDataset();

                // count the number of unique answers
                Map<String, Integer> counts = new HashMap<String, Integer>();
                for (Obs o : obs) {
                    Boolean answer = o.getValueAsBoolean();
                    if (answer == null) {
                        answer = false;
                    }
                    String name = answer.toString();
                    Integer count = counts.get(name);
                    counts.put(name, count == null ? 1 : count + 1);
                }

                // put the counts into the dataset
                for (Map.Entry<String, Integer> entry : counts.entrySet()) {
                    pieDataset.setValue(entry.getKey(), entry.getValue());
                }

                JFreeChart pieChart = ChartFactory.createPieChart(concept.getName().getName(), pieDataset, true,
                        true, false);
                map.put("pieChart", pieChart);

            } else if (ConceptDatatype.CODED.equals(concept.getDatatype().getHl7Abbreviation())) {
                // create pie graph for coded answers
                map.put("displayType", "coded");

                List<Obs> obs = obsService.getObservations(null, null, Collections.singletonList(concept), null,
                        Collections.singletonList(OpenmrsConstants.PERSON_TYPE.PERSON), null, null, null, null,
                        null, null, false);

                DefaultPieDataset pieDataset = new DefaultPieDataset();

                // count the number of unique answers
                Map<String, Integer> counts = new HashMap<String, Integer>();
                for (Obs o : obs) {
                    Concept value = o.getValueCoded();
                    String name;
                    if (value == null) {
                        name = "[value_coded is null]";
                    } else {
                        name = value.getName().getName();
                    }
                    Integer count = counts.get(name);
                    counts.put(name, count == null ? 1 : count + 1);
                }

                // put the counts into the dataset
                for (Map.Entry<String, Integer> entry : counts.entrySet()) {
                    pieDataset.setValue(entry.getKey(), entry.getValue());
                }

                JFreeChart pieChart = ChartFactory.createPieChart(concept.getName().getName(), pieDataset, true,
                        true, false);
                map.put("pieChart", pieChart);

            }
        }

    }

    //map.put("obs", obs);
    //map.put("obsAnswered", obsAnswered);

    map.put("locale", locale.getLanguage().substring(0, 2));

    return map;
}

From source file:org.openmrs.module.amrscustomization.web.controller.CustomConceptProposalFormController.java

/**
 * @see org.springframework.web.servlet.mvc.SimpleFormController#processFormSubmission(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse, java.lang.Object,
 *      org.springframework.validation.BindException)
 *//* www. j av a 2  s . c  o m*/
@Override
protected ModelAndView processFormSubmission(HttpServletRequest request, HttpServletResponse response,
        Object obj, BindException errors) throws Exception {

    HttpSession httpSession = request.getSession();
    ConceptProposal cp = (ConceptProposal) obj;
    String action = request.getParameter("action");

    Concept c = null;
    if (StringUtils.hasText(request.getParameter("conceptId")))
        c = Context.getConceptService().getConcept(Integer.valueOf(request.getParameter("conceptId")));
    cp.setMappedConcept(c);

    MessageSourceAccessor msa = getMessageSourceAccessor();
    if (action.equals(msa.getMessage("general.cancel"))) {
        httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "general.canceled");
        return new ModelAndView(new RedirectView(getSuccessView()));
    } else if (action.equals(msa.getMessage("ConceptProposal.ignore"))) {
        cp.setState(OpenmrsConstants.CONCEPT_PROPOSAL_REJECT);
    } else {
        // Set the state of the concept according to the button pushed
        if (cp.getMappedConcept() == null)
            errors.rejectValue("mappedConcept", "amrscustomization.ConceptProposal.mappedConcept.error");
        else {
            String proposalAction = request.getParameter("actionToTake");
            if (proposalAction.equals("createObsAndIgnoreProposal")) {
                cp.setState(OpenmrsConstants.CONCEPT_PROPOSAL_CONCEPT);
            } else if (proposalAction.equals("saveAsSynonym")) {
                if (cp.getMappedConcept() == null)
                    errors.rejectValue("mappedConcept",
                            "amrscustomization.ConceptProposal.mappedConcept.error");
                if (!StringUtils.hasText(cp.getFinalText()))
                    errors.rejectValue("finalText", "error.null");
                cp.setState(OpenmrsConstants.CONCEPT_PROPOSAL_SYNONYM);
            }
        }
    }

    return super.processFormSubmission(request, response, cp, errors);
}

From source file:org.openmrs.web.controller.ConceptFormController.java

/**
 * The onSubmit function receives the form/command object that was modified by the input form
 * and saves it to the db//  w  w w  .j  a va 2 s . c o  m
 *
 * @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse, java.lang.Object,
 *      org.springframework.validation.BindException)
 * @should display numeric values from table
 * @should copy numeric values into numeric concepts
 * @should return a concept with a null id if no match is found
 * @should void a synonym marked as preferred when it is removed
 * @should set the local preferred name
 * @should add a new Concept map to an existing concept
 * @should remove a concept map from an existing concept
 * @should ignore new concept map row if the user did not select a term
 * @should add a new Concept map when creating a concept
 * @should not save changes if there are validation errors
 */
@Override
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object obj,
        BindException errors) throws Exception {

    HttpSession httpSession = request.getSession();
    ConceptService cs = Context.getConceptService();

    if (Context.isAuthenticated()) {

        ConceptFormBackingObject conceptBackingObject = (ConceptFormBackingObject) obj;
        MessageSourceAccessor msa = getMessageSourceAccessor();
        String action = request.getParameter("action");

        if (action.equals(msa.getMessage("general.retire"))) {
            Concept concept = conceptBackingObject.getConcept();
            try {
                String reason = request.getParameter("retiredReason");
                if (!StringUtils.hasText(reason)) {
                    reason = msa.getMessage("general.default.retireReason");
                }
                cs.retireConcept(concept, reason);
                httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Concept.concept.retired.successFully");
                return new ModelAndView(
                        new RedirectView(getSuccessView() + "?conceptId=" + concept.getConceptId()));
            } catch (APIException e) {
                log.error("Unable to Retire concept because an error occurred: " + concept, e);
                httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "general.cannot.retire");
            }
            // return to the edit screen because an error was thrown
            return new ModelAndView(
                    new RedirectView(getSuccessView() + "?conceptId=" + concept.getConceptId()));

        } else if (action.equals(msa.getMessage("general.unretire"))) {
            Concept concept = conceptBackingObject.getConcept();
            try {
                concept.setRetired(false);
                cs.saveConcept(concept);
                httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR,
                        "Concept.concept.unRetired.successFully");
                return new ModelAndView(
                        new RedirectView(getSuccessView() + "?conceptId=" + concept.getConceptId()));
            } catch (ConceptsLockedException cle) {
                log.error("Tried to unretire concept while concepts were locked", cle);
                httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Concept.concepts.locked.unRetire");
            } catch (DuplicateConceptNameException e) {
                log.error("Tried to unretire concept with a duplicate name", e);
                httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "general.cannot.unretire");
            } catch (APIException e) {
                log.error("Error while trying to unretire concept", e);
                httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "general.cannot.unretire");
            }
            // return to the edit screen because an error was thrown
            return new ModelAndView(
                    new RedirectView(getSuccessView() + "?conceptId=" + concept.getConceptId()));

        } else if (action.equals(msa.getMessage("Concept.delete", "Delete Concept"))) {
            Concept concept = conceptBackingObject.getConcept();
            try {
                cs.purgeConcept(concept);
                httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Concept.deleted");
                return new ModelAndView(new RedirectView("index.htm"));
            } catch (ConceptsLockedException cle) {
                log.error("Tried to delete concept while concepts were locked", cle);
                httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Concept.concepts.locked");
            } catch (DataIntegrityViolationException e) {
                log.error("Unable to delete a concept because it is in use: " + concept, e);
                httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Concept.cannot.delete");
            } catch (Exception e) {
                log.error("Unable to delete concept because an error occurred: " + concept, e);
                httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Concept.cannot.delete");
            }
            // return to the edit screen because an error was thrown
            return new ModelAndView(
                    new RedirectView(getSuccessView() + "?conceptId=" + concept.getConceptId()));
        } else {
            Concept concept = conceptBackingObject.getConceptFromFormData();
            //if the user is editing a concept, initialise the associated creator property
            //this is aimed at avoiding a lazy initialisation exception when rendering
            //the jsp after validation has failed
            if (concept.getConceptId() != null) {
                concept.getCreator().getPersonName();
            }

            try {
                errors.pushNestedPath("concept");
                ValidateUtil.validate(concept, errors);
                errors.popNestedPath();

                validateConceptUsesPersistedObjects(concept, errors);

                if (!errors.hasErrors()) {
                    if (action.equals(msa.getMessage("Concept.cancel"))) {
                        return new ModelAndView(new RedirectView("index.htm"));
                    }
                    cs.saveConcept(concept);
                    httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Concept.saved");
                    if (action.equals(msa.getMessage("Concept.save"))) {
                        return new ModelAndView(
                                new RedirectView("concept.htm" + "?conceptId=" + concept.getConceptId()));
                    }
                    return new ModelAndView(
                            new RedirectView(getSuccessView() + "?conceptId=" + concept.getConceptId()));
                }
                httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Concept.cannot.save");
            } catch (ConceptsLockedException cle) {
                errors.popNestedPath();
                log.error("Tried to save concept while concepts were locked", cle);
                httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Concept.concepts.locked");
                errors.reject("concept", "Concept.concepts.locked");
            } catch (DuplicateConceptNameException e) {
                errors.popNestedPath();
                log.error("Tried to save concept with a duplicate name", e);
                httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Concept.cannot.save");
                errors.rejectValue("concept", "Concept.name.duplicate");
            } catch (APIException e) {
                errors.popNestedPath();
                log.error("Error while trying to save concept", e);
                httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Concept.cannot.save");
                errors.reject("concept", "Concept.cannot.save");
            }
        }
        // return to the edit form because an error was thrown
        return showForm(request, response, errors);
    }

    return new ModelAndView(new RedirectView(getFormView()));
}