Java Code Examples for javax.interceptor.InvocationContext#getTarget()

The following examples show how to use javax.interceptor.InvocationContext#getTarget() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LoggingInterceptor.java    From apicurio-registry with Apache License 2.0 6 votes vote down vote up
@AroundInvoke
public Object logMethodEntry(InvocationContext context) throws Exception {
    Logger logger = null;
    try {
        Class<?> targetClass = RegistryApplication.class;
        Object target = context.getTarget();
        if (target != null) {
            targetClass = target.getClass();
        }
        
        logger = getLogger(targetClass);
    } catch (Throwable t) {
    }

    logger.debug("ENTERING method [{}] with {} parameters", context.getMethod().getName(), context.getParameters().length);
    Object rval = context.proceed();
    logger.debug("LEAVING method [{}]", context.getMethod().getName());
    return rval;
}
 
Example 2
Source File: AbstractMethodValidationInterceptor.java    From quarkus with Apache License 2.0 6 votes vote down vote up
/**
 * Validates the Bean Validation constraints specified at the parameters and/or
 * return value of the intercepted constructor.
 *
 * @param ctx The context of the intercepted constructor invocation.
 *
 * @throws Exception Any exception caused by the intercepted constructor
 *         invocation. A {@link ConstraintViolationException} in case
 *         at least one constraint violation occurred either during
 *         parameter or return value validation.
 */
protected void validateConstructorInvocation(InvocationContext ctx) throws Exception {
    ExecutableValidator executableValidator = validator.forExecutables();
    Set<? extends ConstraintViolation<?>> violations = executableValidator
            .validateConstructorParameters(ctx.getConstructor(), ctx.getParameters());

    if (!violations.isEmpty()) {
        throw new ConstraintViolationException(getMessage(ctx.getConstructor(), ctx.getParameters(), violations),
                violations);
    }

    ctx.proceed();
    Object createdObject = ctx.getTarget();

    violations = validator.forExecutables().validateConstructorReturnValue(ctx.getConstructor(), createdObject);

    if (!violations.isEmpty()) {
        throw new ConstraintViolationException(getMessage(ctx.getConstructor(), ctx.getParameters(), violations),
                violations);
    }
}
 
Example 3
Source File: PayloadExtractor.java    From training with MIT License 6 votes vote down vote up
@AroundInvoke
public Object onMessage(InvocationContext invocation) throws Exception {
	Object mdb = invocation.getTarget();

	if (invocation.getMethod().getName().equals("onMessage")) {
		Message message = (Message) invocation.getParameters()[0];
		try {
			Object payload = extractPayload(message);
			invokeConsumeMethod(mdb, payload);
		} catch (Exception e) {
			System.out.println("Report error: sending message to dead letter");
			e.printStackTrace();
			deadLetterSender.sendDeadLetter(message, e.getMessage(), e);
		}
	}
	return invocation.proceed();
}
 
Example 4
Source File: ConfigBundleInterceptor.java    From kumuluzee with MIT License 6 votes vote down vote up
/**
 * Method initialises class fields from configuration.
 */
@PostConstruct
public Object loadConfiguration(InvocationContext ic) throws Exception {

    Object target = ic.getTarget();
    Class targetClass = target.getClass();

    if (targetClassIsProxied(targetClass)) {
        targetClass = targetClass.getSuperclass();
    }

    ConfigBundle configBundleAnnotation = (ConfigBundle) targetClass.getDeclaredAnnotation(ConfigBundle.class);

    processConfigBundleBeanSetters(target, targetClass, getKeyPrefix(targetClass), new HashMap<>(),
            configBundleAnnotation.watch());

    return ic.proceed();
}
 
Example 5
Source File: SecuredAnnotationAuthorizer.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
protected List<Annotation> extractMetadata(InvocationContext invocationContext)
{
    List<Annotation> result = new ArrayList<Annotation>();

    Method method = invocationContext.getMethod();

    // some very old EE6 containers have a bug in resolving the target
    // so we fall back on the declaringClass of the method.
    Class<?> targetClass =
            invocationContext.getTarget() != null
                    ? ProxyUtils.getUnproxiedClass(invocationContext.getTarget().getClass())
                    : method.getDeclaringClass();


    result.addAll(SecurityUtils.getAllAnnotations(targetClass.getAnnotations(),
        new HashSet<Integer>()));
    //later on method-level annotations need to overrule class-level annotations -> don't change the order
    result.addAll(SecurityUtils.getAllAnnotations(method.getAnnotations(),
            new HashSet<Integer>()));

    return result;
}
 
Example 6
Source File: ValidationInterceptor.java    From krazo with Apache License 2.0 5 votes vote down vote up
@AroundInvoke
public Object validateMethodInvocation(InvocationContext ctx) throws Exception {

    Object resource = ctx.getTarget();
    Method method = ctx.getMethod();

    log.log(Level.FINE, "Starting validation for controller method: {0}#{1}", new Object[]{
            resource.getClass().getName(), method.getName()
    });

    Validator validator = validatorFactory.getValidator();
    ExecutableValidator executableValidator = validator.forExecutables();

    // validate controller property parameters
    processViolations(ctx,
            validator.validate(resource)
    );

    // validate controller method parameters
    processViolations(ctx,
            executableValidator.validateParameters(resource, method, ctx.getParameters())
    );

    // execute method
    Object result = ctx.proceed();

    // TODO: Does this make sense? Nobody will be able to handle these. Remove?
    processViolations(ctx,
            executableValidator.validateReturnValue(resource, method, result)
    );

    return result;

}
 
Example 7
Source File: TransactionalInterceptorBase.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private TransactionConfiguration getTransactionConfiguration(InvocationContext ic) {
    TransactionConfiguration configuration = ic.getMethod().getAnnotation(TransactionConfiguration.class);
    if (configuration == null) {
        Class<?> clazz;
        Object target = ic.getTarget();
        if (target != null) {
            clazz = target.getClass();
        } else {
            // Very likely an intercepted static method
            clazz = ic.getMethod().getDeclaringClass();
        }
        return clazz.getAnnotation(TransactionConfiguration.class);
    }
    return configuration;
}
 
Example 8
Source File: JAXRSFieldInjectionInterceptor.java    From openwebbeans-meecrowave with Apache License 2.0 5 votes vote down vote up
private void doInject(final InvocationContext ic) throws Exception {
    final Message current = JAXRSUtils.getCurrentMessage();
    if (current != null) {
        final OperationResourceInfoStack stack = OperationResourceInfoStack.class.cast(current.get(OperationResourceInfoStack.class.getName()));
        if (stack != null && !stack.isEmpty()) {
            final Object instance;
            if (ConstructorInterceptorInvocationContext.class.isInstance(ic)) {
                final ConstructorInterceptorInvocationContext constructorInterceptorInvocationContext = ConstructorInterceptorInvocationContext.class.cast(ic);
                constructorInterceptorInvocationContext.directProceed();
                instance = constructorInterceptorInvocationContext.getNewInstance();
            } else {
                instance = ic.getTarget();
            }
            Application application = null;
            final Object appInfo = current.getExchange().getEndpoint().get(Application.class.getName());
            if (ApplicationInfo.class.isInstance(appInfo)) {
                application = ApplicationInfo.class.cast(appInfo).getProvider();
            }
            synchronized (this) {
                if (injected.get()) {
                    return;
                }
                InjectionUtils.injectContextProxiesAndApplication(
                        stack.lastElement().getMethodInfo().getClassResourceInfo(),
                        instance,
                        application,
                        ProviderFactory.getInstance(current));
                injected.compareAndSet(false, true);
            }
        }
    }
}
 
Example 9
Source File: LoginToContinueInterceptor.java    From tomee with Apache License 2.0 5 votes vote down vote up
private LoginToContinue getLoginToContinue(final InvocationContext invocationContext) {
    if (invocationContext.getTarget() instanceof LoginToContinueMechanism) {
        return ((LoginToContinueMechanism) invocationContext.getTarget()).getLoginToContinue();
    }

    throw new IllegalArgumentException();
}
 
Example 10
Source File: TransactionStrategyHelper.java    From deltaspike with Apache License 2.0 5 votes vote down vote up
/**
 * @return the &#064;Transactional annotation from either the method or class
 *         or <code>null</code> if none present.
 */
protected Transactional extractTransactionalAnnotation(InvocationContext context)
{
    Class targetClass = context.getTarget() != null ? context.getTarget().getClass() :
        context.getMethod().getDeclaringClass();
    return AnnotationUtils
        .extractAnnotationFromMethodOrClass(beanManager, context.getMethod(), targetClass, Transactional.class);
}
 
Example 11
Source File: ValidationInterceptor.java    From ozark with Apache License 2.0 4 votes vote down vote up
@AroundInvoke
public Object validateMethodInvocation(InvocationContext ctx) throws Exception {

    Object resource = ctx.getTarget();
    Method method = ctx.getMethod();

    log.log(Level.FINE, "Starting validation for controller method: {0}#{1}", new Object[]{
            resource.getClass().getName(), method.getName()
    });

    Validator validator = validatorFactory.getValidator();
    ExecutableValidator executableValidator = validator.forExecutables();

    // validate controller property parameters
    processViolations(ctx,
            validator.validate(resource)
    );

    // validate controller method parameters
    processViolations(ctx,
            executableValidator.validateParameters(resource, method, ctx.getParameters())
    );

    // execute method
    Object result = ctx.proceed();

    // TODO: Does this make sense? Nobody will be able to handle these. Remove?
    processViolations(ctx,
            executableValidator.validateReturnValue(resource, method, result)
    );

    return result;

}
 
Example 12
Source File: MonitoringTargetInterceptor.java    From javamelody with Apache License 2.0 4 votes vote down vote up
@Override
protected String getRequestName(InvocationContext context) {
	final Method method = context.getMethod();
	final Object target = context.getTarget();
	return target.getClass().getSimpleName() + '.' + method.getName();
}