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;
}
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;
}
}
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);
}
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);
}
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);
}
}
}
Aggregations