/**
   * @see RadiologyObsFormController#saveObs(HttpServletRequest, HttpServletResponse, String,
   *     RadiologyOrder, Obs Obs, BindingResult)
   */
  @Test
  @Verifies(
      value =
          "should edit obs with edit reason, complex concept and request which is an instance of multihttpserveletrequest",
      method =
          "saveObs(HttpServletRequest, HttpServletResponse, String, RadiologyOrder, Obs Obs, BindingResult)")
  public void
      saveObs_ShouldEditObsWithEditReasonComplexConceptANdRequestWhichIsAnInstanceOfMultiHTTPServletRequest() {

    MockHttpSession mockSession = new MockHttpSession();
    MockMultipartHttpServletRequest mockRequest = new MockMultipartHttpServletRequest();
    mockRequest.addParameter("saveObs", "saveObs");
    mockRequest.setSession(mockSession);

    when(obsErrors.hasErrors()).thenReturn(false);
    ConceptComplex concept = new ConceptComplex();
    ConceptDatatype cdt = new ConceptDatatype();
    cdt.setHl7Abbreviation("ED");
    concept.setDatatype(cdt);
    mockObs.setConcept(concept);
    final String fileName = "test.txt";
    final byte[] content = "Hello World".getBytes();
    MockMultipartFile mockMultipartFile =
        new MockMultipartFile("complexDataFile", fileName, "text/plain", content);

    mockRequest.addFile(mockMultipartFile);

    radiologyObsFormController.saveObs(
        mockRequest, null, "Test Edit Reason", mockRadiologyOrder, mockObs, obsErrors);

    assertNotNull(mockSession.getAttribute(WebConstants.OPENMRS_MSG_ATTR));
    assertThat((String) mockSession.getAttribute(WebConstants.OPENMRS_MSG_ATTR), is("Obs.saved"));
  }
  /**
   * @see RadiologyObsFormController#saveObs(HttpServletRequest, HttpServletResponse, String,
   *     RadiologyOrder, Obs Obs, BindingResult)
   */
  @Test
  @Verifies(
      value = "should populate model and view with obs occuring thrown APIException",
      method =
          "saveObs(HttpServletRequest, HttpServletResponse, String, RadiologyOrder, Obs Obs, BindingResult)")
  public void saveObs_ShouldPopulateModelAndViewWithObsOccuringThrownAPIException()
      throws Exception {

    MockHttpSession mockSession = new MockHttpSession();
    MockMultipartHttpServletRequest mockRequest = new MockMultipartHttpServletRequest();
    mockRequest.addParameter("editReason", "Test Edit Reason");
    mockRequest.setSession(mockSession);

    when(obsErrors.hasErrors()).thenReturn(false);
    mockObs.setConcept(new Concept());
    final String fileName = "test.txt";
    final byte[] content = "Hello World".getBytes();
    MockMultipartFile mockMultipartFile =
        new MockMultipartFile("complexDataFile", fileName, "text/plain", content);

    mockRequest.addFile(mockMultipartFile);
    APIException apiException = new APIException("Test Exception Handling");
    when(obsService.saveObs(mockObs, "Test Edit Reason")).thenThrow(apiException);
    ModelAndView modelAndView =
        radiologyObsFormController.saveObs(
            mockRequest, null, "Test Edit Reason", mockRadiologyOrder, mockObs, obsErrors);
    assertThat(modelAndView.getViewName(), is("module/radiology/radiologyObsForm"));
    assertNotNull(modelAndView);

    assertThat(modelAndView.getModelMap(), hasKey("obs"));
    Obs obs = (Obs) modelAndView.getModelMap().get("obs");
    assertThat(obs, is(mockObs));
  }
  @Test
  public void createResumeWithPost() throws Exception {
    MockMultipartHttpServletRequest request = new MockMultipartHttpServletRequest();
    request.setRequestURI("/resume/store");

    String filename = "sample_resume.docx";
    byte[] content =
        IOUtils.toByteArray(new ClassPathResource("/sample_resume.docx").getInputStream());
    MockMultipartFile mockMultipartFile =
        new MockMultipartFile(
            "file", filename, URLConnection.guessContentTypeFromName(filename), content);
    request.addFile(mockMultipartFile);

    MockHttpServletResponse response = handleRequest(request);
    Assert.assertEquals(201, response.getStatus());
  }
Ejemplo n.º 4
0
 /**
  * Reset the request and the response, maintaining the same session. Useful, for example, to call
  * a post after calling the get of the form.
  */
 protected void resetRequestAndResponse() {
   HttpSession httpSession = null;
   // preparing the multipart request
   if (mpReq != null) {
     httpSession = mpReq.getSession();
   }
   mpReq = new MockMultipartHttpServletRequest();
   mpReq.setSession(httpSession);
   mpReq.setMethod("GET");
   // preparing the normal request
   if (req != null) {
     httpSession = req.getSession();
   }
   req = new MockHttpServletRequest();
   req.setSession(httpSession);
   req.setMethod("GET");
   res = new MockHttpServletResponse();
 }
  /**
   * @see RadiologyObsFormController#saveObs(HttpServletRequest, HttpServletResponse, String,
   *     RadiologyOrder, Obs Obs, BindingResult)
   */
  @Test
  @Verifies(
      value =
          "should edit obs with edit reason concept not complex and request which is an instance of multihttpserveletrequest",
      method =
          "saveObs(HttpServletRequest, HttpServletResponse, String, RadiologyOrder, Obs Obs, BindingResult)")
  public void
      saveObs_ShouldEditObsWithEditReasonConceptNotComplexAndRequestWhichIsAnInstanceOfMultiHTTPServletRequest() {

    MockHttpSession mockSession = new MockHttpSession();
    MockMultipartHttpServletRequest mockRequest = new MockMultipartHttpServletRequest();
    mockRequest.addParameter("saveObs", "saveObs");
    mockRequest.setSession(mockSession);

    when(obsErrors.hasErrors()).thenReturn(false);
    ;
    mockObs.setConcept(new Concept());
    final String fileName = "test.txt";
    final byte[] content = "Hello World".getBytes();
    MockMultipartFile mockMultipartFile =
        new MockMultipartFile("complexDataFile", fileName, "text/plain", content);

    mockRequest.addFile(mockMultipartFile);

    ModelAndView modelAndView =
        radiologyObsFormController.saveObs(
            mockRequest, null, "Test Edit Reason", mockRadiologyOrder, mockObs, obsErrors);

    assertNotNull(mockSession.getAttribute(WebConstants.OPENMRS_MSG_ATTR));
    assertThat((String) mockSession.getAttribute(WebConstants.OPENMRS_MSG_ATTR), is("Obs.saved"));
    assertThat(
        modelAndView.getViewName(),
        is(
            "redirect:"
                + RADIOLOGY_OBS_FORM_URL
                + "orderId="
                + mockRadiologyOrder.getId()
                + "&obsId="
                + mockObs.getId()));
  }
  public void testSaveRecord(String intWithRangeValue) throws Exception {
    login("admin", "password", new String[] {Role.ADMIN});

    request.setMethod("POST");
    request.setRequestURI("/bdrs/user/singleSiteMultiTaxa.htm");

    DateFormat dateFormat = new SimpleDateFormat("dd MMM yyyy");
    dateFormat.setLenient(false);

    GregorianCalendar cal = new GregorianCalendar();
    cal.set(2010, 10, 12, 15, 30);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);
    Date sightingDate = cal.getTime();

    Map<String, String> params = new HashMap<String, String>();
    params.put("surveyId", survey.getId().toString());
    params.put("latitude", "-36.879620605027");
    params.put("longitude", "126.650390625");
    params.put("date", dateFormat.format(sightingDate));
    params.put("time_hour", new Integer(cal.get(Calendar.HOUR_OF_DAY)).toString());
    params.put("time_minute", new Integer(cal.get(Calendar.MINUTE)).toString());
    params.put("notes", "This is a test record");
    params.put("sightingIndex", "2");

    Map<Attribute, Object> surveyScopeAttributeValueMapping = new HashMap<Attribute, Object>();
    Map<IndicatorSpecies, Map<Attribute, Object>> recordScopeAttributeValueMapping =
        new HashMap<IndicatorSpecies, Map<Attribute, Object>>(2);
    Map<Attribute, Object> attributeValueMapping;

    // We have 2 species set up so lets save them both
    int sightingIndex = 0;
    String surveyPrefix = "";
    for (IndicatorSpecies taxon : new IndicatorSpecies[] {speciesA, speciesB}) {
      params.put(
          String.format("%d_survey_species_search", sightingIndex), taxon.getScientificName());
      params.put(String.format("%d_species", sightingIndex), taxon.getId().toString());
      params.put(
          String.format("%d_number", sightingIndex), new Integer(sightingIndex + 21).toString());

      String recordPrefix = String.format("%d_", sightingIndex);
      String prefix;
      String key;
      String value; // The value in the post dict
      attributeValueMapping = new HashMap<Attribute, Object>();
      Map<Attribute, Object> valueMap;
      recordScopeAttributeValueMapping.put(taxon, attributeValueMapping);
      for (Attribute attr : survey.getAttributes()) {

        if (AttributeScope.SURVEY.equals(attr.getScope())) {
          prefix = surveyPrefix;
          valueMap = surveyScopeAttributeValueMapping;
        } else {
          prefix = recordPrefix;
          valueMap = attributeValueMapping;
        }

        key = String.format(AttributeParser.ATTRIBUTE_NAME_TEMPLATE, prefix, attr.getId());
        value = "";

        switch (attr.getType()) {
          case INTEGER:
            Integer val = new Integer(sightingIndex + 30);
            value = val.toString();
            valueMap.put(attr, val);
            break;
          case INTEGER_WITH_RANGE:
            valueMap.put(attr, intWithRangeValue);
            break;
          case DECIMAL:
            value = String.format("50.%d", sightingIndex);
            valueMap.put(attr, Double.parseDouble(value));
            break;
          case DATE:
            Date date = new Date(System.currentTimeMillis());
            value = dateFormat.format(date);
            // Reparsing the date strips out the hours, minutes and seconds
            valueMap.put(attr, dateFormat.parse(value));
            break;
          case STRING_AUTOCOMPLETE:
          case STRING:
            value = String.format("String %d", sightingIndex);
            valueMap.put(attr, value);
            break;
          case TEXT:
            value = String.format("Text %d", sightingIndex);
            valueMap.put(attr, value);
            break;
          case STRING_WITH_VALID_VALUES:
            value = attr.getOptions().get(sightingIndex).getValue();
            valueMap.put(attr, value);
            break;
          case FILE:
            String file_filename = String.format("attribute_%d", attr.getId());
            MockMultipartFile mockFileFile =
                new MockMultipartFile(key, file_filename, "audio/mpeg", file_filename.getBytes());
            ((MockMultipartHttpServletRequest) request).addFile(mockFileFile);
            valueMap.put(attr, mockFileFile);
            break;
          case IMAGE:
            String image_filename = String.format("attribute_%d", attr.getId());
            MockMultipartFile mockImageFile =
                new MockMultipartFile(key, image_filename, "image/png", image_filename.getBytes());
            ((MockMultipartHttpServletRequest) request).addFile(mockImageFile);
            valueMap.put(attr, mockImageFile);
            break;
          default:
            Assert.assertTrue("Unknown Attribute Type: " + attr.getType().toString(), false);
            break;
        }
        params.put(key, value);
      }
      sightingIndex += 1;
    }

    request.setParameters(params);
    ModelAndView mv = handle(request, response);
    Assert.assertEquals(2, recordDAO.countAllRecords().intValue());

    Assert.assertTrue(mv.getView() instanceof RedirectView);
    RedirectView redirect = (RedirectView) mv.getView();
    Assert.assertEquals(redirectionService.getMySightingsUrl(survey), redirect.getUrl());

    sightingIndex = 0;
    for (IndicatorSpecies taxon : new IndicatorSpecies[] {speciesA, speciesB}) {
      List<Record> records = recordDAO.getRecords(taxon);
      Assert.assertEquals(1, records.size());
      Record record = records.get(0);

      Assert.assertEquals(survey.getId(), record.getSurvey().getId());
      // Coordinates are truncates to 6 decimal points
      Assert.assertEquals(
          new Double(params.get("latitude")).doubleValue(),
          record.getPoint().getY(),
          Math.pow(10, -6));
      Assert.assertEquals(
          new Double(params.get("longitude")).doubleValue(),
          record.getPoint().getX(),
          Math.pow(10, -6));
      Assert.assertEquals(sightingDate, record.getWhen());
      Assert.assertEquals(sightingDate.getTime(), record.getTime().longValue());
      Assert.assertEquals(params.get("notes"), record.getNotes());

      Assert.assertEquals(taxon, record.getSpecies());
      Assert.assertEquals(sightingIndex + 21, record.getNumber().intValue());

      Map<Attribute, Object> attributeValueMap = recordScopeAttributeValueMapping.get(taxon);
      Object expected;
      for (TypedAttributeValue recAttr : record.getAttributes()) {
        if (AttributeScope.SURVEY.equals(recAttr.getAttribute().getScope())) {
          expected = surveyScopeAttributeValueMapping.get(recAttr.getAttribute());
        } else {
          expected = attributeValueMap.get(recAttr.getAttribute());
        }

        switch (recAttr.getAttribute().getType()) {
          case INTEGER:
          case INTEGER_WITH_RANGE:
            Assert.assertEquals(expected, recAttr.getNumericValue().intValue());
            break;
          case DECIMAL:
            Assert.assertEquals(expected, recAttr.getNumericValue().doubleValue());
            break;
          case DATE:
            Assert.assertEquals(expected, recAttr.getDateValue());
            break;
          case STRING_AUTOCOMPLETE:
          case STRING:
          case TEXT:
            Assert.assertEquals(expected, recAttr.getStringValue());
            break;
          case STRING_WITH_VALID_VALUES:
            Assert.assertEquals(expected, recAttr.getStringValue());
            break;
          case FILE:
          case IMAGE:
            String filename = ((MockMultipartFile) expected).getOriginalFilename();
            Assert.assertEquals(filename, recAttr.getStringValue());
            break;
          default:
            Assert.assertTrue(
                "Unknown Attribute Type: " + recAttr.getAttribute().getType().toString(), false);
            break;
        }
      }
      sightingIndex += 1;
    }

    // Test Save and Add Another
    request.setParameter("submitAndAddAnother", "submitAndAddAnother");
    mv = handle(request, response);
    Assert.assertEquals(4, recordDAO.countAllRecords().intValue());

    Assert.assertTrue(mv.getView() instanceof RedirectView);
    redirect = (RedirectView) mv.getView();
    Assert.assertEquals("/bdrs/user/surveyRenderRedirect.htm", redirect.getUrl());
  }
 private ServletRequest prepareServletRequest(
     Object target, NativeWebRequest request, MethodParameter parameter) {
   String modelPrefixName = parameter.getParameterAnnotation(FormModel.class).value();
   HttpServletRequest nativeRequest = (HttpServletRequest) request.getNativeRequest();
   MultipartRequest multipartRequest =
       WebUtils.getNativeRequest(nativeRequest, MultipartRequest.class);
   MockHttpServletRequest mockRequest = null;
   if (multipartRequest != null) {
     MockMultipartHttpServletRequest mockMultipartRequest = new MockMultipartHttpServletRequest();
     for (MultipartFile file : multipartRequest.getFileMap().values()) {
       mockMultipartRequest.addFile(
           new MultipartFileWrapper(getNewParameterName(file.getName(), modelPrefixName), file));
     }
     mockRequest = mockMultipartRequest;
   } else {
     mockRequest = new MockHttpServletRequest();
   }
   for (Entry<String, String> entry : getUriTemplateVariables(request).entrySet()) {
     String parameterName = entry.getKey();
     String value = entry.getValue();
     if (isFormModelAttribute(parameterName, modelPrefixName)) {
       mockRequest.setParameter(getNewParameterName(parameterName, modelPrefixName), value);
     }
   }
   for (Object parameterEntry : nativeRequest.getParameterMap().entrySet()) {
     Entry<String, String[]> entry = (Entry<String, String[]>) parameterEntry;
     String parameterName = entry.getKey();
     String[] value = entry.getValue();
     if (isFormModelAttribute(parameterName, modelPrefixName)) {
       mockRequest.setParameter(getNewParameterName(parameterName, modelPrefixName), value);
     }
   }
   return mockRequest;
 }