private Obs getObsGroup() {
    ConceptDatatype datatype = new ConceptDatatype();
    datatype.setUuid(ConceptDatatype.CODED_UUID);
    datatype.setHl7Abbreviation(ConceptDatatype.CODED);

    Concept concept = new Concept(1);
    concept.setDatatype(datatype);
    concept.addName(new ConceptName("MedSet", Locale.ENGLISH));

    ConceptSource source = new ConceptSource();
    source.setName("LOCAL");

    ConceptMap map = new ConceptMap();
    map.setSourceCode("100");
    map.setSource(source);

    concept.addConceptMapping(map);

    Date dateCreated = new Date(213231421890234L);

    Obs obs = new Obs(1);
    obs.setConcept(concept);
    obs.setDateCreated(dateCreated);

    return obs;
  }
  /**
   * @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 edit obs with edit reason and complex concept",
      method =
          "saveObs(HttpServletRequest, HttpServletResponse, String, RadiologyOrder, Obs Obs, BindingResult)")
  public void saveObs_ShouldEditObsWithEditReasonAndComplexConcept() {

    MockHttpSession mockSession = new MockHttpSession();
    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);

    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()));
  }
  /**
   * @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));
  }
 public ObsBuilder addMember(Concept question, String valueText) {
   Obs child = new Obs();
   child.setPerson(obs.getPerson());
   child.setObsDatetime(obs.getObsDatetime());
   child.setConcept(question);
   child.setValueText(valueText);
   obs.addGroupMember(child);
   return this;
 }
 private Obs findOrCreateObs(Obs diagnosisObs, Concept concept) {
   for (Obs o : diagnosisObs.getGroupMembers()) {
     if (concept.equals(o.getConcept())) {
       return o;
     }
   }
   Obs obs = new Obs();
   obs.setConcept(concept);
   return obs;
 }
  @Test
  public void testParsingDispositionWithTransferLocation() throws Exception {
    Concept admit =
        new ConceptBuilder(
                null,
                conceptService.getConceptDatatypeByName("N/A"),
                conceptService.getConceptClassByName("Misc"))
            .addName("Transfer")
            .get();
    when(emrConceptService.getConcept("test:transfer")).thenReturn(admit);

    Obs dispositionObs =
        dispositionDescriptor.buildObsGroup(
            new Disposition(
                "emrapi.transfer",
                "Transfer",
                "test:transfer",
                Collections.<String>emptyList(),
                Collections.<DispositionObs>emptyList()),
            emrConceptService);

    Obs transferLocationObs = new Obs();
    transferLocationObs.setObsId(100);
    transferLocationObs.setConcept(dispositionDescriptor.getInternalTransferLocationConcept());
    transferLocationObs.setValueText("3");
    dispositionObs.addGroupMember(transferLocationObs);

    Location transferLocation = new Location();
    transferLocation.setName("Outpatient clinic");
    when(locationService.getLocation(3)).thenReturn(transferLocation);

    encounter.addObs(doNotGoToServiceToFormatMembers(dispositionObs));
    ParsedObs parsed = parser.parseObservations(Locale.ENGLISH);

    SimpleObject expectedTransferLocationObject =
        SimpleObject.create("obsId", transferLocationObs.getObsId());
    expectedTransferLocationObject.put("question", "Transfer location");
    expectedTransferLocationObject.put("answer", "Outpatient clinic");

    List<SimpleObject> expectedAdditionalObsList = new ArrayList<SimpleObject>();
    expectedAdditionalObsList.add(expectedTransferLocationObject);

    assertThat(parsed.getDiagnoses().size(), is(0));
    assertThat(parsed.getDispositions().size(), is(1));
    assertThat(parsed.getObs().size(), is(0));
    assertThat(path(parsed.getDispositions(), 0, "disposition"), is((Object) "Transfer"));
    assertThat(
        path(parsed.getDispositions(), 0, "additionalObs"), is((Object) expectedAdditionalObsList));
  }
  /** @see {@link ObsValidator#validate(java.lang.Object, org.springframework.validation.Errors)} */
  @Test
  @Verifies(
      value = "should fail validation if concept datatype is text and valueText is null",
      method = "validate(java.lang.Object, org.springframework.validation.Errors)")
  public void validate_shouldFailValidationIfConceptDatatypeIsTextAndValueTextIsNull()
      throws Exception {
    Obs obs = new Obs();
    obs.setPerson(Context.getPersonService().getPerson(2));
    obs.setConcept(Context.getConceptService().getConcept(19));
    obs.setObsDatetime(new Date());

    Errors errors = new BindException(obs, "obs");
    new ObsValidator().validate(obs, errors);

    Assert.assertTrue(errors.hasFieldErrors("valueText"));
  }
  /** @see {@link ObsValidator#validate(java.lang.Object, org.springframework.validation.Errors)} */
  @Test
  @Verifies(
      value = "should pass validation if all values present",
      method = "validate(java.lang.Object, org.springframework.validation.Errors)")
  public void validate_shouldPassValidationIfAllValuesPresent() throws Exception {
    Obs obs = new Obs();
    obs.setPerson(Context.getPersonService().getPerson(2));
    obs.setConcept(Context.getConceptService().getConcept(5089));
    obs.setObsDatetime(new Date());
    obs.setValueNumeric(1.0);

    Errors errors = new BindException(obs, "obs");
    new ObsValidator().validate(obs, errors);

    Assert.assertFalse(errors.hasErrors());
  }
  /** @see {@link ObsValidator#validate(java.lang.Object, org.springframework.validation.Errors)} */
  @Test
  @Verifies(
      value = "should fail if obs has no values and not parent",
      method = "validate(java.lang.Object, org.springframework.validation.Errors)")
  public void validate_shouldFailIfObsHasNoValuesAndNotParent() throws Exception {

    Obs obs = new Obs();
    obs.setPerson(Context.getPersonService().getPerson(2));
    obs.setConcept(Context.getConceptService().getConcept(18));
    obs.setObsDatetime(new Date());

    Errors errors = new BindException(obs, "obs");
    new ObsValidator().validate(obs, errors);

    Assert.assertTrue(errors.getGlobalErrorCount() > 0);
  }
  @Test
  public void testParsingDispositionWithDateOfDeath() throws Exception {
    Concept admit =
        new ConceptBuilder(
                null,
                conceptService.getConceptDatatypeByName("N/A"),
                conceptService.getConceptClassByName("Misc"))
            .addName("Death")
            .get();
    when(emrConceptService.getConcept("test:death")).thenReturn(admit);

    Obs dispositionObs =
        dispositionDescriptor.buildObsGroup(
            new Disposition(
                "emrapi.death",
                "Death",
                "test:death",
                Collections.<String>emptyList(),
                Collections.<DispositionObs>emptyList()),
            emrConceptService);

    Date dateOfDeath = new DateTime(2012, 2, 20, 10, 10, 10).toDate();
    Obs dateOfDeathObs = new Obs();
    dateOfDeathObs.setObsId(100);
    dateOfDeathObs.setConcept(dispositionDescriptor.getDateOfDeathConcept());
    dateOfDeathObs.setValueDate(dateOfDeath);
    dispositionObs.addGroupMember(dateOfDeathObs);

    encounter.addObs(doNotGoToServiceToFormatMembers(dispositionObs));
    ParsedObs parsed = parser.parseObservations(Locale.ENGLISH);

    SimpleObject expectedAdmissionLocationObject =
        SimpleObject.create("obsId", dateOfDeathObs.getObsId());
    expectedAdmissionLocationObject.put("question", "Date of death");
    expectedAdmissionLocationObject.put("answer", "20 Feb 2012 10:10 AM");

    List<SimpleObject> expectedAdditionalObsList = new ArrayList<SimpleObject>();
    expectedAdditionalObsList.add(expectedAdmissionLocationObject);

    assertThat(parsed.getDiagnoses().size(), is(0));
    assertThat(parsed.getDispositions().size(), is(1));
    assertThat(parsed.getObs().size(), is(0));
    assertThat(path(parsed.getDispositions(), 0, "disposition"), is((Object) "Death"));
    assertThat(
        path(parsed.getDispositions(), 0, "additionalObs"), is((Object) expectedAdditionalObsList));
  }
  /** @see {@link ObsValidator#validate(java.lang.Object, org.springframework.validation.Errors)} */
  @Test
  @Verifies(
      value = "should fail validation if obsDatetime is null",
      method = "validate(java.lang.Object, org.springframework.validation.Errors)")
  public void validate_shouldFailValidationIfObsDatetimeIsNull() throws Exception {
    Obs obs = new Obs();
    obs.setPerson(Context.getPersonService().getPerson(2));
    obs.setConcept(Context.getConceptService().getConcept(5089));
    obs.setValueNumeric(1.0);

    Errors errors = new BindException(obs, "obs");
    new ObsValidator().validate(obs, errors);

    Assert.assertFalse(errors.hasFieldErrors("person"));
    Assert.assertFalse(errors.hasFieldErrors("concept"));
    Assert.assertTrue(errors.hasFieldErrors("obsDatetime"));
    Assert.assertFalse(errors.hasFieldErrors("valueNumeric"));
  }
  /** @see {@link ObsValidator#validate(java.lang.Object, org.springframework.validation.Errors)} */
  @Test
  @Verifies(
      value = "should fail validation if concept datatype is boolean and valueBoolean is null",
      method = "validate(java.lang.Object, org.springframework.validation.Errors)")
  public void validate_shouldFailValidationIfConceptDatatypeIsBooleanAndValueBooleanIsNull()
      throws Exception {
    Obs obs = new Obs();
    obs.setPerson(Context.getPersonService().getPerson(2));
    obs.setConcept(Context.getConceptService().getConcept(18));
    obs.setObsDatetime(new Date());

    Errors errors = new BindException(obs, "obs");
    new ObsValidator().validate(obs, errors);

    Assert.assertFalse(errors.hasFieldErrors("person"));
    Assert.assertFalse(errors.hasFieldErrors("concept"));
    Assert.assertFalse(errors.hasFieldErrors("obsDatetime"));
    Assert.assertTrue(
        errors.hasFieldErrors("valueNumeric")); // Booleans translates to numeric at the moment
  }
  /**
   * @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()));
  }
  /** @see {@link ObsValidator#validate(java.lang.Object, org.springframework.validation.Errors)} */
  @Test
  @Verifies(
      value = "should fail validation if obs ancestors contains obs",
      method = "validate(java.lang.Object, org.springframework.validation.Errors)")
  public void validate_shouldFailValidationIfObsAncestorsContainsObs() throws Exception {
    Obs obs = new Obs();
    obs.setPerson(Context.getPersonService().getPerson(2));
    obs.setConcept(Context.getConceptService().getConcept(3)); // datatype = N/A
    obs.setObsDatetime(new Date());

    Set<Obs> group = new HashSet<Obs>();
    group.add(obs);
    obs.setGroupMembers(group);

    Errors errors = new BindException(obs, "obs");
    new ObsValidator().validate(obs, errors);

    Assert.assertFalse(errors.hasFieldErrors("person"));
    Assert.assertFalse(errors.hasFieldErrors("concept"));
    Assert.assertFalse(errors.hasFieldErrors("obsDatetime"));
    Assert.assertTrue(errors.hasFieldErrors("groupMembers"));
  }
  /** @see {@link ObsValidator#validate(java.lang.Object, org.springframework.validation.Errors)} */
  @Test
  @Verifies(
      value = "should fail if the parent obs has values",
      method = "validate(java.lang.Object, org.springframework.validation.Errors)")
  public void validate_shouldFailIfParentObshasValues() throws Exception {

    Obs obs = new Obs();
    obs.setPerson(Context.getPersonService().getPerson(2));
    obs.setConcept(Context.getConceptService().getConcept(18));

    obs.setValueBoolean(false);
    obs.setValueCoded(Context.getConceptService().getConcept(18));
    obs.setValueComplex("test");
    obs.setValueDatetime(new Date());
    obs.setValueDrug(Context.getConceptService().getDrug(3));
    obs.setValueGroupId(getLoadCount());
    obs.setValueModifier("test");
    obs.setValueNumeric(1212.0);
    obs.setValueText("test");

    Set<Obs> group = new HashSet<Obs>();
    group.add(Context.getObsService().getObs(7));
    group.add(Context.getObsService().getObs(9));
    obs.setGroupMembers(group);

    Errors errors = new BindException(obs, "obs");
    new ObsValidator().validate(obs, errors);

    Assert.assertFalse(errors.hasFieldErrors("person"));
    Assert.assertFalse(errors.hasFieldErrors("concept"));
    Assert.assertTrue(errors.hasFieldErrors("valueCoded"));
    Assert.assertTrue(errors.hasFieldErrors("valueDrug"));
    Assert.assertTrue(errors.hasFieldErrors("valueDatetime"));
    Assert.assertTrue(errors.hasFieldErrors("valueNumeric"));
    Assert.assertTrue(errors.hasFieldErrors("valueModifier"));
    Assert.assertTrue(errors.hasFieldErrors("valueText"));
    Assert.assertTrue(errors.hasFieldErrors("valueBoolean"));
    Assert.assertTrue(errors.hasFieldErrors("valueComplex"));
  }
  /** @see {@link ObsValidator#validate(java.lang.Object, org.springframework.validation.Errors)} */
  @Test
  @Verifies(
      value =
          "should fail validation if concept value for text datatype is greater than the maximum length",
      method = "validate(java.lang.Object, org.springframework.validation.Errors)")
  public void validate_shouldFailValidationIfValueTextIsGreaterThanTheMaximumLength()
      throws Exception {
    Obs obs = new Obs();
    obs.setPerson(Context.getPersonService().getPerson(2));
    obs.setConcept(Context.getConceptService().getConcept(19));
    obs.setObsDatetime(new Date());
    obs.setValueText(
        "the limit of valueText is 50. So we are trying to test it with more than 50 characters and this is the test text	1");

    Errors errors = new BindException(obs, "obs");
    new ObsValidator().validate(obs, errors);

    Assert.assertFalse(errors.hasFieldErrors("person"));
    Assert.assertFalse(errors.hasFieldErrors("concept"));
    Assert.assertFalse(errors.hasFieldErrors("obsDatetime"));
    Assert.assertTrue(errors.hasFieldErrors("valueText"));
  }
 /**
  * Creates an OpenMRS Obs instance
  *
  * @param concept concept associated with the Obs
  * @param value value associated with the Obs
  * @param datetime date/time associated with the Obs (may be null)
  * @param accessionNumber accession number associatd with the Obs (may be null)
  * @return the created Obs instance
  */
 public static Obs createObs(
     Concept concept, Object value, Date datetime, String accessionNumber) {
   Obs obs = new Obs();
   obs.setConcept(concept);
   ConceptDatatype dt = obs.getConcept().getDatatype();
   if (dt.isNumeric()) {
     obs.setValueNumeric(Double.parseDouble(value.toString()));
   } else if (dt.isText()) {
     if (value instanceof Location) {
       obs.setValueText(((Location) value).getLocationId().toString());
     } else {
       obs.setValueText(value.toString());
     }
   } else if (dt.isCoded()) {
     if (value instanceof Concept) obs.setValueCoded((Concept) value);
     else obs.setValueCoded((Concept) convertToType(value.toString(), Concept.class));
   } else if (dt.isBoolean()) {
     boolean booleanValue =
         value != null && !Boolean.FALSE.equals(value) && !"false".equals(value);
     obs.setValueNumeric(booleanValue ? 1.0 : 0.0);
   } else if (dt.isDate()) {
     Date date = (Date) value;
     obs.setValueDatetime(date);
   } else if ("ZZ".equals(dt.getHl7Abbreviation())) {
     // don't set a value
   } else {
     throw new IllegalArgumentException(
         "concept datatype not yet implemented: "
             + dt.getName()
             + " with Hl7 Abbreviation: "
             + dt.getHl7Abbreviation());
   }
   if (datetime != null) obs.setObsDatetime(datetime);
   if (accessionNumber != null) obs.setAccessionNumber(accessionNumber);
   return obs;
 }
  @Test
  public void shouldSubmitEDConsultNoteWithAdditionalObservationsOfTypeDate() throws Exception {
    int primaryConceptNameId = 2460;

    String diagnosisJson =
        "{ \"certainty\": \"PRESUMED\", \"diagnosisOrder\": \"PRIMARY\", \"diagnosis\": \""
            + CodedOrFreeTextAnswer.CONCEPT_NAME_PREFIX
            + primaryConceptNameId
            + "\" }";

    String additionalObsJson =
        "{ \"concept\": \"uuid-123\", \"value\": \"2013-05-21 17:23:47\", \"datatype\": \"Date\"}";

    Concept conceptFor2460 = new Concept();
    final ConceptName conceptName2460 = new ConceptName();
    conceptName2460.setConcept(conceptFor2460);

    when(conceptService.getConceptName(primaryConceptNameId)).thenReturn(conceptName2460);

    final Concept conceptForAdditionalObs = new Concept();
    conceptForAdditionalObs.setUuid("uuid-123");
    Calendar calendar = new GregorianCalendar(2013, 04, 21, 17, 23, 47);
    final Date dateForAdditionalObs = calendar.getTime();

    when(conceptService.getConceptByUuid("uuid-123")).thenReturn(conceptForAdditionalObs);

    Patient patient = new Patient();
    patient.addName(new PersonName("Jean", "Paul", "Marie"));
    final Location sessionLocation = new Location();
    final Provider currentProvider = new Provider();

    DispositionFactory dispositionFactory = mock(DispositionFactory.class);

    EmrContext emrContext = new EmrContext();
    emrContext.setSessionLocation(sessionLocation);
    emrContext.setCurrentProvider(currentProvider);

    MockHttpSession httpSession = new MockHttpSession();
    MockHttpServletRequest httpServletRequest = new MockHttpServletRequest();
    ConsultPageController controller = new ConsultPageController();
    String result =
        controller.post(
            patient,
            asList(diagnosisJson),
            "",
            asList(additionalObsJson),
            "",
            httpSession,
            httpServletRequest,
            consultService,
            conceptService,
            dispositionFactory,
            emrContext,
            new TestUiUtils());

    final Obs traumaObs = new Obs();
    traumaObs.setConcept(conceptForAdditionalObs);
    traumaObs.setValueDate(dateForAdditionalObs);

    verify(consultService)
        .saveConsultNote(
            argThat(
                new ArgumentMatcher<ConsultNote>() {
                  @Override
                  public boolean matches(Object o) {
                    ConsultNote actual = (ConsultNote) o;
                    Obs actualObs = actual.getAdditionalObs().get(0);
                    return containsInAnyOrder(
                                new Diagnosis(
                                    new CodedOrFreeTextAnswer(conceptName2460),
                                    Diagnosis.Order.PRIMARY))
                            .matches(actual.getDiagnoses())
                        && actual.getAdditionalObs().size() == 1
                        && actualObs.getConcept() == conceptForAdditionalObs
                        && actualObs.getValueDate().equals(dateForAdditionalObs);
                  }
                }));
  }
 public ObsBuilder setConcept(Concept question) {
   obs.setConcept(question);
   return this;
 }
  @Test
  public void shouldEvaluateOBRORUR01TemplateForOBSGroup() throws Exception {
    // given
    Encounter encounter = new Encounter();

    Date date = new Date();
    encounter.setEncounterDatetime(date);
    encounter.setUuid("ENCOUNTER UUID");

    EncounterType encounterType = new EncounterType();
    encounterType.setName("ENCOUNTER TYPE NAME");
    encounter.setEncounterType(encounterType);

    Location location = new Location(1);
    location.setUuid("LOCATION UUID");
    location.setName("LOCATION NAME");
    encounter.setLocation(location);

    Person provider = new Person(1);
    provider.setUuid("PROVIDER UUID");
    provider.addName(
        new PersonName("PROVIDER GIVENNAME", "PROVIDER MIDDLENAME", "PROVIDER FAMILYNAME"));
    encounter.setProvider(provider);

    ConceptSource source = new ConceptSource();
    source.setName("AMPATH");

    ConceptMap map = new ConceptMap();
    map.setSourceCode("200");
    map.setSource(source);

    ConceptDatatype datatype = new ConceptDatatype();
    datatype.setUuid(ConceptDatatype.NUMERIC_UUID);
    datatype.setHl7Abbreviation(ConceptDatatype.NUMERIC);

    ConceptNumeric concept = new ConceptNumeric();
    concept.setDatatype(datatype);
    concept.addConceptMapping(map);
    concept.addName(new ConceptName("NumericConcept", Locale.ENGLISH));
    concept.setUnits("mg");

    Date dateCreated = new Date(213231421890234L);

    Obs obs = new Obs(2);
    obs.setConcept(concept);
    obs.setDateCreated(dateCreated);
    obs.setValueNumeric(10d);

    obs.setObsGroup(getObsGroup());
    obs.getObsGroup().addGroupMember(obs);

    encounter.addObs(obs);

    obs = new Obs(3);
    obs.setConcept(concept);
    obs.setDateCreated(dateCreated);
    obs.setValueNumeric(23d);
    encounter.addObs(obs);

    Map<String, Object> bindings = new HashMap<String, Object>();
    bindings.put("encounter", encounter);
    bindings.put("implementationId", "MVP");

    // when
    HL7Template hl7Template = hl7QueryService.getHL7TemplateByName("Generic Obs Group");
    String evaluatedTemplate = hl7QueryService.evaluateTemplate(hl7Template, bindings);

    // then
    evaluatedTemplate = StringUtils.deleteWhitespace(evaluatedTemplate);
    Assert.assertEquals(
        "<ORU_R01.ORDER_OBSERVATION><OBR><OBR.1>0</OBR.1><OBR.4><CE.1>100</CE.1>"
            + "<CE.2>MEDICALRECORDOBSERVATIONS</CE.2><CE.3>LOCAL</CE.3></OBR.4><OBR.18>0</OBR.18>"
            + "<OBR.29><EIP.2><EI.3>ENCOUNTERUUID</EI.3></EIP.2></OBR.29></OBR><ORU_R01.OBSERVATION>"
            + "<OBX><OBX.1>1</OBX.1><OBX.2>NM</OBX.2><OBX.3><CE.1>200</CE.1><CE.2>NumericConcept</CE.2>"
            + "<CE.3>AMPATH</CE.3></OBX.3><OBX.5>23.0</OBX.5><OBX.6><CE.1>mg</CE.1><CE.3>UCUM</CE.3></OBX.6>"
            + "<OBX.14><TS.1>"
            + new HL7TemplateFunctions().formatDate(dateCreated, null)
            + "</TS.1>"
            + "</OBX.14></OBX></ORU_R01.OBSERVATION></ORU_R01.ORDER_OBSERVATION>"
            + "<ORU_R01.ORDER_OBSERVATION><OBR><OBR.1>2</OBR.1><OBR.4><CE.1>100</CE.1><CE.2>MedSet</CE.2>"
            + "<CE.3>LOCAL</CE.3></OBR.4><OBR.18>0</OBR.18><OBR.29><EIP.2><EI.3>ENCOUNTERUUID</EI.3></EIP.2></OBR.29"
            + "></OBR><ORU_R01.OBSERVATION><OBX><OBX.1>2</OBX.1><OBX.2>NM</OBX.2><OBX.3><CE.1>200</CE.1>"
            + "<CE.2>NumericConcept</CE.2><CE.3>AMPATH</CE.3></OBX.3><OBX.5>10.0</OBX.5><OBX.6><CE.1>mg</CE.1>"
            + "<CE.3>UCUM</CE.3></OBX.6><OBX.14><TS.1>"
            + new HL7TemplateFunctions().formatDate(dateCreated, null)
            + "</TS.1></OBX.14></OBX></ORU_R01.OBSERVATION></ORU_R01.ORDER_OBSERVATION>",
        evaluatedTemplate);
  }
  @RequestMapping(method = RequestMethod.POST)
  public void savePatientInfo(
      @RequestParam("patientId") Integer patientId,
      @RequestParam(value = "encounterId", required = false) Integer encounterId,
      HttpServletRequest request,
      HttpServletResponse response)
      throws ParseException, IOException {

    Map<String, String> parameters = RegistrationWebUtils.optimizeParameters(request);

    // get patient
    Patient patient = Context.getPatientService().getPatient(patientId);

    /*
     * SAVE ENCOUNTER
     */
    Encounter encounter = null;
    if (encounterId != null) {
      encounter = Context.getEncounterService().getEncounter(encounterId);
    } else {
      encounter = RegistrationWebUtils.createEncounter(patient, true);

      // create OPD obs
      Concept opdWardConcept =
          Context.getConceptService().getConcept(RegistrationConstants.CONCEPT_NAME_OPD_WARD);
      Concept selectedOPDConcept =
          Context.getConceptService()
              .getConcept(
                  Integer.parseInt(
                      parameters.get(RegistrationConstants.FORM_FIELD_PATIENT_OPD_WARD)));
      Obs opd = new Obs();
      opd.setConcept(opdWardConcept);
      opd.setValueCoded(selectedOPDConcept);
      encounter.addObs(opd);

      // send patient to opd room/bloodbank

      // harsh 5/10/2012 changed the way to get blood bank concept->shifted hardcoded dependency
      // from id to name
      //			Concept bloodbankConcept = Context.getConceptService().getConcept(
      //			    GlobalPropertyUtil.getInteger(RegistrationConstants.PROPERTY_BLOODBANK_CONCEPT_ID,
      // 6425));
      String bloodBankWardName =
          GlobalPropertyUtil.getString(
              RegistrationConstants.PROPERTY_BLOODBANK_OPDWARD_NAME, "Blood Bank Room");

      // ghanshyam 03-sept-2013 Bug #394 [Blood bank]queue
      String socn = new String(selectedOPDConcept.getName().toString());
      String substringofsocn = socn.substring(0, 15);

      if (!substringofsocn.equalsIgnoreCase(bloodBankWardName)) {
        RegistrationWebUtils.sendPatientToOPDQueue(patient, selectedOPDConcept, true);
      } else {
        OrderType orderType = null;
        String orderTypeName =
            Context.getAdministrationService().getGlobalProperty("bloodbank.orderTypeName");
        orderType = OrderUtil.getOrderTypeByName(orderTypeName);

        Order order = new Order();
        order.setConcept(selectedOPDConcept);
        order.setCreator(Context.getAuthenticatedUser());
        order.setDateCreated(new Date());
        order.setOrderer(Context.getAuthenticatedUser());
        order.setPatient(patient);
        order.setStartDate(new Date());
        order.setAccessionNumber("0");
        order.setOrderType(orderType);
        order.setEncounter(encounter);
        encounter.addOrder(order);
      }
    }

    // create temporary attributes
    for (String name : parameters.keySet()) {
      if ((name.contains(".attribute.")) && (!StringUtils.isBlank(parameters.get(name)))) {
        String[] parts = name.split("\\.");
        String idText = parts[parts.length - 1];
        Integer id = Integer.parseInt(idText);
        Concept tempCatConcept = Context.getConceptService().getConceptByName("TEMPORARY CATEGORY");

        Concept temporaryAttributeConcept =
            Context.getConceptService().getConcept(tempCatConcept.getConceptId());
        Obs temporaryAttribute = new Obs();
        temporaryAttribute.setConcept(temporaryAttributeConcept);
        logger.info("concept: " + temporaryAttributeConcept);
        logger.info("value: " + parameters.get(name));
        temporaryAttribute.setValueAsString(parameters.get(name));
        encounter.addObs(temporaryAttribute);
      }
    }

    // save encounter
    Context.getEncounterService().saveEncounter(encounter);
    logger.info(
        String.format(
            "Save encounter for the visit of patient [encounterId=%s, patientId=%s]",
            encounter.getId(), patient.getId()));

    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    out.print("success");
  }