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

The following examples show how to use javax.interceptor.InvocationContext#getMethod() . 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: FaultToleranceInterceptor.java    From smallrye-fault-tolerance with Apache License 2.0 6 votes vote down vote up
@AroundInvoke
public Object interceptCommand(InvocationContext invocationContext) throws Exception {
    Method method = invocationContext.getMethod();
    Class<?> beanClass = interceptedBean != null ? interceptedBean.getBeanClass() : method.getDeclaringClass();
    InterceptionPoint point = new InterceptionPoint(beanClass, invocationContext);

    FaultToleranceOperation operation = operationProvider.get(beanClass, method);

    MetricsCollector collector = getMetricsCollector(operation, point);

    if (operation.isAsync() && operation.returnsCompletionStage()) {
        return properAsyncFlow(operation, invocationContext, collector, point);
    } else if (operation.isAsync()) {
        return futureFlow(operation, invocationContext, collector, point);
    } else {
        return syncFlow(operation, invocationContext, collector, point);
    }
}
 
Example 2
Source File: AbstractEjbTimingAspect.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
@AroundInvoke
public Object doPerfLogging(final InvocationContext ctx) throws Throwable {
   final Method executingMethod = ctx.getMethod();
   Profiled profiled = executingMethod == null ? DefaultProfiled.INSTANCE : (Profiled)ctx.getMethod().getAnnotation(Profiled.class);
   if (profiled == null) {
      profiled = DefaultProfiled.INSTANCE;
   }

   return this.runProfiledMethod(new AbstractJoinPoint() {
      public Object proceed() throws Throwable {
         return ctx.proceed();
      }

      public Object getExecutingObject() {
         return ctx.getTarget();
      }

      public Object[] getParameters() {
         return ctx.getParameters();
      }

      public String getMethodName() {
         return executingMethod == null ? "null" : executingMethod.getName();
      }
   }, (Profiled)profiled, this.newStopWatch(((Profiled)profiled).logger(), ((Profiled)profiled).level()));
}
 
Example 3
Source File: DefaultFutureableStrategy.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
protected ExecutorService getOrCreatePool(final InvocationContext ic)
{
    final Method method = ic.getMethod();
    ExecutorService executorService = configByMethod.get(method);
    if (executorService == null)
    {
        final AnnotatedType<?> annotatedType = beanManager.createAnnotatedType(method.getDeclaringClass());
        final AnnotatedMethod<?> annotatedMethod = AnnotatedMethods.findMethod(annotatedType, method);
        final Futureable methodConfig = annotatedMethod.getAnnotation(Futureable.class);
        final ExecutorService instance = manager.find(
                (methodConfig == null ? annotatedType.getAnnotation(Futureable.class) : methodConfig).value());
        configByMethod.putIfAbsent(method, instance);
        executorService = instance;
    }
    return executorService;
}
 
Example 4
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 5
Source File: ShiroInterceptor.java    From shiro-jwt with MIT License 6 votes vote down vote up
@AroundInvoke
public Object around(final InvocationContext ic) throws Exception {
    try {
        assertAuthorized(new InvocationContextToMethodInvocationConverter(ic));
    } catch (AuthorizationException exception) {
        Method m = ic.getMethod();
        String message = m.getAnnotation(SecurityChecked.class).message();

        if ("".equals(message)) {
            throw exception;
        } else {
            throw new ShiroException(message, exception);
        }

    }
    return ic.proceed();
}
 
Example 6
Source File: CDIJCacheHelper.java    From commons-jcs with Apache License 2.0 6 votes vote down vote up
public MethodMeta findMeta(final InvocationContext ic)
{
    final Method mtd = ic.getMethod();
    final Class<?> refType = findKeyType(ic.getTarget());
    final MethodKey key = new MethodKey(refType, mtd);
    MethodMeta methodMeta = methods.get(key);
    if (methodMeta == null)
    {
        synchronized (this)
        {
            methodMeta = methods.get(key);
            if (methodMeta == null)
            {
                methodMeta = createMeta(ic);
                methods.put(key, methodMeta);
            }
        }
    }
    return methodMeta;
}
 
Example 7
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 8
Source File: TrackingInterceptor.java    From Architecting-Modern-Java-EE-Applications with MIT License 5 votes vote down vote up
private Tracked resolveAnnotation(InvocationContext context) {
    Function<AnnotatedElement, Tracked> extractor = c -> c.getAnnotation(Tracked.class);
    Method method = context.getMethod();

    Tracked tracked = extractor.apply(method);
    return tracked != null ? tracked : extractor.apply(method.getDeclaringClass());
}
 
Example 9
Source File: LoggableInterceptor.java    From microprofile-rest-client with Apache License 2.0 5 votes vote down vote up
@AroundInvoke
public Object logInvocation(InvocationContext ctx) throws Exception {
    Method m = ctx.getMethod();
    invocationMessage = m.getDeclaringClass().getName() + "." + m.getName();

    Object returnVal = ctx.proceed();
    invocationMessage += " " + returnVal;
    return returnVal;
}
 
Example 10
Source File: SwaggerRestApplicationInterceptor.java    From thorntail with Apache License 2.0 5 votes vote down vote up
/**
 * As per the JAX-RS specification, if a deployment sub-classes JAX-RS Application and returns a non-empty collection for
 * either {@link Application#getClasses()} or {@link Application#getSingletons()}, then, only the references mentioned in
 * those collections should be used as REST resources. This poses a slight problem when the developers <i>expect</i> to see
 * their Swagger resources, but don't see it (due to specification conformance). This method takes care of adding the
 * relevant resources (if required).
 */
@SuppressWarnings("unchecked")
@AroundInvoke
public Object aroundInvoke(InvocationContext context) throws Exception {
    Object response = context.proceed();

    // Verify if we need to do anything at all or not. This is to avoid the potential misconfiguration where this
    // interceptor gets added to beans that should not be included.
    Method method = context.getMethod();
    if (Application.class.isAssignableFrom(method.getDeclaringClass())) {
        if ("getClasses".equals(method.getName())) {
            Set<Class<?>> classes = new HashSet<>((Set<Class<?>>) response);

            // Check the response for singletons as well.
            Method getSingletons = Application.class.getDeclaredMethod("getSingletons");
            Set singletons = (Set) getSingletons.invoke(context.getTarget());
            if (!classes.isEmpty() || !singletons.isEmpty()) {
                classes.add(ApiListingResource.class);
                classes.add(SwaggerSerializers.class);
                response = classes;
                SwaggerMessages.MESSAGES.addingSwaggerResourcesToCustomApplicationSubClass();
            }
        }
    } else {
        SwaggerMessages.MESSAGES.warnInvalidBeanTarget(method.getDeclaringClass());
    }

    return response;
}
 
Example 11
Source File: CustomSecurityAspect.java    From training with MIT License 5 votes vote down vote up
@AroundInvoke
public Object customSecurityConcern(InvocationContext context) throws Exception {
	Method method = context.getMethod();
	if (isCallAllowed(method)) {
		return context.proceed();
	} else {
		throw new IllegalAccessError();
	}
}
 
Example 12
Source File: Breakr.java    From breakr with Apache License 2.0 5 votes vote down vote up
@AroundInvoke
public Object guard(InvocationContext ic) throws Exception {
    long maxFailures = IgnoreCallsWhen.MAX_FAILURES;
    long maxDuration = IgnoreCallsWhen.TIMEOUT;
    Method method = ic.getMethod();

    boolean closeCircuit = method.isAnnotationPresent(CloseCircuit.class);
    if (closeCircuit) {
        this.circuit.reset();
    }

    IgnoreCallsWhen configuration = method.
            getAnnotation(IgnoreCallsWhen.class);
    if (configuration != null) {
        maxFailures = configuration.failures();
        maxDuration = configuration.slowerThanMillis();
    }
    long start = System.currentTimeMillis();

    try {
        if (circuit.isOpen(maxFailures)) {
            return null;
        }
        return ic.proceed();
    } catch (Exception ex) {
        circuit.newException(ex);
        throw ex;
    } finally {
        long duration = System.currentTimeMillis() - start;
        if (duration > maxDuration) {
            this.circuit.newTimeout(duration);
        }
    }
}
 
Example 13
Source File: Interceptor.java    From tomee with Apache License 2.0 5 votes vote down vote up
/**
 * This interceptor creates/updates an inner map for every method that it intercepts.
 * The inner map contains the array of method parameters in the key PARAMETERS.
 * The inner map contains the list of interceptor methods in the key INTERCEPTORS.
 * The inner map is put back into the contextData against the method name as the key.
 *
 * @param ctx             - InvocationContext
 * @param interceptorName name of the interceptor
 * @return contextData - the contextData which now has been filled with a hashmap of hashmap.
 */
@SuppressWarnings("unchecked")
public static Map<String, Object> profile(final InvocationContext ctx, final String interceptorName) {
    /*if (sessionContext != null) {
        System.out.println(sessionContext.lookup("java:comp/env"));        
    }
    else {
        System.out.println("SessionContext is null");
    }*/


    final Map<String, Object> ctxData = ctx.getContextData();

    final String KEY;
    if (ctx.getMethod() != null) {
        KEY = ctx.getMethod().getName();
    } else {
        KEY = (ctx.getTarget()).getClass().getSimpleName();
    }

    Map<String, Object> innerMap = (HashMap<String, Object>) ctxData.get(KEY);
    innerMap = updateInterceptorsList(innerMap, interceptorName);

    // don't try to get parameters for call back methods (you'll get an IllegalStateException)
    if (ctx.getMethod() != null) {
        final Object[] params = ctx.getParameters();
        innerMap.put("PARAMETERS", params);
    }

    ctxData.put(KEY, innerMap);

    return ctxData;
}
 
Example 14
Source File: LockSupplierStorage.java    From deltaspike with Apache License 2.0 4 votes vote down vote up
protected LockSupplier getLockSupplier(final InvocationContext ic)
{
    final Method key = ic.getMethod();
    LockSupplier operation = lockSuppliers.get(key);
    if (operation == null)
    {
        final Class declaringClass = key.getDeclaringClass();
        final AnnotatedType<Object> annotatedType = beanManager.createAnnotatedType(declaringClass);
        final AnnotatedMethod<?> annotatedMethod = AnnotatedMethods.findMethod(annotatedType, key);

        Locked config = annotatedMethod.getAnnotation(Locked.class);
        if (config == null)
        {
            config = annotatedType.getAnnotation(Locked.class);
        }
        final Locked.LockFactory factory = config.factory() != Locked.LockFactory.class ?
                Locked.LockFactory.class.cast(
                        beanManager.getReference(beanManager.resolve(
                                beanManager.getBeans(
                                        config.factory())),
                                Locked.LockFactory.class, null)) : this;

        final ReadWriteLock writeLock = factory.newLock(annotatedMethod, config.fair());
        final long timeout = config.timeoutUnit().toMillis(config.timeout());
        final Lock lock = config.operation() == READ ? writeLock.readLock() : writeLock.writeLock();

        if (timeout > 0)
        {
            operation = new LockSupplier()
            {
                @Override
                public Lock get()
                {
                    try
                    {
                        if (!lock.tryLock(timeout, TimeUnit.MILLISECONDS))
                        {
                            throw new IllegalStateException("Can't lock for " + key + " in " + timeout + "ms");
                        }
                    }
                    catch (final InterruptedException e)
                    {
                        Thread.interrupted();
                        throw new IllegalStateException("Locking interrupted", e);
                    }
                    return lock;
                }
            };
        }
        else
        {
            operation = new LockSupplier()
            {
                @Override
                public Lock get()
                {
                    lock.lock();
                    return lock;
                }
            };
        }

        final LockSupplier existing = lockSuppliers.putIfAbsent(key, operation);
        if (existing != null)
        {
            operation = existing;
        }
    }
    return operation;
}
 
Example 15
Source File: DefaultSecurityStrategy.java    From deltaspike with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Object execute(InvocationContext invocationContext) throws Exception
{
    Method method = invocationContext.getMethod();

    SecurityMetaDataStorage metaDataStorage = securityExtension.getMetaDataStorage();

    Class targetClass = ProxyUtils.getUnproxiedClass(invocationContext.getTarget().getClass()); //see DELTASPIKE-517

    Set<Authorizer> authorizers = metaDataStorage.getAuthorizers(targetClass, method);

    invokeBeforeMethodInvocationAuthorizers(invocationContext, authorizers);

    Object result = invocationContext.proceed();

    invokeAfterMethodInvocationAuthorizers(invocationContext, authorizers, result);

    return result;
}
 
Example 16
Source File: MethodStopwatchSource.java    From javasimon with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
protected final Method getTargetMethod(InvocationContext context) {
	return context.getMethod();
}
 
Example 17
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();
}
 
Example 18
Source File: InvokerStorage.java    From deltaspike with Apache License 2.0 4 votes vote down vote up
Invoker getOrCreateInvoker(final InvocationContext ic)
{
    final Method method = ic.getMethod();
    Invoker i = providers.get(method);
    if (i == null)
    {
        final Class declaringClass = method.getDeclaringClass();
        final AnnotatedType<Object> annotatedType = beanManager.createAnnotatedType(declaringClass);
        final AnnotatedMethod<?> annotatedMethod = AnnotatedMethods.findMethod(annotatedType, method);

        Throttled config = annotatedMethod.getAnnotation(Throttled.class);
        if (config == null)
        {
            config = annotatedType.getAnnotation(Throttled.class);
        }
        Throttling sharedConfig = annotatedMethod.getAnnotation(Throttling.class);
        if (sharedConfig == null)
        {
            sharedConfig = annotatedType.getAnnotation(Throttling.class);
        }

        final Throttling.SemaphoreFactory factory =
                sharedConfig != null && sharedConfig.factory() != Throttling.SemaphoreFactory.class ?
                        Throttling.SemaphoreFactory.class.cast(
                                beanManager.getReference(beanManager.resolve(
                                        beanManager.getBeans(
                                                sharedConfig.factory())),
                                        Throttling.SemaphoreFactory.class, null)) : this;

        final Semaphore semaphore = factory.newSemaphore(
                annotatedMethod,
                sharedConfig != null && !sharedConfig.name().isEmpty() ?
                        sharedConfig.name() : declaringClass.getName(),
                sharedConfig != null && sharedConfig.fair(),
                sharedConfig != null ? sharedConfig.permits() : 1);
        final long timeout = config.timeoutUnit().toMillis(config.timeout());
        final int weigth = config.weight();
        i = new Invoker(semaphore, weigth, timeout);
        final Invoker existing = providers.putIfAbsent(ic.getMethod(), i);
        if (existing != null)
        {
            i = existing;
        }
    }
    return i;
}
 
Example 19
Source File: InterceptionPoint.java    From smallrye-fault-tolerance with Apache License 2.0 4 votes vote down vote up
public InterceptionPoint(Class<?> beanClass, InvocationContext invocationContext) {
    this.beanClass = beanClass;
    method = invocationContext.getMethod();
    name = beanClass.getName() + "#" + method.getName();
}
 
Example 20
Source File: MonitoringInterceptor.java    From javamelody with Apache License 2.0 2 votes vote down vote up
/**
 * Determine request name for an invocation context.
 *
 * @param context the invocation context (not null)
 * @return the request name for this invocation
 */
protected String getRequestName(InvocationContext context) {
	final Method method = context.getMethod();
	return method.getDeclaringClass().getSimpleName() + '.' + method.getName();
}