Search in sources :

Example 66 with ObjectNode

use of org.codehaus.jackson.node.ObjectNode in project openmrs-module-coreapps by openmrs.

the class EncounterDiagnosesTagHandlerComponentTest method testHandleSubmissionHandlesValidSubmissionEditingForm.

@Test
public void testHandleSubmissionHandlesValidSubmissionEditingForm() throws Exception {
    final DiagnosisMetadata dmd = emrApiProperties.getDiagnosisMetadata();
    final Date date = new Date();
    // first, create an encounter
    final Concept malaria = conceptService.getConcept(11);
    final Patient patient = patientService.getPatient(8);
    final Encounter existingEncounter = new Encounter();
    existingEncounter.setEncounterType(new EncounterType(1));
    existingEncounter.setPatient(patient);
    existingEncounter.setEncounterDatetime(date);
    existingEncounter.setLocation(locationService.getLocation(2));
    Obs primaryDiagnosis = dmd.buildDiagnosisObsGroup(new Diagnosis(new CodedOrFreeTextAnswer(malaria), Diagnosis.Order.PRIMARY));
    Obs secondaryDiagnosis = dmd.buildDiagnosisObsGroup(new Diagnosis(new CodedOrFreeTextAnswer("Unknown disease"), Diagnosis.Order.SECONDARY));
    existingEncounter.addObs(primaryDiagnosis);
    existingEncounter.addObs(secondaryDiagnosis);
    encounterService.saveEncounter(existingEncounter);
    ObjectMapper jackson = new ObjectMapper();
    ArrayNode json = jackson.createArrayNode();
    {
        // change the existing primary diagnosis from PRESUMED to CONFIRMED
        ObjectNode diagnosisNode = json.addObject();
        diagnosisNode.put("certainty", "CONFIRMED");
        diagnosisNode.put("order", "PRIMARY");
        diagnosisNode.put("diagnosis", CodedOrFreeTextAnswer.CONCEPT_PREFIX + "11");
        diagnosisNode.put("existingObs", primaryDiagnosis.getObsId());
    }
    {
        // this is a new diagnosis
        ObjectNode diagnosisNode = json.addObject();
        diagnosisNode.put("certainty", "PRESUMED");
        diagnosisNode.put("order", "SECONDARY");
        diagnosisNode.put("diagnosis", CodedOrFreeTextAnswer.NON_CODED_PREFIX + "I had spelled it wrong before");
    }
    final String jsonToSubmit = jackson.writeValueAsString(json);
    new RegressionTestHelper() {

        @Override
        public String getXmlDatasetPath() {
            return "";
        }

        @Override
        public String getFormName() {
            return "encounterDiagnosesSimpleForm";
        }

        @Override
        public Map<String, Object> getFormEntrySessionAttributes() {
            Map<String, Object> attributes = new HashMap<String, Object>();
            attributes.put("uiUtils", new TestUiUtils() {

                @Override
                public String includeFragment(String providerName, String fragmentId, Map<String, Object> config) throws PageAction {
                    return "[[ included fragment " + providerName + "." + fragmentId + " here ]]";
                }
            });
            return attributes;
        }

        @Override
        public Patient getPatientToView() throws Exception {
            return patient;
        }

        @Override
        public Encounter getEncounterToEdit() {
            return existingEncounter;
        }

        @Override
        public String[] widgetLabelsForEdit() {
            return new String[] { "Date:", "Location:", "Provider:", "Encounter Type:" };
        }

        @Override
        public void setupEditRequest(MockHttpServletRequest request, Map<String, String> widgets) {
            request.setParameter(widgets.get("Date:"), dateAsString(date));
            request.setParameter(widgets.get("Location:"), "2");
            request.setParameter(widgets.get("Provider:"), "1");
            request.setParameter(widgets.get("Encounter Type:"), "1");
            request.setParameter("encounterDiagnoses", jsonToSubmit);
        }

        @Override
        public void testEditFormHtml(String html) {
            System.out.println(html);
        }

        @Override
        public void testEditedResults(SubmissionResults results) {
            results.assertNoErrors();
            results.assertEncounterEdited();
            List<Obs> diagnoses = new ArrayList<Obs>();
            for (Obs obs : results.getEncounterCreated().getObsAtTopLevel(true)) {
                if (dmd.isDiagnosis(obs)) {
                    diagnoses.add(obs);
                }
            }
            Matcher<Obs> newPrimary = new ObsGroupMatcher().withGroupingConcept(dmd.getDiagnosisSetConcept()).withNonVoidedObs(dmd.getDiagnosisCertaintyConcept(), dmd.getConceptFor(Diagnosis.Certainty.CONFIRMED)).withVoidedObs(dmd.getDiagnosisCertaintyConcept(), dmd.getConceptFor(Diagnosis.Certainty.PRESUMED)).withNonVoidedObs(dmd.getDiagnosisOrderConcept(), dmd.getConceptFor(Diagnosis.Order.PRIMARY)).withNonVoidedObs(dmd.getCodedDiagnosisConcept(), malaria);
            Matcher<Obs> newSecondary = new ObsGroupMatcher().withGroupingConcept(dmd.getDiagnosisSetConcept()).withNonVoidedObs(dmd.getDiagnosisCertaintyConcept(), dmd.getConceptFor(Diagnosis.Certainty.PRESUMED)).withNonVoidedObs(dmd.getDiagnosisOrderConcept(), dmd.getConceptFor(Diagnosis.Order.SECONDARY)).withNonVoidedObs(dmd.getNonCodedDiagnosisConcept(), "I had spelled it wrong before");
            Matcher<Obs> oldSecondary = new ObsGroupMatcher().withGroupingConcept(dmd.getDiagnosisSetConcept()).withVoidedObs(dmd.getDiagnosisCertaintyConcept(), dmd.getConceptFor(Diagnosis.Certainty.PRESUMED)).withVoidedObs(dmd.getDiagnosisOrderConcept(), dmd.getConceptFor(Diagnosis.Order.SECONDARY)).withVoidedObs(dmd.getNonCodedDiagnosisConcept(), "Unknown disease").thatIsVoided();
            assertThat(diagnoses.size(), is(3));
            assertThat(diagnoses, containsInAnyOrder(newPrimary, newSecondary, oldSecondary));
        }
    }.run();
}
Also used : ObsGroupMatcher(org.openmrs.module.emrapi.matcher.ObsGroupMatcher) Matcher(org.hamcrest.Matcher) Encounter(org.openmrs.Encounter) ArrayList(java.util.ArrayList) List(java.util.List) Diagnosis(org.openmrs.module.emrapi.diagnosis.Diagnosis) ArrayNode(org.codehaus.jackson.node.ArrayNode) ObjectMapper(org.codehaus.jackson.map.ObjectMapper) Concept(org.openmrs.Concept) Obs(org.openmrs.Obs) ObjectNode(org.codehaus.jackson.node.ObjectNode) TestUiUtils(org.openmrs.module.appui.TestUiUtils) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) DiagnosisMetadata(org.openmrs.module.emrapi.diagnosis.DiagnosisMetadata) Patient(org.openmrs.Patient) CodedOrFreeTextAnswer(org.openmrs.module.emrapi.diagnosis.CodedOrFreeTextAnswer) Date(java.util.Date) EncounterType(org.openmrs.EncounterType) HashMap(java.util.HashMap) Map(java.util.Map) ObsGroupMatcher(org.openmrs.module.emrapi.matcher.ObsGroupMatcher) RegressionTestHelper(org.openmrs.module.htmlformentry.RegressionTestHelper) Test(org.junit.Test) BaseModuleWebContextSensitiveTest(org.openmrs.web.test.BaseModuleWebContextSensitiveTest)

Example 67 with ObjectNode

use of org.codehaus.jackson.node.ObjectNode in project openmrs-module-coreapps by openmrs.

the class ProgramHistoryFragmentController method controller.

public void controller(FragmentConfiguration config, @FragmentParam("app") AppDescriptor app, @InjectBeans PatientDomainWrapper patientWrapper, @SpringBean("programWorkflowService") ProgramWorkflowService programWorkflowService) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    Object patient = null;
    patient = config.get("patient");
    if (patient == null) {
        patient = config.get("patientId");
    }
    if (patient == null) {
        config.require("patient");
    }
    if (patient instanceof Patient) {
        patientWrapper.setPatient((Patient) patient);
    } else if (patient instanceof PatientDomainWrapper) {
        patientWrapper = (PatientDomainWrapper) patient;
    } else if (patient instanceof Integer) {
        // assume we have patientId
        patientWrapper.setPatient(Context.getPatientService().getPatient((Integer) patient));
    } else {
        throw new IllegalArgumentException("Patient must be of type Patient or PatientDomainWrapper");
    }
    ObjectNode appConfig = app.getConfig();
    appConfig.put("patientUuid", patientWrapper.getPatient().getUuid());
    if (appConfig.get("program") == null || StringUtils.isEmpty(appConfig.get("program").getTextValue())) {
        throw new MissingPropertyException("Program must be specified");
    }
    Program program = programWorkflowService.getProgramByUuid(appConfig.get("program").getTextValue());
    if (program == null) {
        throw new MissingPropertyException("Invalid program");
    }
    List<PatientProgram> patientPrograms = programWorkflowService.getPatientPrograms(patientWrapper.getPatient(), program, null, null, null, null, false);
    // TODO: assumption here is that "getPatientPrograms" returns results in chronological order--need to confirm?
    Collections.reverse(patientPrograms);
    List<String> programJson = new ArrayList<String>();
    Boolean includeActive = appConfig.get("includeActive") != null ? appConfig.get("includeActive").getBooleanValue() : true;
    Boolean includeInactive = appConfig.get("includeInactive") != null ? appConfig.get("includeInactive").getBooleanValue() : true;
    for (PatientProgram patientProgram : patientPrograms) {
        if ((patientProgram.getDateCompleted() == null && includeActive) || (patientProgram.getDateCompleted() != null && includeInactive)) {
            appConfig.put("patientProgram", patientProgram.getUuid());
            programJson.add(appConfig.toString().replace('\"', '\''));
        }
    }
    Map<String, Object> appConfigMap = mapper.convertValue(appConfig, Map.class);
    config.merge(appConfigMap);
    config.addAttribute("programJson", programJson);
}
Also used : PatientDomainWrapper(org.openmrs.module.emrapi.patient.PatientDomainWrapper) PatientProgram(org.openmrs.PatientProgram) Program(org.openmrs.Program) ObjectNode(org.codehaus.jackson.node.ObjectNode) ArrayList(java.util.ArrayList) Patient(org.openmrs.Patient) MissingPropertyException(groovy.lang.MissingPropertyException) PatientProgram(org.openmrs.PatientProgram) ObjectMapper(org.codehaus.jackson.map.ObjectMapper)

Example 68 with ObjectNode

use of org.codehaus.jackson.node.ObjectNode in project openmrs-module-pihcore by PIH.

the class CauseOfDeathListTagHandlerComponentTest method testCreateAndEdit.

@Test
public void testCreateAndEdit() throws Exception {
    final ConceptName causeOne = conceptService.getConceptNameByUuid("2f7263e4-2a57-49b5-aef0-af9a259aac65");
    final Concept causeTwo = conceptService.getConcept(13);
    final Concept editedCauseTwo = conceptService.getConcept(11);
    final String causeThree = "Cause Three";
    final String editedCauseThree = "Edited Cause Three";
    final Concept causeFour = conceptService.getConcept(16);
    ArrayNode submission = jackson.createArrayNode();
    ObjectNode one = submission.addObject();
    one.put("ConceptName", causeOne.getUuid());
    ObjectNode two = submission.addObject();
    two.put("Concept", causeTwo.getUuid());
    ObjectNode three = submission.addObject();
    three.put("NonCodedValue", causeThree);
    ObjectNode four = submission.addObject();
    four.put("Concept", causeFour.getUuid());
    final String createJson = jackson.writeValueAsString(submission);
    two.put("Concept", editedCauseTwo.getUuid());
    three.put("NonCodedValue", editedCauseThree);
    // this removes 'four'
    submission.remove(3);
    final String editJson = jackson.writeValueAsString(submission);
    final Date date = new Date();
    new RegressionTestHelper() {

        @Override
        public String getXmlDatasetPath() {
            return "";
        }

        @Override
        public String getFormName() {
            return "causesOfDeathForm";
        }

        @Override
        public String[] widgetLabels() {
            return new String[] { "Date:", "Location:", "Provider:", "Causes:" };
        }

        @Override
        public void setupRequest(MockHttpServletRequest request, Map<String, String> widgets) {
            request.setParameter(widgets.get("Date:"), dateAsString(date));
            request.setParameter(widgets.get("Location:"), "2");
            request.setParameter(widgets.get("Provider:"), "1");
            request.setParameter(widgets.get("Causes:"), createJson);
        }

        @Override
        public void testResults(SubmissionResults results) {
            results.assertNoErrors();
            results.assertEncounterCreated();
            results.assertProvider(1);
            results.assertLocation(2);
            results.assertObsGroupCreatedCount(4);
            results.assertObsGroupCreated(groupingConcept.getConceptId(), codedCauseConcept.getId(), causeOne, sequenceConcept.getId(), 1);
            results.assertObsGroupCreated(groupingConcept.getConceptId(), codedCauseConcept.getId(), causeTwo, sequenceConcept.getId(), 2);
            results.assertObsGroupCreated(groupingConcept.getConceptId(), nonCodedCauseConcept.getId(), causeThree, sequenceConcept.getId(), 3);
            results.assertObsGroupCreated(groupingConcept.getConceptId(), codedCauseConcept.getId(), causeFour, sequenceConcept.getId(), 4);
            assertThat(results.getPatient().getCauseOfDeath(), is(causeFour));
        }

        @Override
        public boolean doEditEncounter() {
            return true;
        }

        @Override
        public String[] widgetLabelsForEdit() {
            return widgetLabels();
        }

        @Override
        public void setupEditRequest(MockHttpServletRequest request, Map<String, String> widgets) {
            request.setParameter(widgets.get("Date:"), dateAsString(date));
            request.setParameter(widgets.get("Location:"), "2");
            request.setParameter(widgets.get("Provider:"), "1");
            request.setParameter(widgets.get("Causes:"), editJson);
        }

        @Override
        public void testEditedResults(SubmissionResults results) {
            results.assertNoErrors();
            results.assertEncounterCreated();
            results.assertProvider(1);
            results.assertLocation(2);
            // there should be one voided member obs (causeTwo->causeTwoEdited), and one voided obs group (causeThree)
            // was causeThree
            results.assertObsVoided(groupingConcept.getConceptId(), null);
            assertVoidedObsInObsGroup(results.getEncounterCreated(), groupingConcept, codedCauseConcept, causeTwo);
            results.assertObsGroupCreatedCount(3);
            results.assertObsGroupCreated(groupingConcept.getConceptId(), codedCauseConcept.getId(), causeOne, sequenceConcept.getId(), 1);
            results.assertObsGroupCreated(groupingConcept.getConceptId(), codedCauseConcept.getId(), editedCauseTwo, sequenceConcept.getId(), 2);
            results.assertObsGroupCreated(groupingConcept.getConceptId(), nonCodedCauseConcept.getId(), editedCauseThree, sequenceConcept.getId(), 3);
            assertThat(results.getPatient().getCauseOfDeath(), is(unknownConcept));
        }

        private void assertVoidedObsInObsGroup(Encounter encounter, Concept groupingConcept, Concept concept, Concept value) {
            for (Obs candidate : encounter.getObsAtTopLevel(true)) {
                if (groupingConcept.equals(candidate.getConcept())) {
                    for (Obs member : candidate.getGroupMembers(true)) {
                        if (member.getVoided() && member.getConcept().equals(concept) && member.getValueCoded().equals(value)) {
                            return;
                        }
                    }
                }
            }
            Assert.fail("Did not find a voided obs of " + concept + "=" + value + " inside a group of " + groupingConcept);
        }
    }.run();
}
Also used : Concept(org.openmrs.Concept) Obs(org.openmrs.Obs) ObjectNode(org.codehaus.jackson.node.ObjectNode) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) Date(java.util.Date) ConceptName(org.openmrs.ConceptName) Encounter(org.openmrs.Encounter) ArrayNode(org.codehaus.jackson.node.ArrayNode) RegressionTestHelper(org.openmrs.module.htmlformentry.RegressionTestHelper) BaseModuleContextSensitiveTest(org.openmrs.test.BaseModuleContextSensitiveTest) Test(org.junit.Test)

Example 69 with ObjectNode

use of org.codehaus.jackson.node.ObjectNode in project activityinfo by bedatadriven.

the class CommandDeserializer method deserialize.

@Override
public Command deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    ObjectMapper mapper = (ObjectMapper) jp.getCodec();
    ObjectNode root = (ObjectNode) mapper.readTree(jp);
    String typeName = root.path("type").asText();
    if (Strings.isNullOrEmpty(typeName)) {
        throw new BadRpcRequest("Expected 'type' property on root object. You must specify a command type.");
    }
    Class commandClass;
    try {
        commandClass = lookupCommandClass(typeName);
    } catch (Exception e) {
        LOGGER.log(Level.SEVERE, "Failed to find command class for " + typeName, e);
        throw new BadRpcRequest("Invalid command type '%s'", typeName);
    }
    JsonNode command = root.path("command");
    if (!command.isObject()) {
        throw new BadRpcRequest("Expected 'command' root object property.");
    }
    try {
        return (Command) mapper.readValue(command, commandClass);
    } catch (UnrecognizedPropertyException e) {
        throw new BadRpcRequest("Unexpected property '%s'", formatPath(e.getPath()));
    }
}
Also used : ObjectNode(org.codehaus.jackson.node.ObjectNode) Command(org.activityinfo.legacy.shared.command.Command) UnrecognizedPropertyException(org.codehaus.jackson.map.exc.UnrecognizedPropertyException) JsonNode(org.codehaus.jackson.JsonNode) ObjectMapper(org.codehaus.jackson.map.ObjectMapper) UnrecognizedPropertyException(org.codehaus.jackson.map.exc.UnrecognizedPropertyException) IOException(java.io.IOException) JsonProcessingException(org.codehaus.jackson.JsonProcessingException) JsonMappingException(org.codehaus.jackson.map.JsonMappingException)

Example 70 with ObjectNode

use of org.codehaus.jackson.node.ObjectNode in project activityinfo by bedatadriven.

the class Placeholders method resolveObject.

private ObjectNode resolveObject(ObjectNode node) {
    ObjectNode result = factory.objectNode();
    Iterator<Map.Entry<String, JsonNode>> it = node.getFields();
    while (it.hasNext()) {
        Map.Entry<String, JsonNode> entry = it.next();
        result.put(entry.getKey(), resolve(entry.getValue()));
    }
    return result;
}
Also used : ObjectNode(org.codehaus.jackson.node.ObjectNode) JsonNode(org.codehaus.jackson.JsonNode) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) Map(java.util.Map)

Aggregations

ObjectNode (org.codehaus.jackson.node.ObjectNode)97 ObjectMapper (org.codehaus.jackson.map.ObjectMapper)29 ArrayNode (org.codehaus.jackson.node.ArrayNode)29 JsonNode (org.codehaus.jackson.JsonNode)22 GET (javax.ws.rs.GET)21 Path (javax.ws.rs.Path)18 Test (org.junit.Test)16 Produces (javax.ws.rs.Produces)12 Map (java.util.Map)11 ArrayList (java.util.ArrayList)10 HashMap (java.util.HashMap)9 IOException (java.io.IOException)8 StringWriter (java.io.StringWriter)5 JsonFactory (org.codehaus.jackson.JsonFactory)5 HelixDataAccessor (org.apache.helix.HelixDataAccessor)4 Span (org.apache.stanbol.enhancer.nlp.model.Span)4 DatasetImpl (org.eol.globi.service.DatasetImpl)4 Date (java.util.Date)3 TaskDriver (org.apache.helix.task.TaskDriver)3 WorkflowConfig (org.apache.helix.task.WorkflowConfig)3