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

The following examples show how to use javax.interceptor.InvocationContext#getParameters() . 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: Statisticalnterceptor.java    From Java-EE-8-Design-Patterns-and-Best-Practices with MIT License 6 votes vote down vote up
@AroundInvoke
public Object statisticMethod (InvocationContext invocationContext) throws Exception{
	System.out.println("Statistical method : "
			+ invocationContext.getMethod().getName() + " " 
			+ invocationContext.getMethod().getDeclaringClass()
			);
	
	// get the enrollment:
	TestRevisionTO testRevisionTO = (TestRevisionTO)invocationContext.getParameters()[0];
	
	System.out.println("Enrolment : " + testRevisionTO.getEnrollment());
	
	// event.fireAsync (testRevisionTO.getEnrollment());// fire an async statistical event. This is new in JEE8.
	event.fire (testRevisionTO.getEnrollment());
	
	Object o =  invocationContext.proceed();
	return o;
}
 
Example 2
Source File: Statisticalnterceptor.java    From Java-EE-8-Design-Patterns-and-Best-Practices with MIT License 6 votes vote down vote up
@AroundInvoke
public Object statisticMethod (InvocationContext invocationContext) throws Exception{
	System.out.println("Statistical method : "
			+ invocationContext.getMethod().getName() + " " 
			+ invocationContext.getMethod().getDeclaringClass()
			);
	
	// get the enrollment:
	TestRevisionTO testRevisionTO = (TestRevisionTO)invocationContext.getParameters()[0];
	
	System.out.println("Enrolment : " + testRevisionTO.getEnrollment());
	
	// event.fireAsync (testRevisionTO.getEnrollment());// fire an async statistical event. This is new in JEE8.
	event.fire (testRevisionTO.getEnrollment());
	
	Object o =  invocationContext.proceed();
	return o;
}
 
Example 3
Source File: AbstractSentinelInterceptorSupport.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
protected Object handleBlockException(InvocationContext ctx, SentinelResourceBinding annotation, BlockException ex)
    throws Throwable {

    // Execute block handler if configured.
    Method blockHandlerMethod = extractBlockHandlerMethod(ctx, annotation.blockHandler(),
        annotation.blockHandlerClass());
    if (blockHandlerMethod != null) {
        Object[] originArgs = ctx.getParameters();
        // Construct args.
        Object[] args = Arrays.copyOf(originArgs, originArgs.length + 1);
        args[args.length - 1] = ex;
        try {
            if (isStatic(blockHandlerMethod)) {
                return blockHandlerMethod.invoke(null, args);
            }
            return blockHandlerMethod.invoke(ctx.getTarget(), args);
        } catch (InvocationTargetException e) {
            // throw the actual exception
            throw e.getTargetException();
        }
    }

    // If no block handler is present, then go to fallback.
    return handleFallback(ctx, annotation, ex);
}
 
Example 4
Source File: AutoApplySessionInterceptor.java    From tomee with Apache License 2.0 6 votes vote down vote up
private AuthenticationStatus validateRequest(final InvocationContext invocationContext)
        throws Exception {

    final HttpMessageContext httpMessageContext = (HttpMessageContext) invocationContext.getParameters()[2];

    final Principal principal = httpMessageContext.getRequest().getUserPrincipal();
    if (principal == null) {
        final Object authenticationStatus = invocationContext.proceed();

        if (AuthenticationStatus.SUCCESS.equals(authenticationStatus)) {
            httpMessageContext.getMessageInfo().getMap().put("javax.servlet.http.registerSession", "true");
        }

        return (AuthenticationStatus) authenticationStatus;
    } else {
        final CallerPrincipalCallback callerPrincipalCallback =
                new CallerPrincipalCallback(httpMessageContext.getClientSubject(), principal);

        httpMessageContext.getHandler().handle(new Callback[] {callerPrincipalCallback});

        return AuthenticationStatus.SUCCESS;
    }
}
 
Example 5
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 6
Source File: DocumentLoggerInterceptor.java    From eplmp with Eclipse Public License 1.0 6 votes vote down vote up
@AroundInvoke
public Object log(InvocationContext ctx) throws Exception {

    Object result = ctx.proceed();

    Object[] parameters = ctx.getParameters();
    boolean isRoleAllowed = contextManager.isCallerInRole(UserGroupMapping.REGULAR_USER_ROLE_ID);

    if (isRoleAllowed && parameters != null && parameters.length > 0 && parameters[0] instanceof String) {
        // Not reliable condition, should be reviewed
        String fullName = (String) parameters[0];
        try {
            documentManager.logDocument(fullName, DOWNLOAD_EVENT);
        } catch (Exception ex) {
            LOGGER.log(Level.SEVERE, null, ex);
        }
    }

    return result;
}
 
Example 7
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 8
Source File: InterceptorMdbBean.java    From tomee with Apache License 2.0 5 votes vote down vote up
@AroundInvoke
public Object aroundInvoke(final InvocationContext ctx) throws Exception {
    final Object[] objArr = ctx.getParameters();
    final Message msg = (Message) objArr[0];
    msg.setBooleanProperty("MethodLevelBusinessMethodInterception", true);
    ctx.setParameters(objArr);
    return ctx.proceed();
}
 
Example 9
Source File: RememberMeInterceptor.java    From tomee with Apache License 2.0 5 votes vote down vote up
private void cleanSubject(final InvocationContext invocationContext) throws Exception {
    final HttpMessageContext httpMessageContext = (HttpMessageContext) invocationContext.getParameters()[2];

    final RememberMe rememberMe = getRememberMe();
    getCookie(httpMessageContext.getRequest(), rememberMe.cookieName())
            .ifPresent(cookie -> {
                rememberMeIdentityStore.get().removeLoginToken(cookie.getValue());

                cookie.setMaxAge(0);
                httpMessageContext.getResponse().addCookie(cookie);
            });

    invocationContext.proceed();
}
 
Example 10
Source File: RememberMeInterceptor.java    From tomee with Apache License 2.0 5 votes vote down vote up
private AuthenticationStatus validateRequest(final InvocationContext invocationContext) throws Exception {
    final HttpMessageContext httpMessageContext = (HttpMessageContext) invocationContext.getParameters()[2];

    final RememberMe rememberMe = getRememberMe();
    final Optional<Cookie> cookie = getCookie(httpMessageContext.getRequest(), rememberMe.cookieName());

    if (cookie.isPresent()) {
        final RememberMeCredential rememberMeCredential = new RememberMeCredential(cookie.get().getValue());
        final CredentialValidationResult validate = rememberMeIdentityStore.get().validate(rememberMeCredential);

        if (VALID.equals(validate.getStatus())) {
            return httpMessageContext.notifyContainerAboutLogin(validate);
        } else {
            cookie.get().setMaxAge(0);
            httpMessageContext.getResponse().addCookie(cookie.get());
        }
    }

    final AuthenticationStatus status = (AuthenticationStatus) invocationContext.proceed();

    if (SUCCESS.equals(status) && rememberMe.isRememberMe()) {
        final CallerPrincipal principal = new CallerPrincipal(httpMessageContext.getCallerPrincipal().getName());
        final Set<String> groups = httpMessageContext.getGroups();
        final String loginToken = rememberMeIdentityStore.get().generateLoginToken(principal, groups);

        final Cookie rememberMeCookie = new Cookie(rememberMe.cookieName(), loginToken);
        rememberMeCookie.setMaxAge(rememberMe.cookieMaxAgeSeconds());
        rememberMeCookie.setHttpOnly(rememberMe.cookieHttpOnly());
        rememberMeCookie.setSecure(rememberMe.cookieSecureOnly());
        httpMessageContext.getResponse().addCookie(rememberMeCookie);
    }

    return status;
}
 
Example 11
Source File: LoginToContinueInterceptor.java    From tomee with Apache License 2.0 5 votes vote down vote up
private AuthenticationStatus validateRequest(final InvocationContext invocationContext)
        throws Exception {

    final HttpMessageContext httpMessageContext = (HttpMessageContext) invocationContext.getParameters()[2];
    clearStaleState(httpMessageContext);

    if (httpMessageContext.getAuthParameters().isNewAuthentication()) {
        return processCallerInitiatedAuthentication(httpMessageContext);
    } else {
        return processContainerInitiatedAuthentication(invocationContext, httpMessageContext);
    }
}
 
Example 12
Source File: LdapInterceptor.java    From development with Apache License 2.0 5 votes vote down vote up
/**
 * Ensures that LDAP support is disabled if OSCM acts as a SAML SP.
 */
@AroundInvoke
public Object ensureLdapDisabledForServiceProvider(InvocationContext context)
        throws Exception {
    Object result = null;
    Object organizationProperties = null;

    Object[] parameters = context.getParameters();
    for (int i = 0; i < parameters.length; i++) {
        if (parameters[i] instanceof LdapProperties
                || parameters[i] instanceof Properties) {
            organizationProperties = parameters[i];
        }
    }

    if (configService.isServiceProvider() && organizationProperties != null) {
        UnsupportedOperationException e = new UnsupportedOperationException(
                "It is forbidden to perform this operation if a OSCM acts as a SAML service provider.");

        Log4jLogger logger = LoggerFactory.getLogger(context.getTarget()
                .getClass());
        logger.logError(Log4jLogger.SYSTEM_LOG, e,
                LogMessageIdentifier.ERROR_OPERATION_FORBIDDEN_FOR_SAML_SP);
        throw e;
    }

    result = context.proceed();
    return result;
}
 
Example 13
Source File: DefaultFutureableStrategy.java    From deltaspike with Apache License 2.0 5 votes vote down vote up
private CallKey(final InvocationContext ic)
{
    this.ic = ic;

    final Object[] parameters = ic.getParameters();
    this.hash = ic.getMethod().hashCode() + (parameters == null ? 0 : Arrays.hashCode(parameters));
}
 
Example 14
Source File: MdbInterceptor.java    From tomee with Apache License 2.0 5 votes vote down vote up
@AroundInvoke
public Object mdbInterceptor(final InvocationContext ctx) throws Exception {
    final Object[] objArr = ctx.getParameters();
    final Message msg = (Message) objArr[0];
    msg.clearProperties();
    msg.setBooleanProperty("ClassLevelBusinessMethodInterception", true);
    ctx.setParameters(objArr);
    return ctx.proceed();
}
 
Example 15
Source File: CrossOriginInterceptor.java    From javaee8-jaxrs-sample with GNU General Public License v3.0 5 votes vote down vote up
@AroundInvoke
protected Object invoke(InvocationContext ctx) throws Exception {
    ctx.getParameters();
    if (request.getHeader("Origin") != null) {
        return crossOriginResponse((Response) ctx.proceed(), request.getHeader("Origin"));
    } else {
        return ctx.proceed();
    }
}
 
Example 16
Source File: ExceptionHandlingInterceptor.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@AroundInvoke
Object intercept(InvocationContext ctx) throws Exception {
    if (ctx.getParameters()[0] == ExceptionHandlingCase.OTHER_EXCEPTIONS) {
        throw new MyOtherException();
    }
    return ctx.proceed();
}
 
Example 17
Source File: PaymentManipulationInterceptor.java    From blog-tutorials with MIT License 5 votes vote down vote up
@AroundInvoke
public Object manipulatePayment(InvocationContext invocationContext) throws Exception {

    if (invocationContext.getParameters()[0] instanceof String) {
        if (((String) invocationContext.getParameters()[0]).equalsIgnoreCase("duke")) {
            paymentManipulator.manipulatePayment();
            invocationContext.setParameters(new Object[]{
                    "Duke", new BigDecimal(999.99).setScale(2, RoundingMode.HALF_UP)
            });
        }
    }

    return invocationContext.proceed();
}
 
Example 18
Source File: AbstractSentinelInterceptorSupport.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
protected Object handleFallback(InvocationContext ctx, String fallback, String defaultFallback,
                                Class<?>[] fallbackClass, Throwable ex) throws Throwable {
    Object[] originArgs = ctx.getParameters();

    // Execute fallback function if configured.
    Method fallbackMethod = extractFallbackMethod(ctx, fallback, fallbackClass);
    if (fallbackMethod != null) {
        // Construct args.
        int paramCount = fallbackMethod.getParameterTypes().length;
        Object[] args;
        if (paramCount == originArgs.length) {
            args = originArgs;
        } else {
            args = Arrays.copyOf(originArgs, originArgs.length + 1);
            args[args.length - 1] = ex;
        }

        try {
            if (isStatic(fallbackMethod)) {
                return fallbackMethod.invoke(null, args);
            }
            return fallbackMethod.invoke(ctx.getTarget(), args);
        } catch (InvocationTargetException e) {
            // throw the actual exception
            throw e.getTargetException();
        }
    }
    // If fallback is absent, we'll try the defaultFallback if provided.
    return handleDefaultFallback(ctx, defaultFallback, fallbackClass, ex);
}
 
Example 19
Source File: RegexFilterInterceptor.java    From smallrye-config with Apache License 2.0 5 votes vote down vote up
private Optional<ChangeEvent> getChangeEvent(InvocationContext ctx) {
    Object[] parameters = ctx.getParameters();

    for (Object parameter : parameters) {
        if (parameter.getClass().equals(ChangeEvent.class)) {
            ChangeEvent changeEvent = (ChangeEvent) parameter;
            return Optional.of(changeEvent);
        }
    }
    return Optional.empty();
}
 
Example 20
Source File: ParameterLogArgument.java    From logging-interceptor with Apache License 2.0 4 votes vote down vote up
@Override
public Object value(InvocationContext context) {
    Object object = context.getParameters()[parameter.index()];
    object = evaluateExpressionOn(object);
    return converters.convert(object);
}