Search in sources :

Example 1 with AdministrationService

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

the class ModuleFactory method runDiff.

/**
 * Execute the given sql diff section for the given module
 *
 * @param module the module being executed on
 * @param version the version of this sql diff
 * @param sql the actual sql statements to run (separated by semi colons)
 */
private static void runDiff(Module module, String version, String sql) {
    AdministrationService as = Context.getAdministrationService();
    String key = module.getModuleId() + ".database_version";
    GlobalProperty gp = as.getGlobalPropertyObject(key);
    boolean executeSQL = false;
    // check given version against current version
    if (gp != null && StringUtils.hasLength(gp.getPropertyValue())) {
        String currentDbVersion = gp.getPropertyValue();
        if (log.isDebugEnabled()) {
            log.debug("version:column " + version + ":" + currentDbVersion);
            log.debug("compare: " + ModuleUtil.compareVersion(version, currentDbVersion));
        }
        if (ModuleUtil.compareVersion(version, currentDbVersion) > 0) {
            executeSQL = true;
        }
    } else {
        executeSQL = true;
    }
    // version is greater than the currently installed version. execute this update.
    if (executeSQL) {
        try {
            Context.addProxyPrivilege(PrivilegeConstants.SQL_LEVEL_ACCESS);
            log.debug("Executing sql: " + sql);
            String[] sqlStatements = sql.split(";");
            for (String sqlStatement : sqlStatements) {
                if (sqlStatement.trim().length() > 0) {
                    as.executeSQL(sqlStatement, false);
                }
            }
        } finally {
            Context.removeProxyPrivilege(PrivilegeConstants.SQL_LEVEL_ACCESS);
        }
        // save the global property
        try {
            Context.addProxyPrivilege(PrivilegeConstants.MANAGE_GLOBAL_PROPERTIES);
            String description = "DO NOT MODIFY.  Current database version number for the " + module.getModuleId() + " module.";
            if (gp == null) {
                log.info("Global property " + key + " was not found. Creating one now.");
                gp = new GlobalProperty(key, version, description);
                as.saveGlobalProperty(gp);
            } else if (!gp.getPropertyValue().equals(version)) {
                log.info("Updating global property " + key + " to version: " + version);
                gp.setDescription(description);
                gp.setPropertyValue(version);
                as.saveGlobalProperty(gp);
            } else {
                log.error("Should not be here. GP property value and sqldiff version should not be equal");
            }
        } finally {
            Context.removeProxyPrivilege(PrivilegeConstants.MANAGE_GLOBAL_PROPERTIES);
        }
    }
}
Also used : AdministrationService(org.openmrs.api.AdministrationService) GlobalProperty(org.openmrs.GlobalProperty)

Example 2 with AdministrationService

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

the class ModuleFactory method saveGlobalProperty.

/**
 * Convenience method to save a global property with the given value. Proxy privileges are added
 * so that this can occur at startup.
 *
 * @param key the property for this global property
 * @param value the value for this global property
 * @param desc the description
 * @see AdministrationService#saveGlobalProperty(GlobalProperty)
 */
private static void saveGlobalProperty(String key, String value, String desc) {
    try {
        AdministrationService as = Context.getAdministrationService();
        GlobalProperty gp = as.getGlobalPropertyObject(key);
        if (gp == null) {
            gp = new GlobalProperty(key, value, desc);
        } else {
            gp.setPropertyValue(value);
        }
        as.saveGlobalProperty(gp);
    } catch (Exception e) {
        log.warn("Unable to save the global property", e);
    }
}
Also used : AdministrationService(org.openmrs.api.AdministrationService) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) CycleException(org.openmrs.util.CycleException) InputRequiredException(org.openmrs.util.InputRequiredException) GlobalProperty(org.openmrs.GlobalProperty)

Example 3 with AdministrationService

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

the class UserValidator method validate.

/**
 * Checks the form object for any inconsistencies/errors
 *
 * @see org.springframework.validation.Validator#validate(java.lang.Object,
 *      org.springframework.validation.Errors)
 * @should fail validation if retired and retireReason is null
 * @should fail validation if retired and retireReason is empty
 * @should fail validation if retired and retireReason is whitespace
 * @should pass validation if all required fields have proper values
 * @should fail validation if email as username enabled and email invalid
 * @should fail validation if email as username disabled and email provided
 * @should not throw NPE when user is null
 * @should pass validation if field lengths are correct
 * @should fail validation if field lengths are not correct
 */
@Override
public void validate(Object obj, Errors errors) {
    User user = (User) obj;
    if (user == null) {
        errors.reject("error.general");
    } else {
        if (user.getRetired() && StringUtils.isBlank(user.getRetireReason())) {
            errors.rejectValue("retireReason", "error.null");
        }
        if (user.getPerson() == null) {
            errors.rejectValue("person", "error.null");
        } else {
            // check that required person details are filled out
            Person person = user.getPerson();
            if (person.getGender() == null) {
                errors.rejectValue("person.gender", "error.null");
            }
            if (person.getDead() == null) {
                errors.rejectValue("person.dead", "error.null");
            }
            if (person.getVoided() == null) {
                errors.rejectValue("person.voided", "error.null");
            }
            if (person.getPersonName() == null || StringUtils.isEmpty(person.getPersonName().getFullName())) {
                errors.rejectValue("person", "Person.names.length");
            }
            errors.pushNestedPath("person");
            try {
                personValidator.validate(person, errors);
            } finally {
                errors.popNestedPath();
            }
        }
        AdministrationService as = Context.getAdministrationService();
        boolean emailAsUsername;
        try {
            Context.addProxyPrivilege(PrivilegeConstants.GET_GLOBAL_PROPERTIES);
            emailAsUsername = Boolean.parseBoolean(as.getGlobalProperty(OpenmrsConstants.GLOBAL_PROPERTY_USER_REQUIRE_EMAIL_AS_USERNAME, "false"));
        } finally {
            Context.removeProxyPrivilege(PrivilegeConstants.GET_GLOBAL_PROPERTIES);
        }
        if (emailAsUsername) {
            boolean isValidUserName = isUserNameAsEmailValid(user.getUsername());
            if (!isValidUserName) {
                errors.rejectValue("username", "error.username.email");
            }
        } else {
            boolean isValidUserName = isUserNameValid(user.getUsername());
            if (!isValidUserName) {
                errors.rejectValue("username", "error.username.pattern");
            }
        }
        ValidateUtil.validateFieldLengths(errors, obj.getClass(), "username", "systemId", "retireReason");
    }
}
Also used : User(org.openmrs.User) AdministrationService(org.openmrs.api.AdministrationService) Person(org.openmrs.Person)

Example 4 with AdministrationService

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

the class OpenmrsUtil method applyLogLevels.

/**
 * Set the org.openmrs log4j logger's level if global property log.level.openmrs (
 * OpenmrsConstants.GLOBAL_PROPERTY_LOG_LEVEL ) exists. Valid values for global property are
 * trace, debug, info, warn, error or fatal.
 */
public static void applyLogLevels() {
    AdministrationService adminService = Context.getAdministrationService();
    String logLevel = adminService.getGlobalProperty(OpenmrsConstants.GLOBAL_PROPERTY_LOG_LEVEL, "");
    String[] levels = logLevel.split(",");
    for (String level : levels) {
        String[] classAndLevel = level.split(":");
        if (classAndLevel.length == 1) {
            applyLogLevel(OpenmrsConstants.LOG_CLASS_DEFAULT, logLevel);
        } else {
            applyLogLevel(classAndLevel[0].trim(), classAndLevel[1].trim());
        }
    }
}
Also used : AdministrationService(org.openmrs.api.AdministrationService)

Example 5 with AdministrationService

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

the class OpenmrsUtil method validatePassword.

/**
 * Utility to check the validity of a password for a certain {@link User}. Passwords must be
 * non-null. Their required strength is configured via global properties:
 * <table summary="Configuration props">
 * <tr>
 * <th>Description</th>
 * <th>Property</th>
 * <th>Default Value</th>
 * </tr>
 * <tr>
 * <th>Require that it not match the {@link User}'s username or system id
 * <th>{@link OpenmrsConstants#GP_PASSWORD_CANNOT_MATCH_USERNAME_OR_SYSTEMID}</th>
 * <th>true</th>
 * </tr>
 * <tr>
 * <th>Require a minimum length
 * <th>{@link OpenmrsConstants#GP_PASSWORD_MINIMUM_LENGTH}</th>
 * <th>8</th>
 * </tr>
 * <tr>
 * <th>Require both an upper and lower case character
 * <th>{@link OpenmrsConstants#GP_PASSWORD_REQUIRES_UPPER_AND_LOWER_CASE}</th>
 * <th>true</th>
 * </tr>
 * <tr>
 * <th>Require at least one numeric character
 * <th>{@link OpenmrsConstants#GP_PASSWORD_REQUIRES_DIGIT}</th>
 * <th>true</th>
 * </tr>
 * <tr>
 * <th>Require at least one non-numeric character
 * <th>{@link OpenmrsConstants#GP_PASSWORD_REQUIRES_NON_DIGIT}</th>
 * <th>true</th>
 * </tr>
 * <tr>
 * <th>Require a match on the specified regular expression
 * <th>{@link OpenmrsConstants#GP_PASSWORD_CUSTOM_REGEX}</th>
 * <th>null</th>
 * </tr>
 * </table>
 *
 * @param username user name of the user with password to validated
 * @param password string that will be validated
 * @param systemId system id of the user with password to be validated
 * @throws PasswordException
 * @since 1.5
 * @should fail with short password by default
 * @should fail with short password if not allowed
 * @should pass with short password if allowed
 * @should fail with digit only password by default
 * @should fail with digit only password if not allowed
 * @should pass with digit only password if allowed
 * @should fail with char only password by default
 * @should fail with char only password if not allowed
 * @should pass with char only password if allowed
 * @should fail without both upper and lower case password by default
 * @should fail without both upper and lower case password if not allowed
 * @should pass without both upper and lower case password if allowed
 * @should fail with password equals to user name by default
 * @should fail with password equals to user name if not allowed
 * @should pass with password equals to user name if allowed
 * @should fail with password equals to system id by default
 * @should fail with password equals to system id if not allowed
 * @should pass with password equals to system id if allowed
 * @should fail with password not matching configured regex
 * @should pass with password matching configured regex
 * @should allow password to contain non alphanumeric characters
 * @should allow password to contain white spaces
 * @should still work without an open session
 */
public static void validatePassword(String username, String password, String systemId) throws PasswordException {
    // default values for all of the global properties
    String userGp = "true";
    String lengthGp = "8";
    String caseGp = "true";
    String digitGp = "true";
    String nonDigitGp = "true";
    String regexGp = null;
    AdministrationService svc = null;
    try {
        svc = Context.getAdministrationService();
    } catch (APIException apiEx) {
        // if a service isn't available, fail quietly and just do the
        // defaults
        log.debug("Unable to get global properties", apiEx);
    }
    if (svc != null && Context.isSessionOpen()) {
        // (the session won't be open here to allow for the unit test to
        // fake not having the admin service available)
        userGp = svc.getGlobalProperty(OpenmrsConstants.GP_PASSWORD_CANNOT_MATCH_USERNAME_OR_SYSTEMID, userGp);
        lengthGp = svc.getGlobalProperty(OpenmrsConstants.GP_PASSWORD_MINIMUM_LENGTH, lengthGp);
        caseGp = svc.getGlobalProperty(OpenmrsConstants.GP_PASSWORD_REQUIRES_UPPER_AND_LOWER_CASE, caseGp);
        digitGp = svc.getGlobalProperty(OpenmrsConstants.GP_PASSWORD_REQUIRES_DIGIT, digitGp);
        nonDigitGp = svc.getGlobalProperty(OpenmrsConstants.GP_PASSWORD_REQUIRES_NON_DIGIT, nonDigitGp);
        regexGp = svc.getGlobalProperty(OpenmrsConstants.GP_PASSWORD_CUSTOM_REGEX, regexGp);
    }
    if (password == null) {
        throw new WeakPasswordException();
    }
    if ("true".equals(userGp) && (password.equals(username) || password.equals(systemId))) {
        throw new WeakPasswordException();
    }
    if (StringUtils.isNotEmpty(lengthGp)) {
        try {
            int minLength = Integer.parseInt(lengthGp);
            if (password.length() < minLength) {
                throw new ShortPasswordException(getMessage("error.password.length", lengthGp));
            }
        } catch (NumberFormatException nfe) {
            log.warn("Error in global property <" + OpenmrsConstants.GP_PASSWORD_MINIMUM_LENGTH + "> must be an Integer");
        }
    }
    if ("true".equals(caseGp) && !containsUpperAndLowerCase(password)) {
        throw new InvalidCharactersPasswordException(getMessage("error.password.requireMixedCase"));
    }
    if ("true".equals(digitGp) && !containsDigit(password)) {
        throw new InvalidCharactersPasswordException(getMessage("error.password.requireNumber"));
    }
    if ("true".equals(nonDigitGp) && containsOnlyDigits(password)) {
        throw new InvalidCharactersPasswordException(getMessage("error.password.requireLetter"));
    }
    if (StringUtils.isNotEmpty(regexGp)) {
        try {
            Pattern pattern = Pattern.compile(regexGp);
            Matcher matcher = pattern.matcher(password);
            if (!matcher.matches()) {
                throw new InvalidCharactersPasswordException(getMessage("error.password.different"));
            }
        } catch (PatternSyntaxException pse) {
            log.warn("Invalid regex of " + regexGp + " defined in global property <" + OpenmrsConstants.GP_PASSWORD_CUSTOM_REGEX + ">.");
        }
    }
}
Also used : Pattern(java.util.regex.Pattern) ShortPasswordException(org.openmrs.api.ShortPasswordException) APIException(org.openmrs.api.APIException) AdministrationService(org.openmrs.api.AdministrationService) Matcher(java.util.regex.Matcher) InvalidCharactersPasswordException(org.openmrs.api.InvalidCharactersPasswordException) WeakPasswordException(org.openmrs.api.WeakPasswordException) PatternSyntaxException(java.util.regex.PatternSyntaxException)

Aggregations

AdministrationService (org.openmrs.api.AdministrationService)25 GlobalProperty (org.openmrs.GlobalProperty)8 ArrayList (java.util.ArrayList)5 User (org.openmrs.User)4 Test (org.junit.Test)3 IOException (java.io.IOException)2 Date (java.util.Date)2 HashMap (java.util.HashMap)2 List (java.util.List)2 EncounterType (org.openmrs.EncounterType)2 APIException (org.openmrs.api.APIException)2 BaseContextSensitiveTest (org.openmrs.test.BaseContextSensitiveTest)2 BindException (org.springframework.validation.BindException)2 Errors (org.springframework.validation.Errors)2 File (java.io.File)1 MalformedURLException (java.net.MalformedURLException)1 HashSet (java.util.HashSet)1 LinkedHashMap (java.util.LinkedHashMap)1 Map (java.util.Map)1 Properties (java.util.Properties)1