List of usage examples for javax.interceptor InvocationContext getMethod
public Method getMethod();
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 w w w . jav a 2s .co 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:org.apache.commons.javaflow.examples.cdi.owb.interceptors.LoggableMethodInterceptor.java
@AroundInvoke public Object manageSecurityContext(InvocationContext ctx) throws Exception { System.out.println("Enetering " + ctx.getMethod()); try {//from w w w .ja v a2s . co m return ctx.proceed(); } finally { System.out.println("Exiting " + ctx.getMethod()); } }
From source file:org.apache.commons.javaflow.examples.cdi.weld.interceptors.LoggableMethodInterceptor.java
@AroundInvoke public Object manageSecurityContext(InvocationContext ctx) throws Exception { System.out.println("Entering " + ctx.getMethod()); try {//from w w w .j ava 2 s. c o m return ctx.proceed(); } finally { System.out.println("Exiting " + ctx.getMethod()); } }
From source file:org.commonjava.indy.metrics.jaxrs.interceptor.MetricsInterceptor.java
@AroundInvoke public Object operation(InvocationContext context) throws Exception { if (!config.isMetricsEnabled()) { return context.proceed(); }// w w w. j av a2 s . co m Method method = context.getMethod(); Measure measure = method.getAnnotation(Measure.class); if (measure == null) { measure = method.getDeclaringClass().getAnnotation(Measure.class); } logger.trace("Gathering metrics for: {}", context.getContextData()); String nodePrefix = config.getNodePrefix(); String defaultName = getDefaultName(context.getMethod().getDeclaringClass(), context.getMethod().getName()); List<Timer.Context> timers = Stream.of(measure.timers()).map(named -> { String name = getName(nodePrefix, named.value(), defaultName, TIMER); Timer.Context tc = metricsManager.getTimer(name).time(); logger.trace("START: {} ({})", name, tc); return tc; }).collect(Collectors.toList()); try { return context.proceed(); } catch (Exception e) { Stream.of(measure.exceptions()).forEach((named) -> { String name = getName(nodePrefix, named.value(), defaultName, EXCEPTION); Meter meter = metricsManager.getMeter(name); logger.trace("ERRORS++ {}", name); meter.mark(); }); throw e; } finally { if (timers != null) { timers.forEach(timer -> { logger.trace("STOP: {}", timer); timer.stop(); }); } Stream.of(measure.meters()).forEach((named) -> { String name = getName(nodePrefix, named.value(), defaultName, METER); Meter meter = metricsManager.getMeter(name); logger.trace("CALLS++ {}", name); meter.mark(); }); } }
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()); }// w w w . ja va2 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 */// ww w. j a v a2 s. co m @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.authz.RequiredPermissionsInterceptor.java
/** * Returns a string representation of the given invocation context so it can be displayed in messages. * * @param invocation// ww w.j av a 2 s .co m * * @return string containing information about the invocation */ private String getInvocationString(InvocationContext invocation) { StringBuffer buf = new StringBuffer("invocation: "); buf.append("method=" + invocation.getMethod().toGenericString()); buf.append(",context-data=" + invocation.getContextData()); return buf.toString(); }
From source file:org.rhq.enterprise.server.common.TransactionInterruptInterceptor.java
@AroundInvoke public Object addCheckedActionToTransactionManager(InvocationContext invocation_context) throws Exception { BasicAction currentTx = null;/*from w ww .j av a 2 s . com*/ 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
private String getMethodName(InvocationContext ctx) { return ctx.getTarget().getClass().getName() + "." + ctx.getMethod().getName(); }
From source file:org.silverpeas.core.util.annotation.AnnotationUtil.java
/** * Provides a centralized way to find the method that has been intercepted. * @param invocationContext the context of invocation. * @return the method that has been intercepted. * @throws Exception/*w ww. j a v a2s. c om*/ */ private static Method getInterceptedMethodFromContext(InvocationContext invocationContext) throws Exception { return invocationContext.getMethod(); }