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:fr.mby.utils.spring.aop.support.AopHelper.java

/**
 * Test if an object which implement or extend a parameterized object will be able to handle a specific type.
 * Example : NumberList implements List<Number> { ... } NumberList can store any subtypes of Number : Number,
 * Integer, Long, ... This method return true if called like this supportsType(numberList, Integer.class,
 * List.class) This method return false if called like this supportsType(numberList, String.class, List.class)
 * /*  w  ww .  j a  v a  2s  .c o m*/
 * @param object
 *            the instantiated object we want to test against
 * @param type
 *            the type we want to test if the object can hanldle
 * @param genericIfc
 *            the type of the parameterized object (not the parameter type)
 * @return true if the object implementing the genericIfc supports the specified type
 */
public static <T> boolean supportsType(final Object object, final Class<?> type, final Class<?> genericIfc) {
    Class<?> typeArg = GenericTypeResolver.resolveTypeArgument(object.getClass(), genericIfc);
    if (typeArg == null || typeArg.equals(genericIfc)) {
        final Class<?> targetClass = AopUtils.getTargetClass(object);
        if (targetClass != object.getClass()) {
            typeArg = GenericTypeResolver.resolveTypeArgument(targetClass, genericIfc);
        }
    }

    final boolean test = typeArg == null || typeArg.isAssignableFrom(type);

    final String logMsg;
    if (test) {
        logMsg = "[{}] supports type: [{}] for genericIfc [{}].";
    } else {
        logMsg = "[{}] doesn't support type: [{}] for genericIfc [{}].";
    }

    AopHelper.LOG.debug(logMsg, object.getClass().getSimpleName(), type.getSimpleName(),
            genericIfc.getSimpleName());

    return test;
}

From source file:com.taobao.ad.easyschedule.interceptor.SecurityInterceptor.java

@SuppressWarnings("unchecked")
private Boolean checkAuth(ActionInvocation invocation, List<Integer> featureList)
        throws AuthException, Exception {
    Class action = AopUtils.getTargetClass(invocation.getAction());
    Method targetMethod = action.getMethod(invocation.getProxy().getMethod(), null);
    if (!securityBean.hasAccess(featureList, targetMethod)) {
        return false;
    }//w  w  w  .  j  a  va 2  s.  co m
    return true;
}

From source file:org.langera.freud.optional.spring.SpringBeanImpl.java

public Class getTargetClass() {
    return AopUtils.getTargetClass(bean);
}

From source file:com.ryantenney.metrics.spring.GaugeAnnotationBeanPostProcessor.java

@Override
public Object postProcessAfterInitialization(final Object bean, String beanName) {
    final Class<?> targetClass = AopUtils.getTargetClass(bean);

    ReflectionUtils.doWithFields(targetClass, new FieldCallback() {
        @Override//from   w ww .j  ava  2 s . c o  m
        public void doWith(final Field field) throws IllegalAccessException {
            ReflectionUtils.makeAccessible(field);

            final Gauge annotation = field.getAnnotation(Gauge.class);
            final String metricName = Util.forGauge(targetClass, field, annotation);

            metrics.register(metricName, new com.codahale.metrics.Gauge<Object>() {
                @Override
                public Object getValue() {
                    Object value = ReflectionUtils.getField(field, bean);
                    if (value instanceof com.codahale.metrics.Gauge) {
                        value = ((com.codahale.metrics.Gauge<?>) value).getValue();
                    }
                    return value;
                }
            });

            LOG.debug("Created gauge {} for field {}.{}", metricName, targetClass.getCanonicalName(),
                    field.getName());
        }
    }, FILTER);

    ReflectionUtils.doWithMethods(targetClass, new MethodCallback() {
        @Override
        public void doWith(final Method method) throws IllegalAccessException {
            if (method.getParameterTypes().length > 0) {
                throw new IllegalStateException(
                        "Method " + method.getName() + " is annotated with @Gauge but requires parameters.");
            }

            final Gauge annotation = method.getAnnotation(Gauge.class);
            final String metricName = Util.forGauge(targetClass, method, annotation);

            metrics.register(metricName, new com.codahale.metrics.Gauge<Object>() {
                @Override
                public Object getValue() {
                    return ReflectionUtils.invokeMethod(method, bean);
                }
            });

            LOG.debug("Created gauge {} for method {}.{}", metricName, targetClass.getCanonicalName(),
                    method.getName());
        }
    }, FILTER);

    return bean;
}

From source file:com.watchrabbit.executor.spring.ExecutorAnnotationBeanPostProcessor.java

@Override
public Object postProcessAfterInitialization(final Object bean, String beanName) {
    LOGGER.debug("Processing bean: {}", beanName);
    Class<?> targetClass = AopUtils.getTargetClass(bean);

    Executor classAnnotation = findClassAnnotation(targetClass);

    Map<Method, Executor> annotatedMethods = findAnnotatedMethods(targetClass);

    if (classAnnotation != null || !annotatedMethods.isEmpty()) {
        LOGGER.debug("Bean: {} is annotated with @Executor, creating proxy", beanName);
        return createProxy(targetClass, classAnnotation, annotatedMethods, bean).create();
    }//from  w  ww  .  j a v a2 s  .  c  o  m
    return bean;
}

From source file:guru.qas.martini.annotation.StepsAnnotationProcessorTest.java

@Test
public void testPostProcessAfterInitialization() throws IOException, NoSuchMethodException {
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    TestSteps steps = context.getBean(TestSteps.class);

    Class<?> wrapped = AopUtils.getTargetClass(steps);
    Method method = wrapped.getMethod("anotherStep", String.class);

    Map<String, StepImplementation> givenBeanIndex = context.getBeansOfType(StepImplementation.class);
    Collection<StepImplementation> givens = givenBeanIndex.values();

    List<StepImplementation> matches = Lists.newArrayList();
    for (StepImplementation given : givens) {
        Method givenMethod = given.getMethod();
        if (givenMethod.equals(method)) {
            matches.add(given);/* w  w  w . j a v  a 2s.  c  o m*/
        }
    }

    int count = matches.size();
    assertEquals(count, 1, "wrong number of GivenStep objects registered for TestSteps.anotherStep()");

    StepImplementation match = matches.get(0);
    Pattern pattern = match.getPattern();
    Matcher matcher = pattern.matcher("another \"(.+)\" here");
    assertTrue(matcher.find(), "expected Pattern to match Gherkin regular expression");
    assertEquals(matcher.groupCount(), 1, "wrong number of parameters captured for TestSteps.anotherStep()");
}

From source file:demo.lifecycle.SmartLifecycleRegistry.java

@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
    Class<?> targetClass = AopUtils.getTargetClass(bean);
    ReflectionUtils.doWithMethods(targetClass, new MethodCallback() {
        @Override//from www  . jav  a2  s. c  o  m
        public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
            Start start = AnnotationUtils.getAnnotation(method, Start.class);
            if (start != null) {
                processStart(beanName, start, method, bean);
            }
        }

    });
    return bean;
}

From source file:com.ryantenney.metrics.spring.InjectMetricAnnotationBeanPostProcessor.java

@Override
public Object postProcessAfterInitialization(final Object bean, String beanName) {
    final Class<?> targetClass = AopUtils.getTargetClass(bean);

    ReflectionUtils.doWithFields(targetClass, new FieldCallback() {
        @Override/*from  www. j  a v a2 s.  c  o  m*/
        public void doWith(Field field) throws IllegalAccessException {
            final InjectMetric annotation = field.getAnnotation(InjectMetric.class);
            final String metricName = Util.forInjectMetricField(targetClass, field, annotation);

            final Class<?> type = field.getType();
            Metric metric = null;
            if (Meter.class == type) {
                metric = metrics.meter(metricName);
            } else if (Timer.class == type) {
                metric = metrics.timer(metricName);
            } else if (Counter.class == type) {
                metric = metrics.counter(metricName);
            } else if (Histogram.class == type) {
                metric = metrics.histogram(metricName);
            } else {
                throw new IllegalStateException("Cannot inject a metric of type " + type.getCanonicalName());
            }

            ReflectionUtils.makeAccessible(field);
            ReflectionUtils.setField(field, bean, metric);

            LOG.debug("Injected metric {} for field {}.{}", metricName, targetClass.getCanonicalName(),
                    field.getName());
        }
    }, FILTER);

    return bean;
}

From source file:com.dangdang.ddframe.job.spring.schedule.SpringJobFactory.java

@Override
public Job newJob(final TriggerFiredBundle bundle, final Scheduler scheduler) throws SchedulerException {
    Preconditions.checkNotNull(applicationContext,
            "applicationContext cannot be null, should call setApplicationContext first.");
    Job job = null;//from w w w  .  j a  v  a 2  s.c o  m
    try {
        for (Job each : applicationContext.getBeansOfType(Job.class).values()) {
            if (AopUtils.getTargetClass(each) == bundle.getJobDetail().getJobClass()) {
                job = each;
                break;
            }
        }
        if (ScriptElasticJob.class == bundle.getJobDetail().getJobClass()) {
            return super.newJob(bundle, scheduler);
        }
        if (null == job) {
            throw new NoSuchBeanDefinitionException("");
        }
    } catch (final BeansException ex) {
        log.info("Elastic job: cannot found bean for class: '{}'. This job is not managed for spring.",
                bundle.getJobDetail().getJobClass().getCanonicalName());
        return super.newJob(bundle, scheduler);
    }
    JobDataMap jobDataMap = new JobDataMap();
    jobDataMap.putAll(scheduler.getContext());
    jobDataMap.putAll(bundle.getJobDetail().getJobDataMap());
    jobDataMap.putAll(bundle.getTrigger().getJobDataMap());
    Job target = (Job) AopTargetUtils.getTarget(job);
    setBeanProps(target, jobDataMap);
    return target;
}

From source file:fr.putnami.pwt.plugin.spring.web.filter.DelegatingChainFilter.java

private void scanBean(Object bean, String name) {
    Class<?> implClass = bean.getClass();
    if (AopUtils.isAopProxy(bean)) {
        implClass = AopUtils.getTargetClass(bean);
    }//  w  w  w.jav  a 2 s . c  o m
    if (Filter.class.isAssignableFrom(implClass)) {
        filters.add((Filter) bean);
    }
}