Search in sources :

Example 51 with APIException

use of org.openmrs.api.APIException in project openmrs-core by openmrs.

the class PatientServiceImpl method saveCauseOfDeathObs.

/**
 * @see org.openmrs.api.PatientService#saveCauseOfDeathObs(org.openmrs.Patient, java.util.Date,
 *      org.openmrs.Concept, java.lang.String)
 */
@Override
public void saveCauseOfDeathObs(Patient patient, Date deathDate, Concept cause, String otherReason) throws APIException {
    if (patient == null) {
        throw new APIException("Patient.null", (Object[]) null);
    }
    if (deathDate == null) {
        throw new APIException("Patient.death.date.null", (Object[]) null);
    }
    if (cause == null) {
        throw new APIException("Patient.cause.null", (Object[]) null);
    }
    if (!patient.getDead()) {
        patient.setDead(true);
        patient.setDeathDate(deathDate);
        patient.setCauseOfDeath(cause);
    }
    log.debug("Patient is dead, so let's make sure there's an Obs for it");
    // need to make sure there is an Obs that represents the patient's
    // cause of death, if applicable
    String codProp = Context.getAdministrationService().getGlobalProperty("concept.causeOfDeath");
    Concept causeOfDeath = Context.getConceptService().getConcept(codProp);
    if (causeOfDeath != null) {
        List<Obs> obssDeath = Context.getObsService().getObservationsByPersonAndConcept(patient, causeOfDeath);
        if (obssDeath != null) {
            if (obssDeath.size() > 1) {
                log.error("Multiple causes of death (" + obssDeath.size() + ")?  Shouldn't be...");
            } else {
                Obs obsDeath;
                if (obssDeath.size() == 1) {
                    // already has a cause of death - let's edit it.
                    log.debug("Already has a cause of death, so changing it");
                    obsDeath = obssDeath.iterator().next();
                } else {
                    // no cause of death obs yet, so let's make one
                    log.debug("No cause of death yet, let's create one.");
                    obsDeath = new Obs();
                    obsDeath.setPerson(patient);
                    obsDeath.setConcept(causeOfDeath);
                    Location location = Context.getLocationService().getDefaultLocation();
                    if (location != null) {
                        obsDeath.setLocation(location);
                    } else {
                        log.error("Could not find a suitable location for which to create this new Obs");
                    }
                }
                // put the right concept and (maybe) text in this obs
                Concept currCause = patient.getCauseOfDeath();
                if (currCause == null) {
                    // set to NONE
                    log.debug("Current cause is null, attempting to set to NONE");
                    String noneConcept = Context.getAdministrationService().getGlobalProperty("concept.none");
                    currCause = Context.getConceptService().getConcept(noneConcept);
                }
                if (currCause != null) {
                    log.debug("Current cause is not null, setting to value_coded");
                    obsDeath.setValueCoded(currCause);
                    // ABKTODO: presume current locale?
                    obsDeath.setValueCodedName(currCause.getName());
                    Date dateDeath = patient.getDeathDate();
                    if (dateDeath == null) {
                        dateDeath = new Date();
                    }
                    obsDeath.setObsDatetime(dateDeath);
                    // check if this is an "other" concept - if so, then
                    // we need to add value_text
                    String otherConcept = Context.getAdministrationService().getGlobalProperty("concept.otherNonCoded");
                    Concept conceptOther = Context.getConceptService().getConcept(otherConcept);
                    if (conceptOther != null) {
                        if (conceptOther.equals(currCause)) {
                            // seems like this is an other concept -
                            // let's try to get the "other" field info
                            log.debug("Setting value_text as " + otherReason);
                            obsDeath.setValueText(otherReason);
                        } else {
                            log.debug("New concept is NOT the OTHER concept, so setting to blank");
                            obsDeath.setValueText("");
                        }
                    } else {
                        log.debug("Don't seem to know about an OTHER concept, so deleting value_text");
                        obsDeath.setValueText("");
                    }
                    Context.getObsService().saveObs(obsDeath, "updated by PatientService.saveCauseOfDeathObs");
                } else {
                    log.debug("Current cause is still null - aborting mission");
                }
            }
        }
    } else {
        log.debug("Cause of death is null - should not have gotten here without throwing an error on the form.");
    }
}
Also used : Concept(org.openmrs.Concept) Obs(org.openmrs.Obs) APIException(org.openmrs.api.APIException) Date(java.util.Date) Location(org.openmrs.Location)

Example 52 with APIException

use of org.openmrs.api.APIException in project openmrs-core by openmrs.

the class PersonServiceImpl method retireRelationshipType.

/**
 * @see org.openmrs.api.PersonService#retireRelationshipType(org.openmrs.RelationshipType,
 *      java.lang.String)
 */
@Override
public RelationshipType retireRelationshipType(RelationshipType type, String retiredReason) throws APIException {
    if (retiredReason == null || retiredReason.length() < 1) {
        throw new APIException("Relationship.retiring.reason.required", (Object[]) null);
    }
    type.setRetired(true);
    type.setRetiredBy(Context.getAuthenticatedUser());
    type.setDateRetired(new Date());
    type.setRetireReason(retiredReason);
    return Context.getPersonService().saveRelationshipType(type);
}
Also used : APIException(org.openmrs.api.APIException) Date(java.util.Date)

Example 53 with APIException

use of org.openmrs.api.APIException in project openmrs-core by openmrs.

the class HL7ServiceImpl method writeHL7InArchiveToFileSystem.

/**
 * writes a given hl7 archive to the file system
 *
 * @param hl7InArchive the hl7 archive to write to the file system
 */
private URI writeHL7InArchiveToFileSystem(HL7InArchive hl7InArchive) throws APIException {
    PrintWriter writer = null;
    File destinationDir = HL7Util.getHl7ArchivesDirectory();
    try {
        // number formatter used to format month and day with zero padding
        DecimalFormat df = new DecimalFormat("00");
        // write the archive to a separate file while grouping them according to
        // the year, month and date of month when they were stored in the archives table
        Calendar calendar = Calendar.getInstance(Context.getLocale());
        calendar.setTime(hl7InArchive.getDateCreated());
        // resolve the year folder from the date of creation of the archive
        File yearDir = new File(destinationDir, Integer.toString(calendar.get(Calendar.YEAR)));
        if (!yearDir.isDirectory()) {
            yearDir.mkdirs();
        }
        // resolve the appropriate month folder
        File monthDir = new File(yearDir, df.format(calendar.get(Calendar.MONTH) + 1));
        if (!monthDir.isDirectory()) {
            monthDir.mkdirs();
        }
        // resolve the appropriate day of month folder
        File dayDir = new File(monthDir, df.format(calendar.get(Calendar.DAY_OF_MONTH)));
        if (!dayDir.isDirectory()) {
            dayDir.mkdirs();
        }
        // use the uuid, source id and source key(if present) to generate the file name
        File fileToWriteTo = new File(dayDir, hl7InArchive.getUuid() + (StringUtils.isBlank(hl7InArchive.getHL7SourceKey()) ? "" : "_" + hl7InArchive.getHL7SourceKey()) + ".txt");
        // write the hl7 data to the file
        writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(fileToWriteTo), StandardCharsets.UTF_8));
        writer.write(hl7InArchive.getHL7Data());
        // check if there was an error while writing to the current file
        if (writer.checkError()) {
            log.warn("An Error occured while writing hl7 archive with id '" + hl7InArchive.getHL7InArchiveId() + "' to the file system");
            throw new APIException("Hl7Service.write.no.error", (Object[]) null);
        }
        // hand back the URI for the file
        return fileToWriteTo.toURI();
    } catch (FileNotFoundException e) {
        log.warn("Failed to write hl7 archive with id '" + hl7InArchive.getHL7InArchiveId() + "' to the file system ", e);
        throw new APIException("Hl7Service.write.error", null, e);
    } finally {
        if (writer != null) {
            writer.close();
        }
    }
}
Also used : APIException(org.openmrs.api.APIException) DecimalFormat(java.text.DecimalFormat) Calendar(java.util.Calendar) FileOutputStream(java.io.FileOutputStream) FileNotFoundException(java.io.FileNotFoundException) OutputStreamWriter(java.io.OutputStreamWriter) File(java.io.File) PrintWriter(java.io.PrintWriter)

Example 54 with APIException

use of org.openmrs.api.APIException in project openmrs-core by openmrs.

the class NameTemplate method format.

public String format(PersonName personName) {
    List<String> personNameLines = new ArrayList<>();
    List<List<Map<String, String>>> lines = getLines();
    String layoutToken = getLayoutToken();
    try {
        for (List<Map<String, String>> line : lines) {
            StringBuilder nameLine = new StringBuilder();
            Boolean hasToken = false;
            for (Map<String, String> lineToken : line) {
                if (lineToken.get("isToken").equals(layoutToken)) {
                    String tokenValue = BeanUtils.getProperty(personName, lineToken.get("codeName"));
                    if (StringUtils.isNotBlank(tokenValue)) {
                        hasToken = true;
                        nameLine.append(tokenValue);
                    }
                } else {
                    nameLine.append(lineToken.get("displayText"));
                }
            }
            // only display a line if there's at least one token within it we've been able to resolve
            String nameLineString = nameLine.toString();
            if (StringUtils.isNotBlank(nameLineString) && hasToken) {
                personNameLines.add(nameLineString);
            }
        }
        // bit of hack, but we ignore the "line-by-line" format and just delimit a "line" with blank space
        return StringUtils.join(personNameLines, " ");
    } catch (Exception e) {
        throw new APIException("Unable to format personName " + personName.getId() + " using name template", e);
    }
}
Also used : APIException(org.openmrs.api.APIException) ArrayList(java.util.ArrayList) List(java.util.List) ArrayList(java.util.ArrayList) Map(java.util.Map) APIException(org.openmrs.api.APIException)

Example 55 with APIException

use of org.openmrs.api.APIException in project openmrs-core by openmrs.

the class ConceptServiceImpl method convertBooleanConceptToCoded.

/**
 * @see org.openmrs.api.ConceptService#convertBooleanConceptToCoded(org.openmrs.Concept)
 */
@Override
public void convertBooleanConceptToCoded(Concept conceptToChange) throws APIException {
    if (conceptToChange != null) {
        if (!conceptToChange.getDatatype().isBoolean()) {
            throw new APIException("Concept.datatype.invalid", (Object[]) null);
        }
        conceptToChange.setDatatype(getConceptDatatypeByName("Coded"));
        conceptToChange.addAnswer(new ConceptAnswer(getTrueConcept()));
        conceptToChange.addAnswer(new ConceptAnswer(getFalseConcept()));
        Context.getConceptService().saveConcept(conceptToChange);
    }
}
Also used : APIException(org.openmrs.api.APIException) ConceptAnswer(org.openmrs.ConceptAnswer)

Aggregations

APIException (org.openmrs.api.APIException)86 Date (java.util.Date)11 IOException (java.io.IOException)10 ArrayList (java.util.ArrayList)10 File (java.io.File)9 Obs (org.openmrs.Obs)7 List (java.util.List)6 Map (java.util.Map)6 User (org.openmrs.User)6 FileInputStream (java.io.FileInputStream)5 FileOutputStream (java.io.FileOutputStream)5 Concept (org.openmrs.Concept)5 OpenmrsObject (org.openmrs.OpenmrsObject)5 InputStream (java.io.InputStream)4 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)4 Order (org.openmrs.Order)4 FileNotFoundException (java.io.FileNotFoundException)3 OutputStreamWriter (java.io.OutputStreamWriter)3 MessageDigest (java.security.MessageDigest)3 HashMap (java.util.HashMap)3