Search in sources :

Example 81 with APIException

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

the class Security method encrypt.

/**
 * encrypt text to a string with specific initVector and secretKey; rarely used except in
 * testing and where specifically necessary
 *
 * @see #encrypt(String)
 *
 * @param text string to be encrypted
 * @param initVector custom init vector byte array
 * @param secretKey custom secret key byte array
 * @return encrypted text
 * @since 1.9
 */
public static String encrypt(String text, byte[] initVector, byte[] secretKey) {
    IvParameterSpec initVectorSpec = new IvParameterSpec(initVector);
    SecretKeySpec secret = new SecretKeySpec(secretKey, OpenmrsConstants.ENCRYPTION_KEY_SPEC);
    byte[] encrypted;
    String result;
    try {
        Cipher cipher = Cipher.getInstance(OpenmrsConstants.ENCRYPTION_CIPHER_CONFIGURATION);
        cipher.init(Cipher.ENCRYPT_MODE, secret, initVectorSpec);
        encrypted = cipher.doFinal(text.getBytes(StandardCharsets.UTF_8));
        result = new String(Base64.getEncoder().encode(encrypted), StandardCharsets.UTF_8);
    } catch (GeneralSecurityException e) {
        throw new APIException("could.not.encrypt.text", null, e);
    }
    return result;
}
Also used : APIException(org.openmrs.api.APIException) SecretKeySpec(javax.crypto.spec.SecretKeySpec) GeneralSecurityException(java.security.GeneralSecurityException) IvParameterSpec(javax.crypto.spec.IvParameterSpec) Cipher(javax.crypto.Cipher)

Example 82 with APIException

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

the class HibernateAdministrationDAO method getMaximumPropertyLength.

@Override
public int getMaximumPropertyLength(Class<? extends OpenmrsObject> aClass, String fieldName) {
    if (configuration == null) {
        HibernateSessionFactoryBean sessionFactoryBean = (HibernateSessionFactoryBean) applicationContext.getBean("&sessionFactory");
        configuration = sessionFactoryBean.getConfiguration();
    }
    PersistentClass persistentClass = configuration.getClassMapping(aClass.getName().split("_")[0]);
    if (persistentClass == null) {
        throw new APIException("Couldn't find a class in the hibernate configuration named: " + aClass.getName());
    } else {
        int fieldLength;
        try {
            fieldLength = ((Column) persistentClass.getProperty(fieldName).getColumnIterator().next()).getLength();
        } catch (Exception e) {
            log.debug("Could not determine maximum length", e);
            return -1;
        }
        return fieldLength;
    }
}
Also used : APIException(org.openmrs.api.APIException) APIException(org.openmrs.api.APIException) DAOException(org.openmrs.api.db.DAOException) BeansException(org.springframework.beans.BeansException) PersistentClass(org.hibernate.mapping.PersistentClass)

Example 83 with APIException

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

the class HibernateConceptDAO method getConceptReferenceTermByName.

/**
 * @see org.openmrs.api.db.ConceptDAO#getConceptReferenceTermByName(java.lang.String,
 *      org.openmrs.ConceptSource)
 */
@SuppressWarnings("rawtypes")
@Override
public ConceptReferenceTerm getConceptReferenceTermByName(String name, ConceptSource conceptSource) throws DAOException {
    Criteria criteria = sessionFactory.getCurrentSession().createCriteria(ConceptReferenceTerm.class);
    criteria.add(Restrictions.ilike("name", name, MatchMode.EXACT));
    criteria.add(Restrictions.eq("conceptSource", conceptSource));
    List terms = criteria.list();
    if (terms.isEmpty()) {
        return null;
    } else if (terms.size() > 1) {
        throw new APIException("ConceptReferenceTerm.foundMultipleTermsWithNameInSource", new Object[] { name, conceptSource.getName() });
    }
    return (ConceptReferenceTerm) terms.get(0);
}
Also used : APIException(org.openmrs.api.APIException) List(java.util.List) ArrayList(java.util.ArrayList) OpenmrsObject(org.openmrs.OpenmrsObject) Criteria(org.hibernate.Criteria) ConceptReferenceTerm(org.openmrs.ConceptReferenceTerm)

Example 84 with APIException

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

the class ExistingOrNewVisitAssignmentHandler method loadVisitType.

/**
 * Get the visit type corresponding to an encounter type by reading valid mappings
 * from a global property
 * @param encounterType
 * @return
 * @throws APIException
 */
private static VisitType loadVisitType(EncounterType encounterType) throws APIException {
    String value = Context.getAdministrationService().getGlobalPropertyValue(OpenmrsConstants.GP_ENCOUNTER_TYPE_TO_VISIT_TYPE_MAPPING, "");
    // or encounterTypeUuid:visitTypeUuid o a mixture of uuids and id
    if (!StringUtils.isBlank(value)) {
        VisitService visitService = Context.getVisitService();
        String targetEncounterTypeId = encounterType.getId().toString();
        String[] mappings = value.split(",");
        for (String mapping : mappings) {
            int index = mapping.indexOf(':');
            if (index > 0) {
                String encounterTypeIdOrUuid = mapping.substring(0, index).trim();
                if (targetEncounterTypeId.equals(encounterTypeIdOrUuid) || encounterType.getUuid().equals(encounterTypeIdOrUuid)) {
                    String visitTypeIdOrUuid = mapping.substring(index + 1).trim();
                    VisitType visitType;
                    if (StringUtils.isNumeric(visitTypeIdOrUuid)) {
                        visitType = visitService.getVisitType(Integer.parseInt(visitTypeIdOrUuid));
                    } else {
                        visitType = visitService.getVisitTypeByUuid(visitTypeIdOrUuid);
                    }
                    if (visitType != null) {
                        return visitType;
                    }
                }
            }
        }
        // Reaching here means this encounter type is not in the user's mapping.
        throw new APIException("GlobalProperty.error.loadVisitType", new Object[] { encounterType.getName() });
    }
    return Context.getVisitService().getAllVisitTypes().get(0);
}
Also used : APIException(org.openmrs.api.APIException) VisitService(org.openmrs.api.VisitService) VisitType(org.openmrs.VisitType)

Example 85 with APIException

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

the class OpenmrsObjectSaveHandler method handle.

/**
 * This sets the uuid property on the given OpenmrsObject if it is non-null.
 *
 * @see org.openmrs.api.handler.RequiredDataHandler#handle(org.openmrs.OpenmrsObject,
 *      org.openmrs.User, java.util.Date, java.lang.String)
 * @should set empty string properties to null
 * @should not set empty string properties to null for AllowEmptyStrings annotation
 * @should not trim empty strings for AllowLeadingOrTrailingWhitespace annotation
 * @should trim strings without AllowLeadingOrTrailingWhitespace annotation
 * @should trim empty strings for AllowEmptyStrings annotation
 */
@Override
public void handle(OpenmrsObject openmrsObject, User creator, Date dateCreated, String reason) {
    if (openmrsObject.getUuid() == null) {
        openmrsObject.setUuid(UUID.randomUUID().toString());
    }
    // Set all empty string properties, that do not have the AllowEmptyStrings annotation, to null.
    // And also trim leading and trailing white space for properties that do not have the
    // AllowLeadingOrTrailingWhitespace annotation.
    PropertyDescriptor[] properties = PropertyUtils.getPropertyDescriptors(openmrsObject);
    for (PropertyDescriptor property : properties) {
        if (property.getPropertyType() == null) {
            continue;
        }
        // don't have a setter (e.g. Patient.familyName)
        if (property.getWriteMethod() == null || property.getReadMethod() == null) {
            continue;
        }
        // Ignore properties that have a deprecated getter or setter
        if (property.getWriteMethod().getAnnotation(Deprecated.class) != null || property.getReadMethod().getAnnotation(Deprecated.class) != null) {
            continue;
        }
        // TODO We shouldn't be doing this for all immutable types and fields
        if (openmrsObject instanceof Obs || !property.getPropertyType().equals(String.class)) {
            continue;
        }
        try {
            Object value = PropertyUtils.getProperty(openmrsObject, property.getName());
            if (value == null) {
                continue;
            }
            Object valueBeforeTrim = value;
            if (property.getWriteMethod().getAnnotation(AllowLeadingOrTrailingWhitespace.class) == null) {
                value = ((String) value).trim();
                // If we have actually trimmed any space, set the trimmed value.
                if (!valueBeforeTrim.equals(value)) {
                    PropertyUtils.setProperty(openmrsObject, property.getName(), value);
                }
            }
            // Check if user is interested in setting empty strings to null
            if (property.getWriteMethod().getAnnotation(AllowEmptyStrings.class) != null) {
                continue;
            }
            if ("".equals(value) && !(openmrsObject instanceof Voidable && ((Voidable) openmrsObject).getVoided())) {
                // Set to null only if object is not already voided
                PropertyUtils.setProperty(openmrsObject, property.getName(), null);
            }
        } catch (UnsupportedOperationException ex) {
            // there is no need to log this. These should be (mostly) silently skipped over
            if (log.isInfoEnabled()) {
                log.info("The property " + property.getName() + " is no longer supported and should be ignored.", ex);
            }
        } catch (InvocationTargetException ex) {
            if (log.isWarnEnabled()) {
                log.warn("Failed to access property " + property.getName() + "; accessor threw exception.", ex);
            }
        } catch (Exception ex) {
            throw new APIException("failed.change.property.value", new Object[] { property.getName() }, ex);
        }
    }
}
Also used : Obs(org.openmrs.Obs) APIException(org.openmrs.api.APIException) PropertyDescriptor(java.beans.PropertyDescriptor) AllowLeadingOrTrailingWhitespace(org.openmrs.annotation.AllowLeadingOrTrailingWhitespace) OpenmrsObject(org.openmrs.OpenmrsObject) Voidable(org.openmrs.Voidable) InvocationTargetException(java.lang.reflect.InvocationTargetException) APIException(org.openmrs.api.APIException) InvocationTargetException(java.lang.reflect.InvocationTargetException) AllowEmptyStrings(org.openmrs.annotation.AllowEmptyStrings)

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