SpringUserGetter.java

45 lines | 1.55 kB Blame History Raw Download
package br.ufrgs.inf.prosoft.tigris.monitoring.usersession;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.InvocationTargetException;

/**
 * The type Spring user getter.
 */
public class SpringUserGetter implements UserGetter {

    private final Object auth;
    /**
     * The Logger.
     */
    Logger logger = LoggerFactory.getLogger(SpringUserGetter.class);

    /**
     * Instantiates a new Spring user getter.
     *
     * @throws NoSuchMethodException     the no such method exception
     * @throws ClassNotFoundException    the class not found exception
     * @throws IllegalAccessException    the illegal access exception
     * @throws InstantiationException    the instantiation exception
     * @throws InvocationTargetException the invocation target exception
     */
    public SpringUserGetter() throws NoSuchMethodException, ClassNotFoundException, IllegalAccessException, InstantiationException, InvocationTargetException {
        Object contextHolder = Class.forName("org.springframework.security.core.context.SecurityContextHolder").newInstance();
        Object context = contextHolder.getClass().getMethod("getContext").invoke(contextHolder);
        auth = context.getClass().getMethod("getAuthentication").invoke(context);
    }

    @Override
    public String getCurrentUser() {
        try {
            return (String) auth.getClass().getMethod("getName").invoke(auth);
        } catch (Exception e) {
            logger.debug("Not able to get the current user.", e);
        }
        return "Anonymous";
    }
}