Example usage for org.springframework.aop.support AopUtils getTargetClass

List of usage examples for org.springframework.aop.support AopUtils getTargetClass

Introduction

In this page you can find the example usage for org.springframework.aop.support AopUtils getTargetClass.

Prototype

public static Class<?> getTargetClass(Object candidate) 

Source Link

Document

Determine the target class of the given bean instance which might be an AOP proxy.

Usage

From source file:de.bund.bva.pliscommon.serviceapi.core.aop.StelltLoggingKontextBereitInterceptor.java

/**
 * Dieser Aspekt sorgt dafr, dass eine Korrelation-ID erzeugt wird, falls im AufrufKontext keine gesetzt
 * ist und in der Annotation angegeben ist, dass kein Aufrufkontext als Parameter bergeben wird.
 * Die Korrelation ID wird vor dem eigentlichen Aufruf im Logging-Kontext gesetzt und danach automatisch
 * wieder entfernt./*  w  w w  . j  a  v  a2 s . c o m*/
 *
 * @param invocation
 *            der Methodenaufruf
 *
 * @return das Ergebnis der eigentlichen Methode.
 * @throws Throwable
 *             wenn die eigentliche Methode einen Fehler wirft.
 */
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
    /** Die Korrelations-ID wird zur eindeutigen Identifikation von Service-Aufrufen verwendet. **/
    String korrelationsId = null;

    AufrufKontextTo aufrufKontextTo = leseAufrufKontextTo(invocation.getArguments());

    boolean nutzeAufrufKontext = false;

    Class<?> targetClass = (invocation.getThis() != null ? AopUtils.getTargetClass(invocation.getThis())
            : null);

    StelltLoggingKontextBereit stelltLoggingKontextBereit = ermittleStelltLoggingKontextBereitAnnotation(
            invocation.getMethod(), targetClass);

    if (stelltLoggingKontextBereit != null) {
        // Wenn stelltLogginKontextBereit != null ist, haben wir es mit einer annotierten Klasse zu tun.
        // Dann entscheidet die Methode nutzeAufrufKontext darber, ob AufrufKontextTo verwendet wird
        // oder nicht.
        nutzeAufrufKontext = stelltLoggingKontextBereit.nutzeAufrufKontext();
    } else {
        // Es bleibt die Frage, ob ein AufrufKontextTo ohne Annotation bergeben wurde.
        if (aufrufKontextTo != null) {
            nutzeAufrufKontext = true;
        } else {
            nutzeAufrufKontext = false;
        }
    }

    if (nutzeAufrufKontext) {
        if (aufrufKontextTo != null) {
            if (StringUtils.isEmpty(aufrufKontextTo.getKorrelationsId())) {
                LOG.warn(EreignisSchluessel.KEINE_KORRELATAIONSID_IM_AUFRUFKONTEXT_UEBERMITTELT,
                        "Es wurde keine Korrelations-ID im AufrufKontext bermittelt. Erzeuge neue Korrelations-ID.");
                korrelationsId = UUID.randomUUID().toString();
                aufrufKontextTo.setKorrelationsId(korrelationsId);
            } else {
                LOG.debug("Setze Korrelations-ID aus AufrufKontext.");
                korrelationsId = aufrufKontextTo.getKorrelationsId();
            }

        } else {
            throw new IllegalArgumentException(
                    "Die Annotation StelltLoggingKontextBereit gibt an, dass die Methode "
                            + invocation.getMethod()
                            + " einen Aufrufkontext als Parameter enthlt. Dieser Parameter ist aber null oder nicht vorhanden.");
        }
    } else {
        korrelationsId = UUID.randomUUID().toString();
        LOG.debug("Es wurde kein AufrufKontext bermittelt. Erzeuge neue Korrelations-ID.");
    }

    try {
        MdcHelper.pushKorrelationsId(korrelationsId);
        return invocation.proceed();
    } finally {
        // Nach dem Aufruf alle Korrelations-IDs vom MDC entfernen.
        MdcHelper.entferneKorrelationsIds();
    }
}

From source file:com.google.code.guice.repository.spi.CompositeTransactionInterceptor.java

@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
    // persistence unit name detection
    Class<?> targetClass = invocation.getThis() != null ? AopUtils.getTargetClass(invocation.getThis()) : null;
    TransactionAttribute txAttr = transactionAttributeSource.getTransactionAttribute(invocation.getMethod(),
            targetClass);//  www. ja v  a2s  .c o  m
    String persistenceUnitName = null;

    if (txAttr != null) {
        persistenceUnitName = txAttr.getQualifier();
    }

    PersistenceUnitConfiguration configuration = configurationManager.getConfiguration(persistenceUnitName);
    return configuration.getTransactionInterceptor().invoke(invocation);
}

From source file:fr.putnami.pwt.plugin.spring.rpc.server.service.CommandServiceImpl.java

private void scanBean(Object bean, String name) {
    Class<?> implClass = bean.getClass();
    if (AopUtils.isAopProxy(bean)) {
        implClass = AopUtils.getTargetClass(bean);
    }//from   w w  w  .j a v  a  2 s.  c  o m
    Service serviceAnnotation = AnnotationUtils.findAnnotation(implClass, Service.class);
    if (serviceAnnotation != null) {
        for (Class<?> inter : implClass.getInterfaces()) {
            this.injectService(inter, bean);
        }
    }
}

From source file:com.github.djabry.platform.vaadin.navigation.NavigationSecurity.java

private boolean isSecuredObject(Object o) {

    return this.isSecuredClass(AopUtils.getTargetClass(o));

}

From source file:hsa.awp.common.logging.DebugInterceptor.java

/**
 * Returns the {@link Logger} to be used for logging.
 *
 * @param target the target object of this method call.
 * @return the {@link Logger} to be used.
 * @see #setLogInTargetContext(boolean)//from   w w w. jav  a 2s  .co  m
 */
private Logger getLogger(Object target) {

    if (logInTargetContext) {
        return LoggerFactory.getLogger(AopUtils.getTargetClass(target));
    } else {
        return LoggerFactory.getLogger(getClass());
    }
}

From source file:org.vaadin.spring.security.provider.PreAuthorizeViewProviderAccessDelegate.java

@Override
public boolean isAccessGranted(UI ui, String beanName) {

    PreAuthorize viewSecured = applicationContext.findAnnotationOnBean(beanName, PreAuthorize.class);

    if (viewSecured == null) {
        return true;
    } else if (security.hasAccessDecisionManager()) {

        final Class<?> targetClass = AopUtils.getTargetClass(applicationContext.getBean(beanName));
        final Method method = ClassUtils.getMethod(
                AopUtils.getTargetClass(applicationContext.getBean(beanName)), "enter",
                com.vaadin.navigator.ViewChangeListener.ViewChangeEvent.class);
        final MethodInvocation methodInvocation = MethodInvocationUtils.createFromClass(targetClass,
                method.getName());/*from ww  w .  j  av  a  2 s. co m*/

        final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        final AccessDecisionManager accessDecisionManager = security.getAccessDecisionManager();
        final ExpressionBasedAnnotationAttributeFactory attributeFactory = new ExpressionBasedAnnotationAttributeFactory(
                new DefaultMethodSecurityExpressionHandler());

        Collection<ConfigAttribute> atributi = new ArrayList<ConfigAttribute>();
        atributi.add(attributeFactory.createPreInvocationAttribute(null, null, viewSecured.value()));

        try {
            accessDecisionManager.decide(authentication, methodInvocation, atributi);
            return true;
        } catch (InsufficientAuthenticationException e) {
            return false;
        } catch (AccessDeniedException e) {
            return false;
        }

    } else {
        return true; // Access decision manager required for @PreAuthorize()
    }

}

From source file:com.joshlong.activiti.coordinator.aop.ActivitiStateAnnotationBeanPostProcessor.java

public Object postProcessAfterInitialization(final Object bean, final String beanName) throws BeansException {
    // first sift through and get all the methods
    // then get all the annotations
    // then build the metadata and register the metadata
    final Class<?> targetClass = AopUtils.getTargetClass(bean);
    final ActivitiComponent component = targetClass.getAnnotation(ActivitiComponent.class);

    ReflectionUtils.doWithMethods(targetClass, new ReflectionUtils.MethodCallback() {
        @SuppressWarnings("unchecked")
        public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {

            ActivitiState activitiState = AnnotationUtils.getAnnotation(method, ActivitiState.class);

            String processName = component.processKey();

            if (StringUtils.hasText(activitiState.processName())) {
                processName = activitiState.processName();
            }//from w ww.ja va  2s.  c o  m

            String stateName = activitiState.stateName();

            if (!StringUtils.hasText(stateName)) {
                stateName = activitiState.value();
            }

            Assert.notNull(stateName, "You must provide a stateName!");

            Map<Integer, String> vars = new HashMap<Integer, String>();
            Annotation[][] paramAnnotationsArray = method.getParameterAnnotations();

            int ctr = 0;
            int pvMapIndex = -1;
            int procIdIndex = -1;

            for (Annotation[] paramAnnotations : paramAnnotationsArray) {
                ctr += 1;

                for (Annotation pa : paramAnnotations) {
                    if (pa instanceof ProcessVariable) {
                        ProcessVariable pv = (ProcessVariable) pa;
                        String pvName = pv.value();
                        vars.put(ctr, pvName);
                    } else if (pa instanceof ProcessVariables) {
                        pvMapIndex = ctr;
                    } else if (pa instanceof ProcessId) {
                        procIdIndex = ctr;
                    }
                }
            }

            ActivitiStateHandlerRegistration registration = new ActivitiStateHandlerRegistration(vars, method,
                    bean, stateName, beanName, pvMapIndex, procIdIndex, processName);
            registry.registerActivitiStateHandler(registration);
        }
    }, new ReflectionUtils.MethodFilter() {
        public boolean matches(Method method) {
            return null != AnnotationUtils.getAnnotation(method, ActivitiState.class);
        }
    });

    return bean;
}

From source file:org.springjutsu.validation.executors.RuleExecutorContainer.java

/**
 * Finds the annotated rule executors by searching the bean factory.
 * Also registers XML-configured rule executors.
 * @throws BeansException on a bad./*from ww w  .  j  av a  2s.  c o m*/
 */
@PostConstruct
public void registerRuleExecutors() throws BeansException {
    if (addDefaultRuleExecutors) {
        addDefaultRuleExecutors();
    }
    Map<String, Object> ruleExecutorBeans = ((ListableBeanFactory) beanFactory)
            .getBeansWithAnnotation(ConfiguredRuleExecutor.class);

    for (String springName : ruleExecutorBeans.keySet()) {
        RuleExecutor<?, ?> ruleExecutor = (RuleExecutor<?, ?>) ruleExecutorBeans.get(springName);
        String ruleName = AnnotationUtils
                .findAnnotation(AopUtils.getTargetClass(ruleExecutor), ConfiguredRuleExecutor.class).name();
        setCustomRuleExecutor(ruleName, ruleExecutor);
    }
    if (beanRegistrants != null) {
        for (KeyedBeanRegistrant registrant : beanRegistrants) {
            setCustomRuleExecutor(registrant.getKey(),
                    (RuleExecutor<?, ?>) beanFactory.getBean(registrant.getBeanName()));
        }
    }
}

From source file:org.activiti.spring.components.aop.ActivitiStateAnnotationBeanPostProcessor.java

public Object postProcessAfterInitialization(final Object bean, final String beanName) throws BeansException {
    // first sift through and get all the methods
    // then get all the annotations
    // then build the metadata and register the metadata
    final Class<?> targetClass = AopUtils.getTargetClass(bean);
    final org.activiti.spring.annotations.ActivitiComponent component = targetClass
            .getAnnotation(org.activiti.spring.annotations.ActivitiComponent.class);

    ReflectionUtils.doWithMethods(targetClass, new ReflectionUtils.MethodCallback() {
        @SuppressWarnings("unchecked")
        public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {

            State state = AnnotationUtils.getAnnotation(method, State.class);

            String processName = component.processKey();

            if (StringUtils.hasText(state.process())) {
                processName = state.process();
            }/*  www .  j  a va  2  s.  co  m*/

            String stateName = state.state();

            if (!StringUtils.hasText(stateName)) {
                stateName = state.value();
            }

            Assert.notNull(stateName, "You must provide a stateName!");

            Map<Integer, String> vars = new HashMap<Integer, String>();
            Annotation[][] paramAnnotationsArray = method.getParameterAnnotations();

            int ctr = 0;
            int pvMapIndex = -1;
            int procIdIndex = -1;

            for (Annotation[] paramAnnotations : paramAnnotationsArray) {
                ctr += 1;

                for (Annotation pa : paramAnnotations) {
                    if (pa instanceof ProcessVariable) {
                        ProcessVariable pv = (ProcessVariable) pa;
                        String pvName = pv.value();
                        vars.put(ctr, pvName);
                    } else if (pa instanceof ProcessVariables) {
                        pvMapIndex = ctr;
                    } else if (pa instanceof ProcessId) {
                        procIdIndex = ctr;
                    }
                }
            }

            ActivitiStateHandlerRegistration registration = new ActivitiStateHandlerRegistration(vars, method,
                    bean, stateName, beanName, pvMapIndex, procIdIndex, processName);
            registry.registerActivitiStateHandler(registration);
        }
    }, new ReflectionUtils.MethodFilter() {
        public boolean matches(Method method) {
            return null != AnnotationUtils.getAnnotation(method, State.class);
        }
    });

    return bean;
}

From source file:org.vaadin.spring.security.navigation.PreAuthorizeViewInstanceAccessControl.java

@Override
public boolean isAccessGranted(UI ui, String beanName, View view) {
    final PreAuthorize viewSecured = applicationContext.findAnnotationOnBean(beanName, PreAuthorize.class);

    if (viewSecured == null) {
        logger.trace("No @PreAuthorize annotation found on view {}. Granting access.", beanName);
        return true;
    } else if (security.hasAccessDecisionManager()) {
        final Class<?> targetClass = AopUtils.getTargetClass(view);
        final Method method = ClassUtils.getMethod(targetClass, "enter",
                com.vaadin.navigator.ViewChangeListener.ViewChangeEvent.class);
        final MethodInvocation methodInvocation = MethodInvocationUtils.createFromClass(targetClass,
                method.getName());//www.  j a  va  2 s .  c  o m

        final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        final AccessDecisionManager accessDecisionManager = security.getAccessDecisionManager();
        final ExpressionBasedAnnotationAttributeFactory attributeFactory = new ExpressionBasedAnnotationAttributeFactory(
                new DefaultMethodSecurityExpressionHandler());

        final Collection<ConfigAttribute> attributes = Collections.singleton((ConfigAttribute) attributeFactory
                .createPreInvocationAttribute(null, null, viewSecured.value()));

        try {
            accessDecisionManager.decide(authentication, methodInvocation, attributes);
            logger.trace("Access to view {} was granted by access decision manager", beanName);
            return true;
        } catch (InsufficientAuthenticationException e) {
            logger.trace("Access to view {} was denied because of insufficient authentication credentials",
                    beanName);
            return false;
        } catch (AccessDeniedException e) {
            logger.trace("Access to view {} was denied", beanName);
            return false;
        }
    } else {
        logger.warn(
                "Found view {} annotated with @PreAuthorize but no access decision manager. Granting access.",
                beanName);
        return true;
    }
}