Example usage for javax.interceptor InvocationContext getParameters

List of usage examples for javax.interceptor InvocationContext getParameters

Introduction

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

Prototype

public Object[] getParameters();

Source Link

Document

Returns the parameter values that will be passed to the method or constructor of the target class.

Usage

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 ww  .  ja  v a  2  s  .c  om*/

        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));
    }
}

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

/**
 * //  w  ww  . j ava2s. c  o 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: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  . j  av a2  s  . c  om
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:br.gov.frameworkdemoiselle.internal.interceptor.AuditableInterceptor.java

/**
 * @param ic/*w  ww.  j  av a2 s. co  m*/
 * @param operation
 * @param auditInfo
 * @throws Exception
 */
private void setAuditInfoProperties(InvocationContext ic, String operation, AuditInfo<?> auditInfo)
        throws Exception {
    if (auditInfo != null) {
        auditInfo.setOperation(operation);
        auditInfo.setParameters(ic.getParameters());
        auditInfo.setTarget(ic.getTarget());
        auditInfo.setTargetType(getType(ic));
        // TODO: Should we use the br.gov.frameworkdemoiselle.security.User
        // interface?
        auditInfo.setUser(getUsername());
        auditInfo.setResource(getResource(ic));
        auditInfo.setDateTime(new Date());
    }
}

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

/**
 *
 * @param context/*w  ww.j  a v  a  2 s .co 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:org.perfrepo.web.security.SecurityInterceptor.java

@AroundInvoke
public Object invoke(InvocationContext ctx) throws Exception {
    Object[] params = ctx.getParameters();
    Secured secureAnnotation = ctx.getMethod().getAnnotation(Secured.class);
    if (params.length > 0) {
        //just verify first attribute
        Object param = params[0];
        SecuredEntity se = param.getClass().getAnnotation(SecuredEntity.class);
        if (se != null && param instanceof Entity<?>) {
            Entity<?> entity = (Entity<?>) param;
            if (entity.getId() == null) {
                //create mode, need to verify parent entity
                entity = (Entity<?>) PropertyUtils.getProperty(entity, se.parent());
            }//from www .  j  av  a2  s. c o  m
            if (!authorizationService.isUserAuthorizedFor(secureAnnotation.accessType(), entity)) {
                throw new SecurityException(
                        MessageUtils.getMessage("securityException.101", ctx.getMethod().getName(),
                                param.getClass().getSimpleName(), ((Entity<?>) param).getId()));
            }
        }
    }
    return ctx.proceed();
}

From source file:org.rhq.enterprise.server.authz.RequiredPermissionsInterceptor.java

/**
 * Checks to ensure the method can be invoked.
 *
 * @param  invocation_context the invocation context
 *
 * @return the results of the invocation
 *
 * @throws Exception           if an error occurred further down the interceptor stack
 * @throws PermissionException if the security check fails
 *//*from   w w  w  . j  ava2 s.  c  o m*/
@AroundInvoke
public Object checkRequiredPermissions(InvocationContext invocation_context) throws Exception {
    try {
        Map<Permission, String> perms_errors_list = new HashMap<Permission, String>();
        Method method = invocation_context.getMethod();
        RequiredPermissions perms_anno = method.getAnnotation(RequiredPermissions.class);
        RequiredPermission perm_anno = method.getAnnotation(RequiredPermission.class);

        // process the list of permissions, if specified
        if (((perms_anno != null) && (perms_anno.value().length > 0))) {
            for (RequiredPermission rq : perms_anno.value()) {
                perms_errors_list.put(rq.value(), rq.error());
            }
        }

        // process the individual permission, if specified
        if ((perm_anno != null) && (perm_anno.value() != null)) {
            perms_errors_list.put(perm_anno.value(), perm_anno.error());
        }

        // get the subject, if there is one as the first parameter to the method invocation
        Subject subject = null;
        Object[] params = invocation_context.getParameters();
        if ((params != null) && (params.length > 0) && (params[0] instanceof Subject)) {
            subject = (Subject) params[0];
        }

        // Make sure someone is not spoofing another user - ensure the associated session ID is valid.
        // This means that anytime we pass Subject as the first parameter, we are assuming it needs
        // its session validated.  If there is ever a case where we pass Subject as the first parameter
        // to an EJB and we do NOT want to validate its session, you need to annotate that EJB
        // method with @ExcludeDefaultInterceptors so we don't call this interceptor.
        if (subject != null) {
            if (subject.getSessionId() != null) {
                SubjectManagerLocal subject_manager = LookupUtil.getSubjectManager();

                // isValidSessionId will also update the session's last-access-time
                if (!subject_manager.isValidSessionId(subject.getSessionId(), subject.getName(),
                        subject.getId())) {
                    // if this happens, it is possible someone is trying to spoof an authenticated user!
                    throw buildPermissionException(
                            "The session ID for user [" + subject.getName() + "] is invalid!",
                            invocation_context);
                }
            } else {
                throw buildPermissionException("The subject [" + subject.getName() + "] did not have a session",
                        invocation_context);
            }
        }

        // if the method is not annotated or it has no permissions that are required for it to be invoked,
        // don't do anything; otherwise, we need to check the permissions
        if (perms_errors_list.size() > 0) {
            // the method to be invoked has one or more required permissions;
            // therefore, the method must have a Subject as its first argument value
            if (subject == null) {
                throw buildPermissionException(
                        "Method requires permissions but does not have a subject parameter",
                        invocation_context);
            }

            // look these up now - we don't use @EJB because I don't want the container wasting time
            // injecting EJBs if I don't need them for those methods not annotated with @RequiredPermissions
            AuthorizationManagerLocal authorization_manager = LookupUtil.getAuthorizationManager();

            Set<Permission> required_permissions = perms_errors_list.keySet();
            Set<Permission> subject_permissions = authorization_manager.getExplicitGlobalPermissions(subject);

            for (Permission required_permission : required_permissions) {
                if (!Permission.Target.GLOBAL.equals(required_permission.getTarget())) {
                    throw buildPermissionException("@RequiredPermissions must be Permission.Target.GLOBAL: ["
                            + required_permission + "]", invocation_context);
                }

                if (!subject_permissions.contains(required_permission)) {
                    String perm_error = perms_errors_list.get(required_permission);
                    String full_error = "Subject [" + subject.getName() + "] is not authorized for ["
                            + required_permission + "]";

                    if ((perm_error != null) && (perm_error.length() > 0)) {
                        full_error = perm_error + ": " + full_error;
                    }

                    throw buildPermissionException(full_error, invocation_context);
                }
            }
        }
    } catch (PermissionException pe) {
        LOG.debug("Interceptor detected a permission exception", pe);
        throw pe;
    } catch (Exception e) {
        Exception ex = buildPermissionException("Failed to check required permissions to invoke: ",
                invocation_context, e);
        LOG.debug("Permission Exception", ex);
        throw ex;
    }

    // we are authorized for all the required permissions - let the invocation continue
    return invocation_context.proceed();
}

From source file:org.rhq.enterprise.server.rest.ReportsInterceptor.java

@AroundInvoke
public Object setCaller(final InvocationContext ctx) throws Exception {
    AbstractRestBean target = (AbstractRestBean) ctx.getTarget();

    boolean fromRest = false;
    // If we are "forwarded" from the "normal" rest-api, we have a principal, that we can use
    java.security.Principal p = ejbContext.getCallerPrincipal();
    if (p != null) {
        target.caller = subjectManager.getSubjectByName(p.getName());
        fromRest = true;//from   w  w  w .j a va2 s . c  o  m
    }

    // If no caller was set from the "normal" api, we need to check if it is
    // available in cookies, as in this case we were invoked
    // from the Coregui reports function
    if (target.caller == null) {
        HttpServletRequest request = getRequest(ctx.getParameters());
        if (request == null) {
            // TODO should we throw a different exception?
            String msg = "No " + HttpServletRequest.class.getName() + " parameter was found for "
                    + getMethodName(ctx) + ". An " + HttpServletRequest.class.getName()
                    + " parameter must be specified in order to support authentication";
            log.error(msg);
            throw new OperationNotSupportedException(msg);
        }

        Subject subject = getSubject(request);
        if (subject == null) {
            throw new IllegalAccessException(
                    "Failed to validate request: could not access subject for request URL "
                            + request.getRequestURL());
        }

        target.caller = subject;
    }

    // Invoke the target method
    Object result = ctx.proceed();

    if (result instanceof StreamingOutput) {
        return new LoggingStreamingOutput((StreamingOutput) result, getMethodName(ctx));
    }

    // TODO invalidate session?

    return result;
}

From source file:org.silverpeas.core.util.annotation.AnnotationUtil.java

/**
 * Provides a centralized way to extract annotated method parameter values.
 * @param invocationContext the context of invocation.
 * @return the map with keys of Annotation class and values of object list.
 * @throws Exception// w w  w. j  a  v a2s.co  m
 */
public static Map<Class<Annotation>, List<Object>> extractMethodAnnotatedParameterValues(
        InvocationContext invocationContext) throws Exception {
    return extractMethodAnnotatedParameterValues(getInterceptedMethodFromContext(invocationContext),
            invocationContext.getParameters());
}

From source file:pl.setblack.airomem.direct.impl.ClassContext.java

public Object performTransaction(InvocationContext ctx) {
    final Method method = ctx.getMethod();
    final OperationType opType = findRegistry().sayTypeOfMethod(method);
    if (opType == OperationType.WRITE) {
        return this.performTransaction(ctx.getTarget(), method, ctx.getParameters());
    } else {/*w ww  .  ja  v  a2 s .  com*/
        try {

            final SimpleController controller = PrevaylerRegister.getInstance()
                    .getController(elem.getTargetType(), elem.getName());

            inject(ctx.getTarget(), controller.query(immutable -> immutable));
            return Politician.beatAroundTheBush(() -> ctx.proceed());
        } finally {
            clean(ctx.getTarget());

        }
    }

}