Example usage for javax.interceptor InvocationContext getMethod

List of usage examples for javax.interceptor InvocationContext getMethod

Introduction

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

Prototype

public Method getMethod();

Source Link

Document

Returns the method of the target class for which the interceptor was invoked.

Usage

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);
    }/*  w w  w  .j a v  a 2  s  . c  o m*/
    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:EmployeeBean.java

  @AroundInvoke
public Object TimerLog(InvocationContext ctx) throws Exception {
  String beanClassName = ctx.getClass().getName();
  String businessMethodName = ctx.getMethod().getName();
  String target = beanClassName + "." + businessMethodName;
  long startTime = System.currentTimeMillis();
  System.out.println("Invoking " + target);
  try {/*from   w  w w  .j a va 2  s . c o m*/
    return ctx.proceed();
  } finally {
    System.out.println("Exiting " + target);
    long totalTime = System.currentTimeMillis() - startTime;
    System.out.println("Business method " + businessMethodName + "in " + beanClassName + "takes "
        + totalTime + "ms to execute");
  }
}

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

/**
 * /*from   www  . j a v  a 2s  .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:org.ocelotds.cache.JsCacheRemoveInterceptorTest.java

/**
 * Test of processJsCacheRemoves method, of class JsCacheRemovesInterceptor.
 * @throws java.lang.Exception// w w  w.j  a  va 2  s .  co m
 */
@Test
public void testProcessJsCacheRemove() throws Exception {
    System.out.println("processJsCacheRemove");
    InvocationContext ctx = mock(InvocationContext.class);
    Method method = CacheAnnotedClass.class.getDeclaredMethod("jsCacheRemoveAnnotatedMethodWithAllArgs",
            Integer.TYPE, String.class);
    when(ctx.getMethod()).thenReturn(method);
    instance.processJsCacheRemove(ctx);
    verify(jsCacheAnnotationServices).processJsCacheRemove(any(JsCacheRemove.class), anyList(), anyList());
    verify(ctx).proceed();
}

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 ww  .  j  a  v  a  2s. c o 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:org.ocelotds.cache.JsCacheRemovesInterceptorTest.java

/**
 * Test of processJsCacheRemoves method, of class JsCacheRemovesInterceptor.
 * @throws java.lang.Exception//  ww w  .  j  a v a 2 s  .co m
 */
@Test
public void testProcessJsCacheRemoves() throws Exception {
    System.out.println("processJsCacheRemoves");
    InvocationContext ctx = mock(InvocationContext.class);
    Method method = CacheAnnotedClass.class.getDeclaredMethod("jsCacheRemovesAnnotatedMethod", Integer.TYPE,
            CacheManagerTest.Result.class);
    when(ctx.getMethod()).thenReturn(method);
    instance.processJsCacheRemoves(ctx);
    verify(jsCacheAnnotationServices, times(2)).processJsCacheRemove(any(JsCacheRemove.class), anyList(),
            anyList());
    verify(ctx).proceed();
}

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

/**
 *
 * @param context/*from   w  w  w. j  a v a2  s  . c  om*/
 * @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.gov.frameworkdemoiselle.internal.interceptor.AuditableInterceptor.java

private String getOperation(InvocationContext ic) {
    Auditable auditable = ic.getMethod().getAnnotation(Auditable.class);

    if (auditable == null || Strings.isEmpty(auditable.resource())) {
        if (ic.getMethod().getAnnotation(Name.class) == null) {
            return ic.getMethod().getName();
        } else {/*from   www . j a va2  s.  c  om*/
            return ic.getMethod().getAnnotation(Name.class).value();
        }
    } else {
        return auditable.operation();
    }
}

From source file:br.gov.frameworkdemoiselle.internal.interceptor.AuditableInterceptor.java

/**
 * Returns the resource defined in {@code @Auditable} annotation, the name
 * defined in {@code @Name} annotation or the class name itself
 * /*  w  ww .java 2  s . c o  m*/
 * @param ic
 *            the {@code InvocationContext} in which the method is being
 *            called
 * @return the resource defined in {@code @RequiredPermission} annotation,
 *         the name defined in {@code @Name} annotation or the class name
 *         itself
 */
private String getResource(InvocationContext ic) {
    Auditable auditable = ic.getMethod().getAnnotation(Auditable.class);

    if (auditable == null || Strings.isEmpty(auditable.resource())) {
        if (ic.getTarget().getClass().getAnnotation(Name.class) == null) {
            // Returning resource Target.class.simpleName...;
            return getType(ic).getName();
        } else {
            // Returning resource Target.class.annotation(Name).value...;
            return ic.getTarget().getClass().getAnnotation(Name.class).value();
        }
    } else {
        // Returning annotation defined resource...
        return auditable.resource();
    }
}

From source file:eu.europa.ec.fisheries.uvms.interceptors.TracingInterceptor.java

@AroundInvoke
public Object logCall(InvocationContext context) throws Exception {

    final Stopwatch stopwatch = Stopwatch.createStarted();

    try {/*from w  w  w . ja v a 2s  . co  m*/

        Object[] parameters = context.getParameters();
        String params = "";
        for (Object parameter : parameters) {
            params += " " + String.valueOf(parameter);
        }

        log.debug(String.format("invocation of method %s with parameters %s", context.getMethod(), params));

        return context.proceed();

    } finally {
        log.info(String.format("Elapsed time ==> " + stopwatch));
    }
}