Example usage for javax.interceptor InvocationContext getTarget

List of usage examples for javax.interceptor InvocationContext getTarget

Introduction

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

Prototype

public Object getTarget();

Source Link

Document

Returns the target instance.

Usage

From source file:com.flexive.rest.interceptors.FxRestCallInterceptor.java

@AroundInvoke
public Object aroundInvoke(InvocationContext context) throws Exception {
    final Object target = context.getTarget();
    if (target instanceof FxRestApiService) {
        final FxRestApiService service = (FxRestApiService) target;

        FxRestApiUtils.applyRequestParameters(service.getHttpHeaders(), service.getUriInfo());

        if (LOG.isTraceEnabled()) {
            LOG.trace("REST-API call at " + service.getUriInfo().getBaseUri() + " with user "
                    + FxContext.getUserTicket().getLoginName());
        }//w ww .  ja v  a  2s .  com

        final Object result = context.proceed();

        if (result instanceof FxRestApiResponse) {
            // wrap response, set common parameters
            return FxRestApiUtils.buildResponse((FxRestApiResponse) result);
        }

        return result;
    } else {
        throw new IllegalStateException("@FxRestApi target does not implement FxRestApiService");
    }
}

From source file:Employee.java

 @PostConstruct
public void jndiInject(InvocationContext invocation) {
   Object target = invocation.getTarget();
   Field[] fields = target.getClass().getDeclaredFields();
   Method[] methods = target.getClass().getDeclaredMethods();

   // find all @JndiInjected fields methods and set them
   try {//from   w  ww  .  j a va 2 s.c om
      InitialContext ctx = new InitialContext();
      for (Method method : methods) {
         JndiInjected inject = method.getAnnotation(JndiInjected.class);
         if (inject != null) {
            Object obj = ctx.lookup(inject.value());
            method.setAccessible(true);
            method.invoke(target, obj);
         }
      }
      for (Field field : fields) {
         JndiInjected inject = field.getAnnotation(JndiInjected.class);
         if (inject != null) {
            Object obj = ctx.lookup(inject.value());
            field.setAccessible(true);
            field.set(target, obj);
         }
      }
      invocation.proceed();
   } catch (Exception ex) {
      throw new EJBException("Failed to execute @JndiInjected", ex);
   }
}

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.
 *///from w  ww. j a v a2 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.trust.service.snmp.SNMPInterceptor.java

private Object process(InvocationContext invocationContext) throws Exception {

    this.values = new HashMap<String, Long>();
    Object target = invocationContext.getTarget();
    LOG.debug("process SNMP on " + target.getClass().getCanonicalName());

    /*/*from  www .j  a  v  a  2 s .  c o  m*/
     * Process the possible SNMP annotation on the method
     */
    SNMP methodSnmp = invocationContext.getMethod().getAnnotation(SNMP.class);
    if (null != methodSnmp) {
        increment(methodSnmp.oid(), methodSnmp.service(), 1L);
    }

    /*
     * Process the possible SNMP annotation on the fields
     */
    injectSnmpFields(target);

    /*
     * Invoke
     */
    Object result = invocationContext.proceed();

    /*
     * Post-process the possible SNMP annotation on the fields
     */
    updateSnmpFields(target);

    /*
     * Check for SNMPCounter methods
     */
    SNMPCounter snmpCounter = invocationContext.getMethod().getAnnotation(SNMPCounter.class);
    if (null == snmpCounter) {
        // check if other methods are annotated this way, if so execute them
        for (Method method : target.getClass().getMethods()) {
            if (null != method.getAnnotation(SNMPCounter.class)) {
                method.invoke(target);
            }
        }
    }

    /*
     * Update the SNMP derived fields
     */
    updateSnmpDerivedFields(target);

    /*
     * Return the invocation result
     */
    return result;
}

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

private final Class<?> getType(final InvocationContext ic) {
    Class<?> type = ic.getTarget().getClass();
    type = getTargetType(type);/*from www .j  a  v  a  2 s. c o m*/
    return type;
}

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
 * /*www.  j av a  2  s.  co 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:br.gov.frameworkdemoiselle.internal.interceptor.AuditableInterceptor.java

/**
 * @param ic//from   w  w w .jav a  2s. c o 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.interceptor.UserAuditInterceptor.java

/**
 * /*from w ww  .j  a v a  2s  . 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: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  w w. j  a v  a  2  s.  co  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());
    }
}

From source file:org.nuxeo.ecm.platform.ui.web.shield.NuxeoErrorInterceptor.java

@AroundInvoke
public Object invokeAndWrapExceptions(InvocationContext invocation) throws Exception {
    try {/*from  ww  w  .  j  ava  2s.  c  o  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;
        }
    }
}