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.patient.ShortPatientFormControllerTest.java

/**
 * @see ShortPatientFormController#saveShortPatient(WebRequest,PersonName,PersonAddress,Map,ShortPatientModel, BindingResult)
 *///w  ww. jav  a 2  s .  co m
@Test
@Verifies(value = "should add a new person attribute with a non empty value", method = "saveShortPatient(WebRequest,PersonName,PersonAddress,ShortPatientModel,BindingResult)")
public void saveShortPatient_shouldAddANewPersonAttributeWithANonEmptyValue() throws Exception {
    Patient p = Context.getPatientService().getPatient(2);
    int originalAttributeCount = p.getAttributes().size();
    ShortPatientModel patientModel = new ShortPatientModel(p);
    int attributeTypeId = 2;
    String birthPlace = "Kampala";
    PersonAttribute newPersonAttribute = new PersonAttribute(
            Context.getPersonService().getPersonAttributeType(attributeTypeId), birthPlace);
    newPersonAttribute.setDateCreated(new Date());
    newPersonAttribute.setCreator(Context.getAuthenticatedUser());
    patientModel.getPersonAttributes().add(newPersonAttribute);

    WebRequest mockWebRequest = new ServletWebRequest(new MockHttpServletRequest());
    BindException errors = new BindException(patientModel, "patientModel");
    mockWebRequest.setAttribute("personNameCache", p.getPersonName(), WebRequest.SCOPE_SESSION);
    mockWebRequest.setAttribute("personAddressCache", p.getPersonAddress(), WebRequest.SCOPE_SESSION);
    mockWebRequest.setAttribute("patientModel", patientModel, WebRequest.SCOPE_SESSION);

    ShortPatientFormController controller = (ShortPatientFormController) applicationContext
            .getBean("shortPatientFormController");
    String redirectUrl = controller.saveShortPatient(mockWebRequest,
            (PersonName) mockWebRequest.getAttribute("personNameCache", WebRequest.SCOPE_SESSION),
            (PersonAddress) mockWebRequest.getAttribute("personAddressCache", WebRequest.SCOPE_SESSION), null,
            (ShortPatientModel) mockWebRequest.getAttribute("patientModel", WebRequest.SCOPE_SESSION), errors);
    Assert.assertTrue("Should pass with no validation errors", !errors.hasErrors());

    Assert.assertEquals("Patient.saved",
            mockWebRequest.getAttribute(WebConstants.OPENMRS_MSG_ATTR, WebRequest.SCOPE_SESSION));
    Assert.assertEquals("redirect:/patientDashboard.form?patientId=" + p.getPatientId(), redirectUrl);
    //The new person attribute should have been added and saved
    Assert.assertNotNull(p.getAttribute(2).getPersonAttributeId());
    Assert.assertEquals(birthPlace, p.getAttribute(2).getValue());
    Assert.assertEquals(originalAttributeCount + 1, p.getAttributes().size());
}

From source file:org.openmrs.web.controller.visit.VisitFormController.java

/**
 * Processes requests to purge a visit//  w  w w .jav a2s  . c  om
 *
 * @param request the {@link WebRequest} object
 * @param visit the visit object to purge
 * @param status the {@link SessionStatus}
 * @param model the {@link ModelMap} object
 * @return the url to forward to
 */
@RequestMapping(method = RequestMethod.POST, value = "/admin/visits/purgeVisit")
public String purgeVisit(WebRequest request, @ModelAttribute(value = "visit") Visit visit, SessionStatus status,
        ModelMap model) {
    try {
        Integer patientId = visit.getPatient().getPatientId();
        Context.getVisitService().purgeVisit(visit);
        if (log.isDebugEnabled()) {
            log.debug("Purged visit with id: " + visit.getId());
        }
        request.setAttribute(WebConstants.OPENMRS_MSG_ATTR,
                Context.getMessageSourceService().getMessage("Visit.purged"), WebRequest.SCOPE_SESSION);
        return "redirect:/patientDashboard.form?patientId=" + patientId;
    } catch (APIException e) {
        log.warn("Error occurred while attempting to purge visit", e);
        request.setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                Context.getMessageSourceService().getMessage("Visit.purge.error"), WebRequest.SCOPE_SESSION);
    }
    //there was an exception thrown
    return "redirect:" + VISIT_FORM_URL + ".form?visitId=" + visit.getVisitId() + "&patientId="
            + visit.getPatient().getPatientId();
}

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

/**
 * @see ShortPatientFormController#saveShortPatient(WebRequest,PersonName,PersonAddress,Map,ShortPatientModel, BindingResult)
 *//*  w  ww.j av  a2  s.c  o  m*/
@Test
@Verifies(value = "should void an existing person attribute with an empty value", method = "saveShortPatient(WebRequest,PersonName,PersonAddress,ShortPatientModel,BindingResult)")
public void saveShortPatient_shouldVoidAnExistingPersonAttributeWithAnEmptyValue() throws Exception {
    int attributeTypeId = 8;
    PersonAttributeType pat = Context.getPersonService().getPersonAttributeType(attributeTypeId);
    //For this test to pass we need to have some viewable attributes to be displayed on the form for editing
    AdministrationService as = Context.getAdministrationService();
    GlobalProperty gp = as.getGlobalPropertyObject(OpenmrsConstants.GLOBAL_PROPERTY_PATIENT_VIEWING_ATTRIBUTES);
    if (gp == null)
        gp = new GlobalProperty(OpenmrsConstants.GLOBAL_PROPERTY_PATIENT_VIEWING_ATTRIBUTES);
    gp.setPropertyValue(pat.getName());
    as.saveGlobalProperty(gp);

    Patient p = Context.getPatientService().getPatient(2);
    int originalActiveAttributeCount = p.getActiveAttributes().size();

    ShortPatientModel patientModel = new ShortPatientModel(p);
    PersonAttribute attributeToEdit = null;
    String oldValue = null;
    String newValue = "";
    //assuming we are in the webapp on the form, find the attribute with the matching 
    // attribute type and change its value to an empty string
    for (PersonAttribute at : patientModel.getPersonAttributes()) {
        if (at.getAttributeType().equals(pat)) {
            oldValue = at.getValue();
            at.setValue(newValue);
            attributeToEdit = at;
            break;
        }
    }
    //ensure we found and edited it
    Assert.assertNotNull(attributeToEdit);
    Assert.assertNotNull(oldValue);

    WebRequest mockWebRequest = new ServletWebRequest(new MockHttpServletRequest());
    BindException errors = new BindException(patientModel, "patientModel");
    mockWebRequest.setAttribute("personNameCache", p.getPersonName(), WebRequest.SCOPE_SESSION);
    mockWebRequest.setAttribute("personAddressCache", p.getPersonAddress(), WebRequest.SCOPE_SESSION);
    mockWebRequest.setAttribute("patientModel", patientModel, WebRequest.SCOPE_SESSION);

    ShortPatientFormController controller = (ShortPatientFormController) applicationContext
            .getBean("shortPatientFormController");
    controller.saveShortPatient(mockWebRequest,
            (PersonName) mockWebRequest.getAttribute("personNameCache", WebRequest.SCOPE_SESSION),
            (PersonAddress) mockWebRequest.getAttribute("personAddressCache", WebRequest.SCOPE_SESSION), null,
            (ShortPatientModel) mockWebRequest.getAttribute("patientModel", WebRequest.SCOPE_SESSION), errors);

    Assert.assertTrue("Should pass with no validation errors", !errors.hasErrors());
    Assert.assertEquals("Patient.saved",
            mockWebRequest.getAttribute(WebConstants.OPENMRS_MSG_ATTR, WebRequest.SCOPE_SESSION));

    //the attribute should have been voided
    Assert.assertEquals(originalActiveAttributeCount - 1, p.getActiveAttributes().size());
}

From source file:org.openmrs.calculation.web.controller.CalculationRegistrationFormController.java

/**
 * Save changes which were made within token registration. If any validation error has been
 * occurred it will populate binding result with corresponding error messages and return back to
 * edit page./*from w w  w. j a  v a2 s .c o m*/
 */
@RequestMapping(value = "/module/calculation/calculationRegistration", method = RequestMethod.POST)
public String saveCalculationRegistration(
        @ModelAttribute("calculationRegistration") CalculationRegistration calculationRegistration,
        BindingResult result, WebRequest request) {

    // Validate CalculationRegistration
    calculationRegistrationValidator.validate(calculationRegistration, result);
    if (result.hasErrors()) {
        return null;
    }

    CalculationRegistrationService calculationRegistrationService = Context
            .getService(CalculationRegistrationService.class);
    try {
        calculationRegistration = calculationRegistrationService
                .saveCalculationRegistration(calculationRegistration);
    } catch (Exception e) {
        log.error("Unable to save token registration, because of error:", e);
        request.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "calculation.CalculationRegistration.errorSaving",
                WebRequest.SCOPE_SESSION);
        return null;
    }

    updateSessionMessage(request, "calculation.CalculationRegistration.saved", calculationRegistration);
    return "redirect:calculationRegistrations.list";
}

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

/**
 * @see ShortPatientFormController#saveShortPatient(WebRequest,PersonName,PersonAddress,Map,ShortPatientModel, BindingResult)
 *///from ww w. j a v  a 2  s .  c om
@Test
@Verifies(value = "should should replace an existing attribute with a new one when edited", method = "saveShortPatient(WebRequest,PersonName,PersonAddress,ShortPatientModel,BindingResult)")
public void saveShortPatient_shouldShouldReplaceAnExistingAttributeWithANewOneWhenEdited() throws Exception {
    int attributeTypeId = 2;
    PersonAttributeType pat = Context.getPersonService().getPersonAttributeType(attributeTypeId);
    //For this test to pass we need to have some viewable attributes to be displayed on the form for editing
    AdministrationService as = Context.getAdministrationService();
    GlobalProperty gp = as.getGlobalPropertyObject(OpenmrsConstants.GLOBAL_PROPERTY_PATIENT_VIEWING_ATTRIBUTES);
    if (gp == null)
        gp = new GlobalProperty(OpenmrsConstants.GLOBAL_PROPERTY_PATIENT_VIEWING_ATTRIBUTES);
    gp.setPropertyValue(pat.getName());
    as.saveGlobalProperty(gp);

    Patient p = Context.getPatientService().getPatient(2);
    int originalAttributeCount = p.getAttributes().size();

    ShortPatientModel patientModel = new ShortPatientModel(p);
    PersonAttribute attributeToEdit = null;
    String oldValue = null;
    String newValue = "New";
    //assuming we are in the webapp on the form, find the attribute with the matching 
    // attribute type and change its value
    for (PersonAttribute at : patientModel.getPersonAttributes()) {
        if (at.getAttributeType().equals(pat)) {
            oldValue = at.getValue();
            at.setValue(newValue);
            attributeToEdit = at;
            break;
        }
    }
    //ensure we found and edited it
    Assert.assertNotNull(attributeToEdit);
    Assert.assertNotNull(oldValue);

    WebRequest mockWebRequest = new ServletWebRequest(new MockHttpServletRequest());
    BindException errors = new BindException(patientModel, "patientModel");
    mockWebRequest.setAttribute("personNameCache", p.getPersonName(), WebRequest.SCOPE_SESSION);
    mockWebRequest.setAttribute("personAddressCache", p.getPersonAddress(), WebRequest.SCOPE_SESSION);
    mockWebRequest.setAttribute("patientModel", patientModel, WebRequest.SCOPE_SESSION);

    ShortPatientFormController controller = (ShortPatientFormController) applicationContext
            .getBean("shortPatientFormController");
    controller.saveShortPatient(mockWebRequest,
            (PersonName) mockWebRequest.getAttribute("personNameCache", WebRequest.SCOPE_SESSION),
            (PersonAddress) mockWebRequest.getAttribute("personAddressCache", WebRequest.SCOPE_SESSION), null,
            (ShortPatientModel) mockWebRequest.getAttribute("patientModel", WebRequest.SCOPE_SESSION), errors);

    Assert.assertTrue("Should pass with no validation errors", !errors.hasErrors());
    Assert.assertEquals("Patient.saved",
            mockWebRequest.getAttribute(WebConstants.OPENMRS_MSG_ATTR, WebRequest.SCOPE_SESSION));

    //a new replacement attribute should have been created with the new value
    PersonAttribute newAttribute = p.getAttribute(attributeTypeId);
    Assert.assertEquals(originalAttributeCount + 1, p.getAttributes().size());
    Assert.assertEquals(newValue, newAttribute.getValue());

    PersonAttribute oldAttribute = null;
    //find the voided attribute
    for (PersonAttribute at : p.getAttributes()) {
        //skip past the new one since it will be having a matching attribute type
        //and find exactly the attribute with the expected void reason
        if (at.getAttributeType().equals(pat)
                && OpenmrsUtil.nullSafeEquals("New value: " + newValue, at.getVoidReason())) {
            oldAttribute = at;
            break;
        }
    }

    //The old attribute should have been voided and maintained its old value
    Assert.assertNotNull(oldAttribute);
    Assert.assertEquals(oldValue, oldAttribute.getValue());
    Assert.assertTrue(oldAttribute.isVoided());
}

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

/**
 * Processes requests to retire a concept map type
 *
 * @param request the {@link WebRequest} object
 * @param conceptMapType the concept map type object to retire
 * @param retireReason the reason why the concept map type is getting retired
 * @return the url to redirect to//  w w  w  .  jav a  2 s  .c  om
 */
@RequestMapping(method = RequestMethod.POST, value = "/admin/concepts/retireConceptMapType")
public String retireConceptMapType(WebRequest request,
        @ModelAttribute(value = "conceptMapType") ConceptMapType conceptMapType,
        @RequestParam(required = false, value = "retireReason") String retireReason) {

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

    try {
        Context.getConceptService().retireConceptMapType(conceptMapType, retireReason);
        if (log.isDebugEnabled()) {
            log.debug("Retired concept map type with id: " + conceptMapType.getId());
        }
        request.setAttribute(WebConstants.OPENMRS_MSG_ATTR,
                Context.getMessageSourceService().getMessage("ConceptMapType.retired"),
                WebRequest.SCOPE_SESSION);

        return "redirect:" + CONCEPT_MAP_TYPE_LIST_URL + ".list";
    } catch (APIException e) {
        log.error("Error occurred while attempting to retire concept map type", e);
        request.setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                Context.getMessageSourceService().getMessage("ConceptMapType.retire.error"),
                WebRequest.SCOPE_SESSION);
    }

    //an error occurred
    return CONCEPT_MAP_TYPE_FORM;
}

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

/**
 * Processes requests to purge a concept reference term
 *
 * @param request the {@link WebRequest} object
 * @param conceptReferenceTermModel/*from   w  w w . j  a  v a  2s  .co  m*/
 * @return the url to forward to
 */
@RequestMapping(method = RequestMethod.POST, value = "/admin/concepts/purgeConceptReferenceTerm")
public String purgeTerm(WebRequest request,
        @ModelAttribute(value = "conceptReferenceTermModel") ConceptReferenceTermModel conceptReferenceTermModel) {
    Integer id = conceptReferenceTermModel.getConceptReferenceTerm().getId();
    try {
        Context.getConceptService()
                .purgeConceptReferenceTerm(conceptReferenceTermModel.getConceptReferenceTerm());
        if (log.isDebugEnabled()) {
            log.debug("Purged concept reference term with id: " + id);
        }
        request.setAttribute(WebConstants.OPENMRS_MSG_ATTR,
                Context.getMessageSourceService().getMessage("ConceptReferenceTerm.purged"),
                WebRequest.SCOPE_SESSION);
        return "redirect:" + FIND_CONCEPT_REFERENCE_TERM_URL;
    } catch (APIException e) {
        log.warn("Error occurred while attempting to purge concept reference term", e);
        request.setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                Context.getMessageSourceService().getMessage("ConceptReferenceTerm.purge.error"),
                WebRequest.SCOPE_SESSION);
    }

    //send the user back to form
    return "redirect:" + CONCEPT_REFERENCE_TERM_FORM_URL + ".form?conceptReferenceTermId=" + id;
}

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

/**
 * Processes requests to unretire concept reference terms
 *
 * @param request the {@link WebRequest} object
 * @param conceptReferenceTermModel the concept reference term model object for the term to
 *            unretire//w  ww .ja  va 2s .  c om
 * @return the url to redirect to
 */
@RequestMapping(method = RequestMethod.POST, value = "/admin/concepts/unretireConceptReferenceTerm")
public String unretireConceptReferenceTerm(WebRequest request,
        @ModelAttribute(value = "conceptReferenceTermModel") ConceptReferenceTermModel conceptReferenceTermModel) {

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

        return "redirect:" + CONCEPT_REFERENCE_TERM_FORM_URL + ".form?conceptReferenceTermId="
                + conceptReferenceTerm.getConceptReferenceTermId();
    } catch (APIException e) {
        log.error("Error occurred while unretiring concept reference term", e);
        request.setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                Context.getMessageSourceService().getMessage("ConceptReferenceTerm.unretire.error"),
                WebRequest.SCOPE_SESSION);
    }

    //an error occurred, show the form
    return CONCEPT_REFERENCE_TERM_FORM;
}

From source file:org.openmrs.web.controller.visit.VisitFormController.java

/**
 * Processes requests to void a visit//from w w  w. j a v  a 2s. com
 *
 * @param request the {@link WebRequest} object
 * @param visit the visit object to void
 * @param voidReason the reason why the visit is getting void
 * @param status the {@link SessionStatus}
 * @param model the {@link ModelMap} object
 * @return the url to forward to
 */
@RequestMapping(method = RequestMethod.POST, value = "/admin/visits/voidVisit")
public String voidVisit(WebRequest request, @ModelAttribute(value = "visit") Visit visit,
        @RequestParam(required = false, value = "voidReason") String voidReason, SessionStatus status,
        ModelMap model) {
    if (!StringUtils.hasText(voidReason)) {
        voidReason = Context.getMessageSourceService().getMessage("general.default.voidReason");
    }

    try {
        Context.getVisitService().voidVisit(visit, voidReason);
        if (log.isDebugEnabled()) {
            log.debug("Voided visit with id: " + visit.getId());
        }
        request.setAttribute(WebConstants.OPENMRS_MSG_ATTR,
                Context.getMessageSourceService().getMessage("Visit.voided"), WebRequest.SCOPE_SESSION);
        return "redirect:" + VISIT_FORM_URL + ".form?visitId=" + visit.getVisitId() + "&patientId="
                + visit.getPatient().getPatientId();
    } catch (APIException e) {
        log.warn("Error occurred while attempting to void visit", e);
        request.setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                Context.getMessageSourceService().getMessage("Visit.void.error"), WebRequest.SCOPE_SESSION);
    }

    addEncounterAndObservationCounts(visit, null, model);
    return VISIT_FORM;
}

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

@RequestMapping(value = "/module/dhisreport/configureDhis2", method = RequestMethod.POST)
public void saveConfig(ModelMap model, @RequestParam(value = "url", required = true) String urlString,
        @RequestParam(value = "username", required = true) String username,
        @RequestParam(value = "password", required = true) String password, WebRequest webRequest)
        throws ParseException, MalformedURLException {
    DHIS2ReportingService service = Context.getService(DHIS2ReportingService.class);
    HttpDhis2Server server = service.getDhis2Server();

    // System.out.println( "parameters received on post request" + urlString + username + password );

    if (server == null) {
        server = new HttpDhis2Server();
    }//from w w  w .  ja  va 2 s .  c  om

    URL url = new URL(urlString);
    server.setUrl(url);
    server.setUsername(username);
    server.setPassword(password);

    service.setDhis2Server(server);

    boolean val = testConnection(url, username, password, server, webRequest, model);

    if (val == true) {
        model.addAttribute("dhis2Server", server);
        model.addAttribute("user", Context.getAuthenticatedUser());
        webRequest.setAttribute(WebConstants.OPENMRS_MSG_ATTR,
                Context.getMessageSourceService().getMessage("dhisreport.saveConfigSuccess"),
                WebRequest.SCOPE_SESSION);

        GlobalProperty globalProperty = new GlobalProperty();
        globalProperty.setProperty("dhisreport.dhis2URL");
        globalProperty.setPropertyValue(urlString);
        Context.getAdministrationService().saveGlobalProperty(globalProperty);
        globalProperty.setProperty("dhisreport.dhis2UserName");
        globalProperty.setPropertyValue(username);
        Context.getAdministrationService().saveGlobalProperty(globalProperty);
        globalProperty.setProperty("dhisreport.dhis2Password");
        globalProperty.setPropertyValue(password);
        Context.getAdministrationService().saveGlobalProperty(globalProperty);

    } else {

        model.addAttribute("dhis2Server", server);
        model.addAttribute("user", Context.getAuthenticatedUser());
        webRequest.setAttribute(WebConstants.OPENMRS_MSG_ATTR,
                Context.getMessageSourceService().getMessage("dhisreport.saveConfigFailure"),
                WebRequest.SCOPE_SESSION);

    }
}