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:org.nuxeo.ecm.platform.ui.web.shield.NuxeoErrorInterceptor.java

@AroundInvoke
public Object invokeAndWrapExceptions(InvocationContext invocation) throws Exception {
    try {//from  w  w  w . j  a  v a  2  s  .co m
        // log.debug("Before invocation...");
        return invocation.proceed();
    } catch (Throwable t) {

        if (Transaction.instance().isActive()) {
            Transaction.instance().setRollbackOnly();
        }

        FacesContext facesContext = FacesContext.getCurrentInstance();

        if (FacesLifecycle.getPhaseId() == PhaseId.RENDER_RESPONSE) {
            if (ExceptionHelper.isSecurityError(t)) {
                if (facesContext != null) {
                    Object req = facesContext.getExternalContext().getRequest();
                    if (req instanceof ServletRequest) {
                        ServletRequest request = (ServletRequest) req;
                        request.setAttribute("securityException", t);
                    }
                }
                throw new DocumentSecurityException(
                        "Security Error during call of " + invocation.getTarget().toString(), t);
            }
        }

        ClientException cException = new ClientException(t);
        // redirect is not allowed during render response phase => throw
        // the error without redirecting
        if (FacesLifecycle.getPhaseId() == PhaseId.RENDER_RESPONSE) {
            if (facesContext != null) {
                Object req = facesContext.getExternalContext().getRequest();
                if (req instanceof ServletRequest) {
                    ServletRequest request = (ServletRequest) req;
                    request.setAttribute("applicationException", cException);
                }
            }
            throw cException;
        }

        // check if previous page was already an error page to avoid
        // redirect cycle
        if (facesContext != null) {
            ExternalContext externalContext = facesContext.getExternalContext();
            if (externalContext != null) {
                Map<String, String[]> requestMap = externalContext.getRequestHeaderValuesMap();
                if (requestMap != null) {
                    String[] previousPage = requestMap.get("Referer");
                    if (previousPage != null && previousPage.length != 0) {
                        String pageName = previousPage[0];
                        if (pageName != null && pageName.contains("error_page")) {
                            redirectToErrorPage(UNTHEMED_ERROR_VIEW_ID);
                            return null;
                        }
                    }
                }
            }
        }

        String redirectToViewId = null;
        try {
            log.error("Exception caught, redirecting to the error page...", cException);
            final Context sessionContext = Contexts.getSessionContext();
            // set applicationException in session hoping
            // ErrorPageActionListener will inject it
            sessionContext.set("applicationException", cException);
            if (ExceptionHelper.isSecurityError(t)
                    || cException.getCause() instanceof DocumentSecurityException) {
                redirectToViewId = LOGIN_VIEW_ID;
            } else {
                redirectToViewId = GENERIC_ERROR_VIEW_ID;
            }
        } catch (Throwable e) {
            // might be the case when session context is null
            log.error(e);
            redirectToViewId = UNTHEMED_ERROR_VIEW_ID;
        }

        if (redirectToErrorPage(redirectToViewId)) {
            return null;
        } else {
            log.info("Unable to handle exception in web-context. " + "It might be an external (soap) request. "
                    + "Throwing further...");
            log.error("Original error", t);
            throw cException;
        }
    }
}

From source file:org.openhie.openempi.ejb.SpringInjectionInterceptor.java

@AroundInvoke
public Object myBeanInterceptor(InvocationContext ctx) throws Exception {
    log.debug("Doing the AroundInvoke for bean: " + ctx.getTarget().getClass());
    BaseSpringInjectableBean bean = (BaseSpringInjectableBean) ctx.getTarget();
    bean.init();/*from  w w  w . jav  a  2 s  .c om*/
    return ctx.proceed();
}

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 w  ww  .ja va  2  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
 *//*  www .j a v a2  s .c om*/
@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.common.TransactionInterruptInterceptor.java

@AroundInvoke
public Object addCheckedActionToTransactionManager(InvocationContext invocation_context) throws Exception {
    BasicAction currentTx = null;//from   w  w w . ja  v  a  2 s  . co m
    CheckedAction previousCheckedAction = null;

    try {
        currentTx = BasicAction.Current();

        // Don't bother doing anything if the thread is currently not in a transaction.
        // But if it is in a tx, then install our new CheckedAction unless the method
        // does not want to be told about the transaction timeout (it tells us this
        // via the InterruptOnTransactionTimeout(false) annotation).
        if (currentTx != null) {
            Method method = invocation_context.getMethod();
            InterruptOnTransactionTimeout anno = method.getAnnotation(InterruptOnTransactionTimeout.class);
            boolean interrupt = (anno != null) ? anno.value() : InterruptOnTransactionTimeout.DEFAULT_VALUE;
            TransactionInterruptCheckedAction newCheckedAction = new TransactionInterruptCheckedAction(
                    interrupt);
            previousCheckedAction = currentTx.setCheckedAction(newCheckedAction);
        }
    } catch (Throwable t) {
        LOG.warn("Failure - if the transaction is aborted, its threads cannot be notified. Cause: "
                + ThrowableUtil.getAllMessages(t));
    }

    try {
        return invocation_context.proceed();
    } finally {
        if (currentTx != null && previousCheckedAction != null) {
            try {
                currentTx.setCheckedAction(previousCheckedAction);
            } catch (Exception e) {
                // paranoia - this should never happen, but ignore it if it does, keep the request going
            }
        }
    }
}

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 v a2  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.rhq.enterprise.server.rest.SetCallerInterceptor.java

/**
 * We need to take the Principal that was passed through the web-integration,
 * get an RHQ Subject and set a session for it. When the call was made, we need
 * to invalidate the session again.//from w ww.  j a v  a  2 s  . com
 * @param ctx InvocationContext from the EJB invocation chain
 * @return result of the method call
 * @throws Exception from method call or if no (valid) principal was provided
 */
@AroundInvoke
public Object setCaller(InvocationContext ctx) throws Exception {

    Subject caller = null;
    java.security.Principal p = ejbContext.getCallerPrincipal();
    if (!startupBean.isInitialized()) {
        String notInitMessage = "Tried to call REST endpoint but the server is not ready - still booting up";
        log.debug(notInitMessage);
        return Response.status(Response.Status.SERVICE_UNAVAILABLE).header("Retry-After", "30")
                .entity(notInitMessage).build();
    }

    if (p != null) {
        caller = subjectManager.getSubjectByName(p.getName());
    }

    if (caller == null) {
        throw new IllegalAccessException("No calling principal provided");
    }

    // Get Subject with a session
    caller = sessionManager.put(caller);

    // Provide it to the EJB
    AbstractRestBean target = (AbstractRestBean) ctx.getTarget();
    target.caller = caller;

    // Call the EJBs
    Object result = ctx.proceed();

    // if result is StreamingOutput, we do not want to invalidate the session until it
    // is finished writing the output; otherwise, any secure SLSB calls will fail. We
    // instead wrap the result in an instance of SecureStreamingOutput which
    // invalidates the session after the output has been written.
    if (result instanceof StreamingOutput) {
        return new SecureStreamingOutput((StreamingOutput) result, caller);
    }

    // Invalidate the session again.
    sessionManager.invalidate(caller.getSessionId());

    return result;
}

From source file:org.wso2.appserver.sample.ee.cdi.interceptor.LogImpl.java

@AroundInvoke
public Object log(InvocationContext context) throws Exception {
    log.info("Before greeting");
    context.proceed();
    log.info("After greeting");
    return null;/*w  ww  .j  av  a2 s.  c o m*/
}

From source file:org.xlcloud.iam.EntitlementInterceptor.java

/**
 * It authorizes request, if the request is kind of
 * {@link RequestAwareResource}. See://  w  ww  . j  a  v  a 2s  . c o m
 * {@link #authorizeRequest(InvocationContext)}
 * 
 * @param invocationContext
 *            invocation context
 * @return original invocation value
 * @throws Exception
 */
@AroundInvoke
public Object setupEntitlement(InvocationContext invocationContext) throws Exception {
    if (invocationContext.getTarget() instanceof RequestAwareResource) {
        authorizeRequest(invocationContext);
    }
    return invocationContext.proceed();
}

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 {/*from  w  w  w  .  j av  a  2 s.c o m*/
        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());

        }
    }

}