Search in sources :

Example 61 with User

use of org.openmrs.User in project openmrs-core by openmrs.

the class PatientDataVoidHandlerTest method handle_shouldVoidTheOrdersEncountersAndObservationsAssociatedWithThePatient.

/**
 * @see PatientDataVoidHandler#handle(Patient,User,Date,String)
 */
@Test
public void handle_shouldVoidTheOrdersEncountersAndObservationsAssociatedWithThePatient() {
    Patient patient = Context.getPatientService().getPatient(7);
    Assert.assertFalse(patient.getVoided());
    List<Encounter> encounters = Context.getEncounterService().getEncountersByPatient(patient);
    List<Obs> observations = Context.getObsService().getObservationsByPerson(patient);
    List<Order> orders = Context.getOrderService().getAllOrdersByPatient(patient);
    // we should have some unvoided encounters, obs and orders for the test to be concrete
    assertTrue(CollectionUtils.isNotEmpty(encounters));
    assertTrue(CollectionUtils.isNotEmpty(observations));
    assertTrue(CollectionUtils.isNotEmpty(orders));
    // check that fields to be set by the handler are initially null
    for (Encounter encounter : encounters) {
        assertNull(encounter.getDateVoided());
        assertNull(encounter.getVoidedBy());
        assertNull(encounter.getVoidReason());
    }
    for (Obs obs : observations) {
        assertNull(obs.getDateVoided());
        assertNull(obs.getVoidedBy());
        assertNull(obs.getVoidReason());
    }
    for (Order order : orders) {
        assertNull(order.getDateVoided());
        assertNull(order.getVoidedBy());
        assertNull(order.getVoidReason());
    }
    new PatientDataVoidHandler().handle(patient, new User(1), new Date(), "voidReason");
    // all encounters void related fields should have been set
    for (Encounter encounter : encounters) {
        assertTrue(encounter.getVoided());
        assertNotNull(encounter.getDateVoided());
        assertNotNull(encounter.getVoidedBy());
        assertNotNull(encounter.getVoidReason());
    }
    // all obs void related fields should have been set
    for (Obs obs : observations) {
        assertTrue(obs.getVoided());
        assertNotNull(obs.getDateVoided());
        assertNotNull(obs.getVoidedBy());
        assertNotNull(obs.getVoidReason());
    }
    // all order void related fields should have been set
    for (Order order : orders) {
        assertTrue(order.getVoided());
        assertNotNull(order.getDateVoided());
        assertNotNull(order.getVoidedBy());
        assertNotNull(order.getVoidReason());
    }
    // refresh the lists and check that all encounters, obs and orders were voided
    encounters = Context.getEncounterService().getEncountersByPatient(patient);
    observations = Context.getObsService().getObservationsByPerson(patient);
    assertTrue(CollectionUtils.isEmpty(encounters));
    assertTrue(CollectionUtils.isEmpty(observations));
}
Also used : Order(org.openmrs.Order) Obs(org.openmrs.Obs) User(org.openmrs.User) Patient(org.openmrs.Patient) Encounter(org.openmrs.Encounter) Date(java.util.Date) DateUtils.parseDate(org.apache.commons.lang3.time.DateUtils.parseDate) Test(org.junit.Test) BaseContextSensitiveTest(org.openmrs.test.BaseContextSensitiveTest)

Example 62 with User

use of org.openmrs.User in project openmrs-core by openmrs.

the class OpenmrsFilter method doFilterInternal.

/**
 * This method is called for every request for a page/image/javascript file/etc The main point
 * of this is to make sure the user's current userContext is on the session and on the current
 * thread
 *
 * @see org.springframework.web.filter.OncePerRequestFilter#doFilterInternal(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse, javax.servlet.FilterChain)
 */
@Override
protected void doFilterInternal(HttpServletRequest httpRequest, HttpServletResponse httpResponse, FilterChain chain) throws ServletException, IOException {
    HttpSession httpSession = httpRequest.getSession();
    // used by htmlInclude tag
    httpRequest.setAttribute(WebConstants.INIT_REQ_UNIQUE_ID, String.valueOf(System.currentTimeMillis()));
    if (log.isDebugEnabled()) {
        log.debug("requestURI " + httpRequest.getRequestURI());
        log.debug("requestURL " + httpRequest.getRequestURL());
        log.debug("request path info " + httpRequest.getPathInfo());
    }
    // User context is created if it doesn't already exist and added to the session
    // note: this usercontext storage logic is copied to webinf/view/uncaughtexception.jsp to
    // prevent stack traces being shown to non-authenticated users
    UserContext userContext = (UserContext) httpSession.getAttribute(WebConstants.OPENMRS_USER_CONTEXT_HTTPSESSION_ATTR);
    // default the session username attribute to anonymous
    httpSession.setAttribute("username", "-anonymous user-");
    // and set it onto the session
    if (userContext == null) {
        userContext = new UserContext();
        httpSession.setAttribute(WebConstants.OPENMRS_USER_CONTEXT_HTTPSESSION_ATTR, userContext);
        if (log.isDebugEnabled()) {
            log.debug("Just set user context " + userContext + " as attribute on session");
        }
    } else {
        // set username as attribute on session so parent servlet container
        // can identify sessions easier
        User user = userContext.getAuthenticatedUser();
        if (user != null) {
            httpSession.setAttribute("username", user.getUsername());
        }
    }
    // set the locale on the session (for the servlet container as well)
    httpSession.setAttribute("locale", userContext.getLocale());
    // Add the user context to the current thread
    Context.setUserContext(userContext);
    Thread.currentThread().setContextClassLoader(OpenmrsClassLoader.getInstance());
    log.debug("before chain.Filter");
    // continue the filter chain (going on to spring, authorization, etc)
    try {
        chain.doFilter(httpRequest, httpResponse);
    } finally {
        Context.clearUserContext();
    }
    log.debug("after chain.doFilter");
}
Also used : User(org.openmrs.User) HttpSession(javax.servlet.http.HttpSession) UserContext(org.openmrs.api.context.UserContext)

Example 63 with User

use of org.openmrs.User in project openmrs-core by openmrs.

the class LoggingAdvice method invoke.

/**
 * This method prints out debug statements for getters and info statements for everything else
 * ("setters"). If debugging is turned on, execution time for each method is printed as well.
 * This method is called for every method in the Class/Service that it is wrapped around. This
 * method should be fairly quick and light.
 *
 * @see org.aopalliance.intercept.MethodInterceptor#invoke(org.aopalliance.intercept.MethodInvocation)
 */
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
    Method method = invocation.getMethod();
    String name = method.getName();
    // decide what type of logging we're doing with the current method and the loglevel
    boolean isSetterTypeOfMethod = OpenmrsUtil.stringStartsWith(name, SETTER_METHOD_PREFIXES);
    boolean logGetter = !isSetterTypeOfMethod && log.isDebugEnabled();
    boolean logSetter = isSetterTypeOfMethod && log.isInfoEnabled();
    // used for the execution time calculations
    long startTime = System.currentTimeMillis();
    // check if this method has the logging annotation on it
    Logging loggingAnnotation = null;
    if (logGetter || logSetter) {
        loggingAnnotation = method.getAnnotation(Logging.class);
        if (loggingAnnotation != null && loggingAnnotation.ignore()) {
            logGetter = false;
            logSetter = false;
        }
    }
    if (logGetter || logSetter) {
        StringBuilder output = new StringBuilder();
        output.append("In method ").append(method.getDeclaringClass().getSimpleName()).append(".").append(name);
        // print the argument values unless we're ignoring all
        if (loggingAnnotation == null || !loggingAnnotation.ignoreAllArgumentValues()) {
            int x;
            Class<?>[] types = method.getParameterTypes();
            Object[] values = invocation.getArguments();
            // change the annotation array of indexes to a list of indexes to ignore
            List<Integer> argsToIgnore = new ArrayList<>();
            if (loggingAnnotation != null && loggingAnnotation.ignoredArgumentIndexes().length > 0) {
                for (int argIndexToIgnore : loggingAnnotation.ignoredArgumentIndexes()) {
                    argsToIgnore.add(argIndexToIgnore);
                }
            }
            // loop over and print out each argument value
            output.append(". Arguments: ");
            for (x = 0; x < types.length; x++) {
                output.append(types[x].getSimpleName()).append("=");
                // if there is an annotation to skip this, print out a bogus string.
                if (argsToIgnore.contains(x)) {
                    output.append("<Arg value ignored>");
                } else {
                    output.append(values[x]);
                }
                output.append(", ");
            }
        }
        // print the string as either debug or info
        if (logGetter) {
            log.debug(output.toString());
        } else if (logSetter) {
            log.info(output.toString());
        }
    }
    try {
        // do the actual method we're wrapped around
        return invocation.proceed();
    } catch (Exception e) {
        if (logGetter || logSetter) {
            String username;
            User user = Context.getAuthenticatedUser();
            if (user == null) {
                username = "Guest (Not logged in)";
            } else {
                username = user.getUsername();
                if (username == null || username.length() == 0) {
                    username = user.getSystemId();
                }
            }
            log.debug(String.format("An error occurred while executing this method.%nCurrent user: %s%nError message: %s", username, e.getMessage()), e);
        }
        throw e;
    } finally {
        if (logGetter || logSetter) {
            StringBuilder output = new StringBuilder();
            output.append("Exiting method ").append(name);
            // only append execution time info if we're in debug mode
            if (log.isDebugEnabled()) {
                output.append(". execution time: ").append(System.currentTimeMillis() - startTime).append(" ms");
            }
            // print the string as either debug or info
            if (logGetter) {
                log.debug(output.toString());
            } else if (logSetter) {
                log.info(output.toString());
            }
        }
    }
}
Also used : Logging(org.openmrs.annotation.Logging) User(org.openmrs.User) ArrayList(java.util.ArrayList) Method(java.lang.reflect.Method)

Example 64 with User

use of org.openmrs.User in project openmrs-core by openmrs.

the class RequiredDataAdvice method before.

/**
 * @see org.springframework.aop.MethodBeforeAdvice#before(java.lang.reflect.Method,
 *      java.lang.Object[], java.lang.Object)
 * @should not fail on update method with no arguments
 */
@Override
@SuppressWarnings("unchecked")
public void before(Method method, Object[] args, Object target) throws Throwable {
    String methodName = method.getName();
    // skip out early if there are no arguments
    if (args == null || args.length == 0) {
        return;
    }
    Object mainArgument = args[0];
    // fail early on a null parameter
    if (mainArgument == null) {
        return;
    }
    // not updating the primary argument. eg: ConceptService.updateConceptWord(Concept)
    if (methodName.startsWith("save") || methodName.startsWith("create")) {
        // if the first argument is an OpenmrsObject, handle it now
        Reflect reflect = new Reflect(OpenmrsObject.class);
        if (reflect.isSuperClass(mainArgument)) {
            // fail early if the method name is not like saveXyz(Xyz)
            if (!methodNameEndsWithClassName(method, mainArgument.getClass())) {
                return;
            }
            // if a second argument exists, pass that to the save handler as well
            // (with current code, it means we're either in an obs save or a user save)
            String other = null;
            if (args.length > 1 && args[1] instanceof String) {
                other = (String) args[1];
            }
            ValidateUtil.validate(mainArgument);
            recursivelyHandle(SaveHandler.class, (OpenmrsObject) mainArgument, other);
        } else // if the first argument is a list of openmrs objects, handle them all now
        if (Reflect.isCollection(mainArgument) && isOpenmrsObjectCollection(mainArgument)) {
            // ideally we would fail early if the method name is not like savePluralOfXyz(Collection<Xyz>)
            // but this only occurs once in the API (AdministrationService.saveGlobalProperties
            // so it is not worth handling this case
            // if a second argument exists, pass that to the save handler as well
            // (with current code, it means we're either in an obs save or a user save)
            String other = null;
            if (args.length > 1) {
                other = (String) args[1];
            }
            Collection<OpenmrsObject> openmrsObjects = (Collection<OpenmrsObject>) mainArgument;
            for (OpenmrsObject object : openmrsObjects) {
                ValidateUtil.validate(mainArgument);
                recursivelyHandle(SaveHandler.class, object, other);
            }
        }
    } else {
        // with Patients or Concepts as the first argument
        if (!methodNameEndsWithClassName(method, mainArgument.getClass())) {
            return;
        }
        if (methodName.startsWith("void")) {
            Voidable voidable = (Voidable) args[0];
            Date dateVoided = voidable.getDateVoided() == null ? new Date() : voidable.getDateVoided();
            String voidReason = (String) args[1];
            recursivelyHandle(VoidHandler.class, voidable, Context.getAuthenticatedUser(), dateVoided, voidReason, null);
        } else if (methodName.startsWith("unvoid")) {
            Voidable voidable = (Voidable) args[0];
            Date originalDateVoided = voidable.getDateVoided();
            User originalVoidingUser = voidable.getVoidedBy();
            recursivelyHandle(UnvoidHandler.class, voidable, originalVoidingUser, originalDateVoided, null, null);
        } else if (methodName.startsWith("retire")) {
            Retireable retirable = (Retireable) args[0];
            String retireReason = (String) args[1];
            recursivelyHandle(RetireHandler.class, retirable, retireReason);
        } else if (methodName.startsWith("unretire")) {
            Retireable retirable = (Retireable) args[0];
            Date originalDateRetired = retirable.getDateRetired();
            recursivelyHandle(UnretireHandler.class, retirable, Context.getAuthenticatedUser(), originalDateRetired, null, null);
        }
    }
}
Also used : ConceptNameSaveHandler(org.openmrs.api.handler.ConceptNameSaveHandler) SaveHandler(org.openmrs.api.handler.SaveHandler) User(org.openmrs.User) Retireable(org.openmrs.Retireable) Reflect(org.openmrs.util.Reflect) OpenmrsObject(org.openmrs.OpenmrsObject) Collection(java.util.Collection) OpenmrsObject(org.openmrs.OpenmrsObject) Voidable(org.openmrs.Voidable) UnretireHandler(org.openmrs.api.handler.UnretireHandler) Date(java.util.Date) UnvoidHandler(org.openmrs.api.handler.UnvoidHandler)

Example 65 with User

use of org.openmrs.User in project openmrs-core by openmrs.

the class AuthorizationAdvice method before.

/**
 * Allows us to check whether a user is authorized to access a particular method.
 *
 * @param method
 * @param args
 * @param target
 * @throws Throwable
 * @should notify listeners about checked privileges
 */
@Override
public void before(Method method, Object[] args, Object target) throws Throwable {
    if (log.isDebugEnabled()) {
        log.debug("Calling authorization advice before " + method.getName());
    }
    if (log.isDebugEnabled()) {
        User user = Context.getAuthenticatedUser();
        log.debug("User " + user);
        if (user != null) {
            log.debug("has roles " + user.getAllRoles());
        }
    }
    AuthorizedAnnotationAttributes attributes = new AuthorizedAnnotationAttributes();
    Collection<String> privileges = attributes.getAttributes(method);
    boolean requireAll = attributes.getRequireAll(method);
    // one of them
    if (!privileges.isEmpty()) {
        for (String privilege : privileges) {
            // skip null privileges
            if (privilege == null || privilege.isEmpty()) {
                return;
            }
            if (log.isDebugEnabled()) {
                log.debug("User has privilege " + privilege + "? " + Context.hasPrivilege(privilege));
            }
            if (Context.hasPrivilege(privilege)) {
                if (!requireAll) {
                    // causes them to "pass"
                    return;
                }
            } else {
                if (requireAll) {
                    // if all are required, the first miss causes them
                    // to "fail"
                    throwUnauthorized(Context.getAuthenticatedUser(), method, privilege);
                }
            }
        }
        if (!requireAll) {
            // If there's no match, then we know there are privileges and
            // that the user didn't have any of them. The user is not
            // authorized to access the method
            throwUnauthorized(Context.getAuthenticatedUser(), method, privileges);
        }
    } else if (attributes.hasAuthorizedAnnotation(method) && !Context.isAuthenticated()) {
        throwUnauthorized(Context.getAuthenticatedUser(), method);
    }
}
Also used : User(org.openmrs.User) AuthorizedAnnotationAttributes(org.openmrs.annotation.AuthorizedAnnotationAttributes)

Aggregations

User (org.openmrs.User)201 Test (org.junit.Test)150 BaseContextSensitiveTest (org.openmrs.test.BaseContextSensitiveTest)132 Date (java.util.Date)38 Person (org.openmrs.Person)33 Encounter (org.openmrs.Encounter)21 Patient (org.openmrs.Patient)18 PersonName (org.openmrs.PersonName)17 Role (org.openmrs.Role)13 GlobalProperty (org.openmrs.GlobalProperty)11 Location (org.openmrs.Location)11 ArrayList (java.util.ArrayList)10 EncounterType (org.openmrs.EncounterType)10 Locale (java.util.Locale)7 UserService (org.openmrs.api.UserService)7 PatientServiceImplTest (org.openmrs.api.impl.PatientServiceImplTest)7 BindException (org.springframework.validation.BindException)7 Errors (org.springframework.validation.Errors)7 EncounterRole (org.openmrs.EncounterRole)6 PatientIdentifier (org.openmrs.PatientIdentifier)6