Example usage for javax.interceptor InvocationContext proceed

List of usage examples for javax.interceptor InvocationContext proceed

Introduction

In this page you can find the example usage for javax.interceptor InvocationContext proceed.

Prototype

public Object proceed() throws Exception;

Source Link

Document

Proceed to the next interceptor in the interceptor chain.

Usage

From source file:com.hiperium.bo.interceptor.UserAuditInterceptor.java

/**
 * /*from w w  w . j  a  v a2 s .co m*/
 * @param context
 * @return
 * @throws Exception
 */
public Object registerUserAudit(InvocationContext context) throws InformationException {
    this.log.debug("registerUserAudit() - BEGIN: " + context.getMethod().getName());
    Object result = null;
    // Validate the user session ID
    Object[] params = context.getParameters();
    String sessionId = (String) params[params.length - 1];
    if (StringUtils.isBlank(sessionId) || !this.sessionManager.isUserLoggedIn(sessionId)) {
        throw InformationException.generate(EnumI18N.COMMON, EnumInformationException.ACCESS_NOT_ALLOWED,
                Locale.getDefault());
    }
    try {
        // Identify the CRUD operation in the method invocation
        EnumCrudOperation operation = EnumCrudOperation.decodeValue(context.getMethod().getName());
        if (EnumCrudOperation.CREATE.equals(operation) || EnumCrudOperation.UPDATE.equals(operation)
                || EnumCrudOperation.DELETE.equals(operation)) {
            log.debug("CRUD OPERATION");
            result = context.proceed();
            // At the return of the method invocation we need to store the audit
            this.userAuditBO.create(context.getTarget().getClass().getSimpleName(), operation, sessionId);
        } else if (EnumCrudOperation.READ.equals(operation)) {
            log.debug("READ OPERATION");
            result = context.proceed();
        } else {
            throw InformationException.generate(EnumI18N.COMMON, EnumInformationException.ACCESS_NOT_ALLOWED,
                    this.sessionManager.findUserLocale(sessionId));
        }
    } catch (Exception e) {
        InformationException infoException = null;
        if (e.getCause() instanceof InformationException) {
            infoException = (InformationException) e;
            throw infoException;
        }
        infoException = this.exceptionManager.createMessageException(e,
                this.sessionManager.findUserLocale(sessionId));
        throw infoException;
    }
    this.log.debug("registerUserAudit() - END: " + context.getMethod().getName());
    return result;
}

From source file:com.hiperium.bo.control.impl.DeviceBOImpl.java

/**
 *
 * @param context//w  w  w .  ja  v  a  2 s .c o  m
 * @return
 * @throws Exception
 */
@AroundInvoke
private Object validateMethod(InvocationContext context) throws Exception, InformationException {
    this.log.debug("validateMethod() - BEGIN: " + context.getMethod().getName());
    String methodName = context.getMethod().getName();
    Object result = null;

    // INTERCEPTS ONLY DEVICE OPERATION METHODS
    if ("userOperation".equals(methodName) || "homeOperation".equals(methodName)) {
        Object[] params = context.getParameters();
        String sessionId = (String) params[1];
        if (StringUtils.isBlank(sessionId) || !this.sessionManager.isUserLoggedIn(sessionId)) {
            throw InformationException.generate(EnumI18N.COMMON, EnumInformationException.ACCESS_NOT_ALLOWED,
                    Locale.getDefault());
        }

        // PROCEED WITH METHOD CALL
        try {
            DeviceDTO deviceDTO = (DeviceDTO) params[0];
            super.getDaoFactory().getDeviceDAO().updateDeviceState(deviceDTO);
            result = context.proceed();
            this.userDeviceAuditBO.create(deviceDTO, sessionId);
        } catch (Exception e) {
            InformationException infoException = null;
            if (e.getCause() instanceof InformationException) {
                infoException = (InformationException) e;
                throw infoException;
            }
            infoException = this.exceptionManager.createMessageException(e,
                    this.sessionManager.findUserLocale(sessionId));
            throw infoException;
        }
    } else {
        result = context.proceed();
    }
    this.log.debug("validateMethod() - END: " + context.getMethod().getName());
    return result;
}

From source file:br.ufc.ivela.ejb.interceptors.BeanExceptionInterceptor.java

/**
 * Log Interceptors for EJB, it is configured by default to run over all
 * bean methods, if you wish to disable for a specific bean, use the 
 * ExcludeDefaultInterceptors annotation.
 *//* w  w  w  . ja  va  2 s  .  co  m*/
public Object log(InvocationContext invocationContext) throws Exception {
    Object result = null;
    boolean debug = logger.isDebugEnabled();
    if (debug) {
        String methodName = invocationContext.getMethod().getName();
        String className = invocationContext.getTarget().getClass().getName();
        logger.debug("Calling Method: " + className + "." + methodName);
        Object[] params = invocationContext.getParameters();
        if (params != null) {
            StringBuilder builder = new StringBuilder("Parameters: ");
            for (Object param : params) {
                builder.append('[');
                if (param != null) {
                    builder.append(param.getClass().getName());
                    builder.append(':');
                    builder.append(param.toString());
                } else {
                    logger.debug("null");
                }
                builder.append(']');
            }
            logger.debug(builder.toString());
        }
    }

    try {
        result = invocationContext.proceed();
        if (debug) {
            if (result != null)
                logger.debug("Result: " + result.getClass());
            else
                logger.debug("Result: null");
        }
    } catch (Exception e) {
        String methodName = invocationContext.getMethod().getName();
        String className = invocationContext.getTarget().getClass().getName();
        logger.error("Error in: " + className + "." + methodName, e);
        throw e;
    }
    return result;
}

From source file:be.fedict.hsm.admin.webapp.security.SecurityInterceptor.java

@AroundInvoke
public Object securityVerification(InvocationContext invocationContext) throws Exception {
    Method method = invocationContext.getMethod();
    Class<?> clazz = invocationContext.getMethod().getDeclaringClass();
    LOG.trace("security verification: " + clazz.getSimpleName() + "." + method.getName());
    RolesAllowed rolesAllowedAnnotation = method.getAnnotation(RolesAllowed.class);
    if (null == rolesAllowedAnnotation) {
        rolesAllowedAnnotation = clazz.getAnnotation(RolesAllowed.class);
    }/*from   www  .j  a  va 2 s . com*/
    String[] allowedRoles = rolesAllowedAnnotation.value();

    FacesContext facesContext = FacesContext.getCurrentInstance();
    ExternalContext externalContext = facesContext.getExternalContext();
    HttpServletRequest httpServletRequest = (HttpServletRequest) externalContext.getRequest();
    Principal userPrincipal = httpServletRequest.getUserPrincipal();
    if (null == userPrincipal) {
        throw new SecurityException("user not logged in");
    }

    boolean userInRole = false;
    for (String allowedRole : allowedRoles) {
        if (httpServletRequest.isUserInRole(allowedRole)) {
            LOG.trace("user in role: " + allowedRole);
            userInRole = true;
            break;
        }
    }
    if (false == userInRole) {
        throw new SecurityException("user not in allowed roles");
    }

    return invocationContext.proceed();
}

From source file:org.apache.commons.javaflow.examples.cdi.owb.interceptors.LoggableMethodInterceptor.java

@AroundInvoke
public Object manageSecurityContext(InvocationContext ctx) throws Exception {
    System.out.println("Enetering " + ctx.getMethod());
    try {//from  ww w .j  a v a 2  s.c om
        return ctx.proceed();
    } finally {
        System.out.println("Exiting " + ctx.getMethod());
    }
}

From source file:org.apache.commons.javaflow.examples.cdi.owb.interceptors.SecureBeanInterceptor.java

@AroundInvoke
public Object manageSecurityContext(InvocationContext ctx) throws Exception {
    System.out.println("Security Interceptor before call");
    try {/*from   ww w.  j  a v a2  s.  c om*/
        return ctx.proceed();
    } finally {
        System.out.println("Security Interceptor after call");
    }
}

From source file:org.apache.commons.javaflow.examples.cdi.owb.interceptors.TransactionalMethodInterceptor.java

@AroundInvoke
public Object manageTransaction(InvocationContext ctx) throws Throwable {
    System.out.println("Begin transaction...");
    boolean success = true;
    try {// w  ww  .  j  a  va2s  .c  o m
        return ctx.proceed();
    } catch (final Throwable ex) {
        System.out.println("...Rollback transaction");
        success = false;
        throw ex;
    } finally {
        if (success) {
            System.out.println("...Commit transaction");
        }
    }
}

From source file:org.apache.commons.javaflow.examples.cdi.weld.interceptors.LoggableMethodInterceptor.java

@AroundInvoke
public Object manageSecurityContext(InvocationContext ctx) throws Exception {
    System.out.println("Entering " + ctx.getMethod());
    try {//from ww  w .  j  a  v a2s.c om
        return ctx.proceed();
    } finally {
        System.out.println("Exiting " + ctx.getMethod());
    }
}

From source file:org.commonjava.indy.metrics.jaxrs.interceptor.MetricsInterceptor.java

@AroundInvoke
public Object operation(InvocationContext context) throws Exception {
    if (!config.isMetricsEnabled()) {
        return context.proceed();
    }// w w  w  . jav a2  s . c  om

    Method method = context.getMethod();
    Measure measure = method.getAnnotation(Measure.class);
    if (measure == null) {
        measure = method.getDeclaringClass().getAnnotation(Measure.class);
    }

    logger.trace("Gathering metrics for: {}", context.getContextData());
    String nodePrefix = config.getNodePrefix();

    String defaultName = getDefaultName(context.getMethod().getDeclaringClass(), context.getMethod().getName());

    List<Timer.Context> timers = Stream.of(measure.timers()).map(named -> {
        String name = getName(nodePrefix, named.value(), defaultName, TIMER);
        Timer.Context tc = metricsManager.getTimer(name).time();
        logger.trace("START: {} ({})", name, tc);
        return tc;
    }).collect(Collectors.toList());

    try {
        return context.proceed();
    } catch (Exception e) {
        Stream.of(measure.exceptions()).forEach((named) -> {
            String name = getName(nodePrefix, named.value(), defaultName, EXCEPTION);
            Meter meter = metricsManager.getMeter(name);
            logger.trace("ERRORS++ {}", name);
            meter.mark();
        });

        throw e;
    } finally {
        if (timers != null) {
            timers.forEach(timer -> {
                logger.trace("STOP: {}", timer);
                timer.stop();
            });

        }
        Stream.of(measure.meters()).forEach((named) -> {
            String name = getName(nodePrefix, named.value(), defaultName, METER);
            Meter meter = metricsManager.getMeter(name);
            logger.trace("CALLS++ {}", name);
            meter.mark();
        });
    }
}

From source file:org.hibersap.ejb.interceptor.HibersapSessionInterceptor.java

@AroundInvoke
public Object injectSessionsIntoEjb(final InvocationContext ctx) throws Exception {
    Set<Field> sessionFields = getHibersapSessionFields(ctx.getTarget());

    Map<Session, String> sessionsCreated = new HashMap<Session, String>();
    try {/*  w  ww  .j a  v  a 2  s.  c  o  m*/
        for (Field sessionField : sessionFields) {
            String jndiName = getSessionManagerJndiName(sessionField);
            String key = HIBERSAP_SESSION_PREFIX + jndiName;
            Session session = (Session) ctx.getContextData().get(key);

            if (session == null) {
                LOGGER.debug("Erzeuge Hibersap-Session fr SessionManager " + jndiName);
                session = openSession(jndiName);
                sessionsCreated.put(session, jndiName);
                ctx.getContextData().put(key, session);
            }

            injectSessionIntoTarget(ctx.getTarget(), sessionField, session);
        }

        return ctx.proceed();
    } finally {
        closeSessions(sessionsCreated, ctx.getContextData());
    }
}