Example usage for org.springframework.web.context.request WebRequest setAttribute

List of usage examples for org.springframework.web.context.request WebRequest setAttribute

Introduction

In this page you can find the example usage for org.springframework.web.context.request WebRequest setAttribute.

Prototype

void setAttribute(String name, Object value, int scope);

Source Link

Document

Set the value for the scoped attribute of the given name, replacing an existing value (if any).

Usage

From source file:org.openmrs.web.controller.concept.ConceptReferenceTermFormController.java

/**
 * Processes requests to retire concept reference terms
 *
 * @param request the {@link WebRequest} object
 * @param conceptReferenceTermModel the concept reference term model for the term to retire
 * @param retireReason the reason why the concept reference term is being retired
 * @return the url to redirect to//  ww  w .j a  va 2  s . co m
 */
@RequestMapping(method = RequestMethod.POST, value = "/admin/concepts/retireConceptReferenceTerm")
public String retireConceptReferenceTerm(WebRequest request,
        @ModelAttribute(value = "conceptReferenceTermModel") ConceptReferenceTermModel conceptReferenceTermModel,
        @RequestParam(required = false, value = "retireReason") String retireReason) {

    if (!StringUtils.hasText(retireReason)) {
        retireReason = Context.getMessageSourceService().getMessage("general.default.retireReason");
    }

    try {
        ConceptReferenceTerm conceptReferenceTerm = conceptReferenceTermModel.getConceptReferenceTerm();
        Context.getConceptService().retireConceptReferenceTerm(conceptReferenceTerm, retireReason);
        if (log.isDebugEnabled()) {
            log.debug("Retired concept reference term with id: " + conceptReferenceTerm.getId());
        }
        request.setAttribute(WebConstants.OPENMRS_MSG_ATTR,
                Context.getMessageSourceService().getMessage("ConceptReferenceTerm.retired"),
                WebRequest.SCOPE_SESSION);

        return "redirect:" + FIND_CONCEPT_REFERENCE_TERM_URL;
    } catch (APIException e) {
        log.error("Error occurred while retiring concept reference term", e);
        request.setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                Context.getMessageSourceService().getMessage("ConceptReferenceTerm.retire.error"),
                WebRequest.SCOPE_SESSION);
    }

    //an error occurred
    return CONCEPT_REFERENCE_TERM_FORM;
}

From source file:org.openmrs.module.dhisreport.web.controller.Dhis2ServerController.java

@RequestMapping(value = "/module/dhisreport/testconnection", method = RequestMethod.POST)
public String CheckConnectionWithDHIS2(ModelMap model, WebRequest webRequest) {
    DHIS2ReportingService service = Context.getService(DHIS2ReportingService.class);
    HttpDhis2Server server = service.getDhis2Server();
    String dhisurl = Context.getAdministrationService().getGlobalProperty("dhisreport.dhis2URL");
    String dhisusername = Context.getAdministrationService().getGlobalProperty("dhisreport.dhis2UserName");
    String dhispassword = Context.getAdministrationService().getGlobalProperty("dhisreport.dhis2Password");

    URL url = null;//from   ww w  . j a v a  2  s . c  o m
    try {
        url = new URL(dhisurl);
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    boolean val = testConnection(url, dhisusername, dhispassword, server, webRequest, model);

    String referer = webRequest.getHeader("Referer");

    if (val == false) {
        webRequest.setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                Context.getMessageSourceService().getMessage("dhisreport.dhis2ConnectionFailure"),
                WebRequest.SCOPE_SESSION);
        return "redirect:" + referer;
    }
    webRequest.setAttribute(WebConstants.OPENMRS_MSG_ATTR,
            Context.getMessageSourceService().getMessage("dhisreport.dhis2ConnectionSuccess"),
            WebRequest.SCOPE_SESSION);
    return "redirect:" + referer;
}

From source file:org.openmrs.module.dhisconnector.web.controller.DHISConnectorController.java

@RequestMapping(value = "/module/dhisconnector/configureServer", method = RequestMethod.POST)
public void saveConfig(ModelMap model, @RequestParam(value = "url", required = true) String url,
        @RequestParam(value = "user", required = true) String user,
        @RequestParam(value = "pass", required = true) String pass, WebRequest req) throws ParseException {

    AdministrationService as = Context.getAdministrationService();
    GlobalProperty urlProperty = as.getGlobalPropertyObject(GLOBAL_PROPERTY_URL);
    GlobalProperty userProperty = as.getGlobalPropertyObject(GLOBAL_PROPERTY_USER);
    GlobalProperty passProperty = as.getGlobalPropertyObject(GLOBAL_PROPERTY_PASS);

    if (Context.getService(DHISConnectorService.class).testDHISServerDetails(url, user, pass)) {
        // Save the properties
        urlProperty.setPropertyValue(url);
        userProperty.setPropertyValue(user);
        passProperty.setPropertyValue(pass);

        as.saveGlobalProperty(urlProperty);
        as.saveGlobalProperty(userProperty);
        as.saveGlobalProperty(passProperty);

        req.setAttribute(WebConstants.OPENMRS_MSG_ATTR,
                Context.getMessageSourceService().getMessage("dhisconnector.saveSuccess"),
                WebRequest.SCOPE_SESSION);

        model.addAttribute("url", url);
        model.addAttribute("user", user);
        model.addAttribute("pass", pass);
    } else {/*from   w  w w  . j ava 2  s  . co m*/
        req.setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                Context.getMessageSourceService().getMessage("dhisconnector.saveFailure"),
                WebRequest.SCOPE_SESSION);

        model.addAttribute("url", urlProperty.getPropertyValue());
        model.addAttribute("user", userProperty.getPropertyValue());
        model.addAttribute("pass", passProperty.getPropertyValue());
    }
}

From source file:org.openmrs.module.formentry.web.controller.ManageXsnArchivesController.java

/**
 * accept POST requests to migrate specific XSNs to the filesystem
 * //w ww  .j  a  v a 2s .c  om
 * @param xsnIds list of XSN identifiers to be moved
 * @param modelMap the model for the resulting JSP
 * @return path to the JSP file
 */
@SuppressWarnings("unchecked")
@RequestMapping(method = RequestMethod.POST)
public String migrateXSNs(WebRequest request,
        @RequestParam(value = "xsnIds", required = false) List<Integer> xsnIds, ModelMap modelMap) {
    FormEntryService service = Context.getService(FormEntryService.class);
    int succeeded = 0;
    List<Integer> failed = new ArrayList<Integer>();

    if (xsnIds == null)
        xsnIds = new ArrayList<Integer>();

    // migrate XSNs one by one
    for (Integer xsnId : xsnIds) {
        try {
            FormEntryXsn xsn = service.getFormEntryXsnById(xsnId);
            service.migrateFormEntryXsnToFilesystem(xsn);
            log.info("migrated Form Entry XSN #" + xsnId + " to the filesystem.");
            succeeded++;
        } catch (APIException e) {
            log.error("could not migrate Form Entry XSN #" + xsnId + " to the filesystem.", e);
            failed.add(xsnId);
        }
    }

    // send success / error messages back
    String msg = null;
    if (succeeded > 0) {
        if (succeeded == 1)
            request.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "formentry.xsnarchives.success.single",
                    WebRequest.SCOPE_SESSION);
        else {
            msg = Context.getMessageSourceService().getMessage("formentry.xsnarchives.success",
                    new Object[] { succeeded }, Context.getLocale());
            request.setAttribute(WebConstants.OPENMRS_MSG_ATTR, msg, WebRequest.SCOPE_SESSION);
        }
    }
    if (failed.size() > 0) {
        if (failed.size() == 1)
            request.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "formentry.xsnarchives.failure.single",
                    WebRequest.SCOPE_SESSION);
        else {
            msg = Context.getMessageSourceService().getMessage("formentry.xsnarchives.failure",
                    new Object[] { failed.size() }, Context.getLocale());
            request.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, msg, WebRequest.SCOPE_SESSION);
        }
    }
    if (succeeded == 0 && failed.size() == 0)
        request.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "formentry.xsnarchives.nothingdone",
                WebRequest.SCOPE_SESSION);

    modelMap.put("xsnmap", this.getFormEntryXsnMap());
    modelMap.put("location", Context.getAdministrationService()
            .getGlobalProperty(FormEntryConstants.FORMENTRY_GP_XSN_ARCHIVE_DIR, "unknown"));
    modelMap.put("failedArchives", failed);
    return "module/formentry/manageXsnArchives";
}

From source file:org.openmrs.module.yank.web.controller.ProcessController.java

@RequestMapping(method = RequestMethod.POST)
public String process(@RequestParam(value = "yankIds", required = false) List<Integer> yankIds,
        @RequestParam(value = "submitAll", required = false) String submitAll, WebRequest request)
        throws IOException {
    YankService service = Context.getService(YankService.class);

    List<String> successes = new ArrayList<String>();
    List<String> errors = new ArrayList<String>();

    if (yankIds == null)
        yankIds = new ArrayList<Integer>();

    // TODO make this more efficient
    if (!StringUtils.isBlank(submitAll))
        yankIds = service.getAllYankIds();

    // process all requested yanks
    int count = 0;
    for (Integer id : yankIds) {

        // tidy up for the sake of processing speeds
        if (++count % 20 == 0) {
            Context.flushSession();
            Context.clearSession();
        }//from  w  ww . ja  v a  2 s  . c  o  m

        // get the yank and process it
        Yank yank = service.getYank(id);
        Boolean success = service.processYank(yank);
        if (success)
            successes.add("Yank #" + id + " was processed successfully.");
        else
            errors.add("Yank #" + id + " could not be processed. See server log for more information.");
    }

    // fill in request attrs with success/failure messages
    if (!successes.isEmpty())
        request.setAttribute(WebConstants.OPENMRS_MSG_ATTR,
                renderMessage(successes, "Successfully processed $count yanks."), WebRequest.SCOPE_SESSION);
    if (!errors.isEmpty())
        request.setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                renderMessage(errors, "Could not process $count yanks.  See log for details."),
                WebRequest.SCOPE_SESSION);

    return "redirect:process.form";
}

From source file:org.openmrs.web.controller.maintenance.LocalesAndThemesFormController.java

/**
 * Called upon save of the page/*from   w w w. j  a  va  2 s . co m*/
 * 
 * @param theme the theme name to save
 * @param locale the locale to save (en, en_GB, es, etc)
 * @throws Exception
 */
@RequestMapping(method = RequestMethod.POST, value = "admin/maintenance/localesAndThemes")
public String saveDefaults(WebRequest request, @RequestParam("theme") String theme,
        @RequestParam("locale") String locale) throws Exception {
    boolean localeInList = false;
    String allowedLocales = Context.getAdministrationService()
            .getGlobalProperty(OpenmrsConstants.GLOBAL_PROPERTY_LOCALE_ALLOWED_LIST);
    String[] allowedLocalesList = allowedLocales.split(",");

    // save the theme
    GlobalProperty themeGP = Context.getAdministrationService()
            .getGlobalPropertyObject(OpenmrsConstants.GLOBAL_PROPERTY_DEFAULT_THEME);
    themeGP.setPropertyValue(theme);
    Context.getAdministrationService().saveGlobalProperty(themeGP);

    // save the locale
    for (String loc : allowedLocalesList) {
        loc = loc.trim();
        if (loc.equals(locale)) {
            localeInList = true;
            GlobalProperty localeGP = Context.getAdministrationService()
                    .getGlobalPropertyObject(OpenmrsConstants.GLOBAL_PROPERTY_DEFAULT_LOCALE);
            localeGP.setPropertyValue(locale);
            Context.getAdministrationService().saveGlobalProperty(localeGP);
            break;
        }
    }

    // displaying the success or failure message
    if (localeInList) {
        request.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "LocalesAndThemes.saved", WebRequest.SCOPE_SESSION);
    } else if (StringUtils.isBlank(locale)) {
        request.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "LocalesAndThemes.locale.isRequired",
                WebRequest.SCOPE_SESSION);
    } else {
        request.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "LocalesAndThemes.localeError",
                WebRequest.SCOPE_SESSION);
    }

    return "redirect:/admin/maintenance/localesAndThemes.form";
}

From source file:org.openmrs.module.yank.web.controller.QueryController.java

@RequestMapping(method = RequestMethod.POST)
public String yank(@RequestParam(value = "server", required = true) String server,
        @RequestParam(value = "username", required = true) String username,
        @RequestParam(value = "password", required = true) String password,
        @RequestParam(value = "datatype", required = true) String datatype,
        @RequestParam(value = "uuids") String uuids, @RequestParam(value = "file") MultipartFile file,
        WebRequest request) throws FileNotFoundException, UnsupportedEncodingException, IOException {
    YankService service = Context.getService(YankService.class);

    List<String> successes = new ArrayList<String>();
    List<String> errors = new ArrayList<String>();

    // build uuids from file if it was uploaded
    if (file != null) {
        String fileUuids = new String(file.getBytes());
        if (!StringUtils.isBlank(fileUuids))
            uuids = fileUuids;/*from w w w  . j  a  v  a 2s. c  om*/
    }

    if (StringUtils.isNotEmpty(uuids))
        for (String uuid : uuids.split(",")) {
            // clean it up
            uuid = uuid.trim();

            try {
                // look it up 
                // TODO encrypt username and password here and decrypt in RestUtil
                String data = service.yankFromServer(server, username, password, datatype, uuid);

                if (StringUtils.isBlank(data))
                    throw new APIException("nothing retrieved from server");

                // make a yank out of it
                Yank yank = new Yank();
                yank.setDatatype(datatype);
                yank.setData(data);
                yank.setSummary(service.getSummaryForType(datatype, data));
                service.saveYank(yank);

                successes.add("\"" + uuid + "\" successfully yanked.");

            } catch (Exception ex) {
                log.warn("error querying for uuid " + uuid, ex);
                errors.add("\"" + uuid + "\" could not be yanked [" + ex.getLocalizedMessage() + "]");
            }

        }

    if (!successes.isEmpty())
        request.setAttribute(WebConstants.OPENMRS_MSG_ATTR,
                renderMessage(successes, "Successfully yanked $count items."), WebRequest.SCOPE_SESSION);
    if (!errors.isEmpty())
        request.setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                renderMessage(errors, "Could not yank $count items. See log for details."),
                WebRequest.SCOPE_SESSION);

    return "redirect:process.form";
}

From source file:org.openmrs.web.controller.patient.ShortPatientFormController.java

/**
 * Handles the form submission by validating the form fields and saving it to the DB
 * // w  w  w  . ja  v a 2 s.  co  m
 * @param request the webRequest object
 * @param relationshipsMap
 * @param patientModel the modelObject containing the patient info collected from the form
 *            fields
 * @param result
 * @return the view to forward to
 * @should pass if all the form data is valid
 * @should create a new patient
 * @should send the user back to the form in case of validation errors
 * @should void a name and replace it with a new one if it is changed to a unique value
 * @should void an address and replace it with a new one if it is changed to a unique value
 * @should add a new name if the person had no names
 * @should add a new address if the person had none
 * @should ignore a new address that was added and voided at same time
 * @should set the cause of death as none a coded concept
 * @should set the cause of death as a none coded concept
 * @should void the cause of death obs that is none coded
 * @should add a new person attribute with a non empty value
 * @should not add a new person attribute with an empty value
 * @should void an existing person attribute with an empty value
 * @should should replace an existing attribute with a new one when edited
 * @should not void address if it was not changed
 * @should void address if it was changed
 */
@RequestMapping(method = RequestMethod.POST, value = SHORT_PATIENT_FORM_URL)
public String saveShortPatient(WebRequest request,
        @ModelAttribute("personNameCache") PersonName personNameCache,
        @ModelAttribute("personAddressCache") PersonAddress personAddressCache,
        @ModelAttribute("relationshipsMap") Map<String, Relationship> relationshipsMap,
        @ModelAttribute("patientModel") ShortPatientModel patientModel, BindingResult result) {

    if (Context.isAuthenticated()) {
        // First do form validation so that we can easily bind errors to
        // fields
        new ShortPatientFormValidator().validate(patientModel, result);
        if (result.hasErrors()) {
            return "module/legacyui/admin/patients/shortPatientForm";
        }

        Patient patient = null;
        patient = getPatientFromFormData(patientModel);

        Errors patientErrors = new BindException(patient, "patient");
        patientValidator.validate(patient, patientErrors);
        if (patientErrors.hasErrors()) {
            // bind the errors to the patientModel object by adding them to
            // result since this is not a patient object
            // so that spring doesn't try to look for getters/setters for
            // Patient in ShortPatientModel
            for (ObjectError error : patientErrors.getAllErrors()) {
                result.reject(error.getCode(), error.getArguments(), "Validation errors found");
            }

            return "module/legacyui/admin/patients/shortPatientForm";
        }

        // check if name/address were edited, void them and replace them
        boolean foundChanges = hasPersonNameOrAddressChanged(patient, personNameCache, personAddressCache);

        try {
            patient = Context.getPatientService().savePatient(patient);
            request.setAttribute(WebConstants.OPENMRS_MSG_ATTR,
                    Context.getMessageSourceService().getMessage("Patient.saved"), WebRequest.SCOPE_SESSION);

            // TODO do we really still need this, besides ensuring that the
            // cause of death is provided?
            // process and save the death info
            saveDeathInfo(patientModel, request);

            if (!patient.getVoided() && relationshipsMap != null) {
                for (Relationship relationship : relationshipsMap.values()) {
                    // if the user added a person to this relationship, save
                    // it
                    if (relationship.getPersonA() != null && relationship.getPersonB() != null) {
                        Context.getPersonService().saveRelationship(relationship);
                    }
                }
            }
        } catch (APIException e) {
            log.error("Error occurred while attempting to save patient", e);
            request.setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                    Context.getMessageSourceService().getMessage("Patient.save.error"),
                    WebRequest.SCOPE_SESSION);
            // TODO revert the changes and send them back to the form

            // don't send the user back to the form because the created
            // person name/addresses
            // will be recreated over again if the user attempts to resubmit
            if (!foundChanges) {
                return "module/legacyui/admin/patients/shortPatientForm";
            }
        }

        return "redirect:" + PATIENT_DASHBOARD_URL + "?patientId=" + patient.getPatientId();

    }

    return "module/legacyui/findPatient";
}