@Override
  public Object postProcessAfterInitialization(final Object bean, final String beanName)
      throws BeansException {
    Class<?> targetClass = AopUtils.getTargetClass(bean);
    final RabbitListener classLevelListener =
        AnnotationUtils.findAnnotation(bean.getClass(), RabbitListener.class);
    final List<Method> multiMethods = new ArrayList<Method>();
    ReflectionUtils.doWithMethods(
        targetClass,
        new ReflectionUtils.MethodCallback() {

          @Override
          public void doWith(Method method)
              throws IllegalArgumentException, IllegalAccessException {
            RabbitListener rabbitListener =
                AnnotationUtils.getAnnotation(method, RabbitListener.class);
            if (rabbitListener != null) {
              processAmqpListener(rabbitListener, method, bean, beanName);
            }
            if (classLevelListener != null) {
              RabbitHandler rabbitHandler =
                  AnnotationUtils.getAnnotation(method, RabbitHandler.class);
              if (rabbitHandler != null) {
                multiMethods.add(method);
              }
            }
          }
        });
    if (classLevelListener != null) {
      processMultiMethodListener(classLevelListener, multiMethods, bean, beanName);
    }
    return bean;
  }
 private Class<?> getTargetClass(Object targetObject) {
   Class<?> targetClass = targetObject.getClass();
   if (AopUtils.isAopProxy(targetObject)) {
     targetClass = AopUtils.getTargetClass(targetObject);
     if (targetClass == targetObject.getClass()) {
       try {
         // Maybe a proxy with no target - e.g. gateway
         Class<?>[] interfaces = ((Advised) targetObject).getProxiedInterfaces();
         if (interfaces != null && interfaces.length == 1) {
           targetClass = interfaces[0];
         }
       } catch (Exception e) {
         if (logger.isDebugEnabled()) {
           logger.debug("Exception trying to extract interface", e);
         }
       }
     }
   } else if (org.springframework.util.ClassUtils.isCglibProxyClass(targetClass)) {
     Class<?> superClass = targetObject.getClass().getSuperclass();
     if (!Object.class.equals(superClass)) {
       targetClass = superClass;
     }
   }
   return targetClass;
 }
  @Override
  public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
    Method[] methods = AopUtils.getTargetClass(bean).getDeclaredMethods();
    for (Method method : methods) {
      if (method.isAnnotationPresent(MethodLimiter.class)) {
        MethodLimiter methodLimiter = method.getAnnotation(MethodLimiter.class);
        // 获取zkclient
        ZKClusterClient client =
            ZookeeperClientMakerFactory.getInstance().getZKClusterClient("zkClient");
        String name = methodLimiter.name();
        int rate = methodLimiter.rate();
        // 创建rateLimiter
        RateLimiterFactory.getInstance().putIfAbsent(name, new RateLimiter().create(name, rate));
        String path = PATH_PREFIX + "/" + name;
        if (!client.isExsit(path)) {
          // 创建节点
          client.createNode(
              path, String.valueOf(rate), com.foxxy.git.zookeeper.CreateMode.PERSISTENT);
        }
        client.registerConnectionListener(new LimiterRateMonitorListener(path));

        client.registerNodeListener(path, new LimiterRateMonitorListener(path));
      }
    }
    return bean;
  }
 @Override
 public Object postProcessAfterInitialization(final Object bean, String beanName) {
   if (!this.nonAnnotatedClasses.contains(bean.getClass())) {
     final Set<Method> annotatedMethods = new LinkedHashSet<Method>(1);
     Class<?> targetClass = AopUtils.getTargetClass(bean);
     ReflectionUtils.doWithMethods(
         targetClass,
         new MethodCallback() {
           @Override
           public void doWith(Method method)
               throws IllegalArgumentException, IllegalAccessException {
             for (Scheduled scheduled :
                 AnnotationUtils.getRepeatableAnnotation(
                     method, Schedules.class, Scheduled.class)) {
               processScheduled(scheduled, method, bean);
               annotatedMethods.add(method);
             }
           }
         });
     if (annotatedMethods.isEmpty()) {
       this.nonAnnotatedClasses.add(bean.getClass());
     }
   }
   return bean;
 }
 private void prepareEvaluationContext(
     StandardEvaluationContext context,
     Object method,
     Class<? extends Annotation> annotationType) {
   Class<?> targetType = AopUtils.getTargetClass(this.targetObject);
   if (method instanceof Method) {
     context.registerMethodFilter(targetType, new FixedMethodFilter((Method) method));
     if (expectedType != null) {
       Assert.state(
           context
               .getTypeConverter()
               .canConvert(
                   TypeDescriptor.valueOf(((Method) method).getReturnType()),
                   TypeDescriptor.valueOf(expectedType)),
           "Cannot convert to expected type (" + expectedType + ") from " + method);
     }
   } else if (method == null || method instanceof String) {
     AnnotatedMethodFilter filter =
         new AnnotatedMethodFilter(annotationType, (String) method, this.requiresReply);
     Assert.state(
         canReturnExpectedType(filter, targetType, context.getTypeConverter()),
         "Cannot convert to expected type (" + expectedType + ") from " + method);
     context.registerMethodFilter(targetType, filter);
   }
   context.setVariable("target", targetObject);
 }
  public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
    if (bean instanceof AopInfrastructureBean) {
      // Ignore AOP infrastructure such as scoped proxies.
      return bean;
    }

    Class<?> targetClass = AopUtils.getTargetClass(bean);
    if (targetClass == null) {
      // Can't do much here.
      return bean;
    }

    if (AopUtils.canApply(this.asyncAnnotationAdvisor, targetClass)) {
      if (bean instanceof Advised) {
        ((Advised) bean).addAdvisor(this.asyncAnnotationAdvisor);
        return bean;
      } else {
        ProxyFactory proxyFactory = new ProxyFactory(bean);
        // Copy our properties (proxyTargetClass etc) inherited from ProxyConfig.
        proxyFactory.copyFrom(this);
        proxyFactory.addAdvisor(this.asyncAnnotationAdvisor);
        return proxyFactory.getProxy(this.beanClassLoader);
      }
    } else {
      // No async proxy needed.
      return bean;
    }
  }
  /**
   * Intercept the given method invocation, submit the actual calling of the method to the correct
   * task executor and return immediately to the caller.
   *
   * @param invocation the method to intercept and make asynchronous
   * @return {@link Future} if the original method returns {@code Future}; {@code null} otherwise.
   */
  public Object invoke(final MethodInvocation invocation) throws Throwable {
    Class<?> targetClass =
        (invocation.getThis() != null ? AopUtils.getTargetClass(invocation.getThis()) : null);
    Method specificMethod = ClassUtils.getMostSpecificMethod(invocation.getMethod(), targetClass);
    specificMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);

    Future<?> result =
        determineAsyncExecutor(specificMethod)
            .submit(
                new Callable<Object>() {
                  public Object call() throws Exception {
                    try {
                      Object result = invocation.proceed();
                      if (result instanceof Future) {
                        return ((Future<?>) result).get();
                      }
                    } catch (Throwable ex) {
                      ReflectionUtils.rethrowException(ex);
                    }
                    return null;
                  }
                });

    if (Future.class.isAssignableFrom(invocation.getMethod().getReturnType())) {
      return result;
    } else {
      return null;
    }
  }
  public static Class<?> getGenericTypeFromBean(Object object) {
    Class<?> clazz = object.getClass();

    if (AopUtils.isAopProxy(object)) {
      clazz = AopUtils.getTargetClass(object);
    }
    return getGenericType(clazz);
  }
  /** {@InheritDoc} */
  @Override
  public List<BeanDetail> getBeanDetails() {

    if (this.allBeans == null) {

      // initialize BeanDetail list
      List<BeanDetail> beans = new ArrayList<BeanDetail>();
      BeanDetail springBeanDetail;

      // get the list of bean names
      List<String> names = this.getBeanNames();

      for (String beanName : names) {
        springBeanDetail = new BeanDetail();
        springBeanDetail.setBeanName(beanName);

        Object bean;
        String beanType;

        springBeanDetail.setAliases(Arrays.asList(this.ctx.getAliases(beanName)));
        bean = this.ctx.getBean(beanName);
        beanType = bean.getClass().getName();

        // Manage proxied beans
        // If the bean is proxied then its type is modiified. We
        // detect
        // it and get the correct target type
        if (AopUtils.isAopProxy(bean)) {
          beanType = AopUtils.getTargetClass(bean).getName();
          springBeanDetail.setProxied(true);
        }

        springBeanDetail.setBeanType(beanType);
        springBeanDetail.setPrototype(this.ctx.isPrototype(beanName));
        springBeanDetail.setSingleton(this.ctx.isSingleton(beanName));
        springBeanDetail.setBean(this.ctx.getBean(beanName));

        if (this.configurablebeanFactory != null) {

          BeanDefinition beanDefinition = this.configurablebeanFactory.getBeanDefinition(beanName);
          springBeanDetail.setBeanType(beanDefinition.getBeanClassName());
          springBeanDetail.setDescription(beanDefinition.getDescription());
          springBeanDetail.setScope(beanDefinition.getScope());
          springBeanDetail.setLazyInit(beanDefinition.isLazyInit());
          springBeanDetail.setAbstract(beanDefinition.isAbstract());
        }
        beans.add(springBeanDetail);
      }
      this.allBeans = beans;
    }

    return this.allBeans;
  }
Esempio n. 10
0
 /**
  * Determine if a given {@link FacesWrapperFactory} is suitable by resolving generic arguments.
  *
  * @param factory the factory to test
  * @return <tt>true</tt> if the <tt>factory</tt> is supported, otherwise <tt>false</tt>
  */
 @SuppressWarnings({"rawtypes", "unchecked"})
 private boolean isFactorySupported(FacesWrapperFactory factory) {
   Class typeArg =
       GenericTypeResolver.resolveTypeArgument(factory.getClass(), FacesWrapperFactory.class);
   if (typeArg == null) {
     Class targetClass = AopUtils.getTargetClass(factory);
     if (targetClass != factory.getClass()) {
       typeArg = GenericTypeResolver.resolveTypeArgument(targetClass, FacesWrapperFactory.class);
     }
   }
   return (typeArg == null || typeArg.isAssignableFrom(this.typeClass));
 }
  @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());

      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;
    }
  }
  @SuppressWarnings("deprecation")
  public void getNonAnnotatedTransactionalServices() {
    /* We only want to run getNonAnnotatedTransactionalSerivces once.
     * The tests actually just read the Maps that are generated here.
     */
    if (incorrectlyAnnotatedTransactionalServices != null) {
      return;
    }
    incorrectlyAnnotatedTransactionalServices = new HashMap<String, Class<? extends Object>>();
    nonAnnotatedTransactionalServices = new HashMap<String, String>();
    doubleAnnotatedTransactionalServices = new HashMap<String, String>();

    String[] beanNames = SpringContext.getBeanNames();
    for (String beanName : beanNames) {
      if (beanName.endsWith("-parentBean")) {
        continue;
      }
      Object bean = null;
      try {
        bean = SpringContext.getBean(beanName);
      } catch (BeanIsAbstractException ex) {
        // do nothing, ignore
      } catch (Exception e) {
        LOG.warn("Caught exception while trying to obtain service: " + beanName);
        LOG.warn(e.getClass().getName() + " : " + e.getMessage(), e);
      }
      if (bean != null) {
        Class<? extends Object> beanClass = bean.getClass();
        if (beanClass.getName().matches(".*\\$Proxy.*")) {
          beanClass = AopUtils.getTargetClass(bean);
        }
        if (beanClass.getName().startsWith("org.kuali")
            && !Modifier.isAbstract(beanClass.getModifiers())
            && !beanClass.getName().endsWith("DaoOjb")
            && !beanClass.getName().endsWith("DaoJdbc")
            && !beanClass.getName().endsWith("Factory")
            && !beanClass.getName().contains("Lookupable")
            && !isClassAnnotated(beanName, beanClass)) {
          incorrectlyAnnotatedTransactionalServices.put(beanName, beanClass);
        }
      }
    }
    return;
  }
 private Object applyAdvice(Object bean, PointcutAdvisor advisor, ClassLoader beanClassLoader) {
   Class<?> targetClass = AopUtils.getTargetClass(bean);
   if (AopUtils.canApply(advisor.getPointcut(), targetClass)) {
     if (bean instanceof Advised) {
       ((Advised) bean).addAdvisor(advisor);
       return bean;
     } else {
       ProxyFactory proxyFactory = new ProxyFactory(bean);
       proxyFactory.addAdvisor(advisor);
       /**
        * N.B. it's not a good idea to use proxyFactory.setProxyTargetClass(true) here because it
        * forces all the integration components to be cglib proxyable (i.e. have a default
        * constructor etc.), which they are not in general (usually for good reason).
        */
       return proxyFactory.getProxy(beanClassLoader);
     }
   }
   return bean;
 }
 @Override
 public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
   if (bean == null) {
     return bean;
   }
   Class beanClass = AopUtils.getTargetClass(bean);
   if (beanClass == null) {
     return bean;
   }
   RemotingService remotingService =
       AnnotationUtils.findAnnotation(beanClass, RemotingService.class);
   if (remotingService != null) {
     SpaceRemotingServiceExporter exporter;
     if (StringUtils.hasLength(remotingService.exporter())) {
       exporter =
           (SpaceRemotingServiceExporter) applicationContext.getBean(remotingService.exporter());
       if (exporter == null) {
         throw new IllegalArgumentException(
             "Failed to find exporter under name ["
                 + remotingService.exporter()
                 + "] for bean ["
                 + beanName
                 + "]");
       }
     } else {
       Map exporters = applicationContext.getBeansOfType(SpaceRemotingServiceExporter.class);
       if (exporters.isEmpty()) {
         throw new IllegalArgumentException(
             "No service exporters are defined within the context, can't register remote service bean ["
                 + beanName
                 + "]");
       }
       if (exporters.size() > 1) {
         throw new IllegalStateException(
             "More than one service exporter are defined within the context, please specify the exact service exported to register with");
       }
       exporter = (SpaceRemotingServiceExporter) exporters.values().iterator().next();
     }
     exporter.addService(beanName, bean);
   }
   return bean;
 }
 public void setRepositories(Collection<CrudRepository> repositories) {
   for (CrudRepository repository : repositories) {
     Class<?> repoClass = AopUtils.getTargetClass(repository);
     Field infoField = ReflectionUtils.findField(repoClass, "entityInformation");
     ReflectionUtils.makeAccessible(infoField);
     Method m = ReflectionUtils.findMethod(repository.getClass(), "getTargetSource");
     ReflectionUtils.makeAccessible(m);
     try {
       SingletonTargetSource targetRepo = (SingletonTargetSource) m.invoke(repository);
       EntityInformation entityInfo = (EntityInformation) infoField.get(targetRepo.getTarget());
       Class<?>[] intfs = repository.getClass().getInterfaces();
       String name =
           StringUtils.uncapitalize(intfs[0].getSimpleName().replaceAll("Repository", ""));
       this.repositories.put(
           entityInfo.getJavaType(), new RepositoryCacheEntry(name, repository, entityInfo, null));
     } catch (Throwable t) {
       throw new IllegalStateException(t);
     }
   }
 }
 @Test
 public void testDefaultConfiguration() {
   this.context = new AnnotationConfigEmbeddedWebApplicationContext();
   this.context.register(
       AuthorizationAndResourceServerConfiguration.class, MinimalSecureWebApplication.class);
   this.context.refresh();
   this.context.getBean(AUTHORIZATION_SERVER_CONFIG);
   this.context.getBean(RESOURCE_SERVER_CONFIG);
   this.context.getBean(OAuth2MethodSecurityConfiguration.class);
   ClientDetails config = this.context.getBean(BaseClientDetails.class);
   AuthorizationEndpoint endpoint = this.context.getBean(AuthorizationEndpoint.class);
   UserApprovalHandler handler =
       (UserApprovalHandler) ReflectionTestUtils.getField(endpoint, "userApprovalHandler");
   ClientDetailsService clientDetailsService = this.context.getBean(ClientDetailsService.class);
   ClientDetails clientDetails = clientDetailsService.loadClientByClientId(config.getClientId());
   assertThat(AopUtils.isJdkDynamicProxy(clientDetailsService), equalTo(true));
   assertThat(
       AopUtils.getTargetClass(clientDetailsService).getName(),
       equalTo(ClientDetailsService.class.getName()));
   assertThat(handler instanceof ApprovalStoreUserApprovalHandler, equalTo(true));
   assertThat(clientDetails, equalTo(config));
   verifyAuthentication(config);
 }
  /**
   * Finds the annotated rule executors by searching the bean factory. Also registers XML-configured
   * rule executors.
   *
   * @throws BeansException on a bad.
   */
  @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()));
      }
    }
  }
  @Override
  public boolean postProcessAfterInstantiation(final Object bean, String beanName)
      throws BeansException {
    Class beanClass = AopUtils.getTargetClass(bean);
    if (beanClass == null) {
      return true;
    }
    ReflectionUtils.doWithFields(
        beanClass,
        new ReflectionUtils.FieldCallback() {
          public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
            ExecutorScriptingExecutor executorScriptingExecutor =
                field.getAnnotation(ExecutorScriptingExecutor.class);
            if (executorScriptingExecutor != null) {
              ExecutorSpaceRemotingProxyFactoryBean factoryBean =
                  new ExecutorSpaceRemotingProxyFactoryBean();
              factoryBean.setGigaSpace(findGigaSpaceByName(executorScriptingExecutor.gigaSpace()));
              factoryBean.setTimeout(executorScriptingExecutor.timeout());
              factoryBean.setMetaArgumentsHandler(new ScriptingMetaArgumentsHandler());
              factoryBean.setRemoteInvocationAspect(new LazyLoadingRemoteInvocationAspect());
              factoryBean.setRemoteRoutingHandler(new ScriptingRemoteRoutingHandler());
              factoryBean.setServiceInterface(ScriptingExecutor.class);
              factoryBean.afterPropertiesSet();
              field.setAccessible(true);
              field.set(bean, factoryBean.getObject());
            }
            EventDrivenScriptingExecutor eventDrivenScriptingExecutor =
                field.getAnnotation(EventDrivenScriptingExecutor.class);
            if (eventDrivenScriptingExecutor != null) {
              EventDrivenSpaceRemotingProxyFactoryBean factoryBean =
                  new EventDrivenSpaceRemotingProxyFactoryBean();
              factoryBean.setTimeout(eventDrivenScriptingExecutor.timeout());
              factoryBean.setFifo(eventDrivenScriptingExecutor.fifo());
              factoryBean.setGigaSpace(
                  findGigaSpaceByName(eventDrivenScriptingExecutor.gigaSpace()));
              factoryBean.setMetaArgumentsHandler(new ScriptingMetaArgumentsHandler());
              factoryBean.setRemoteInvocationAspect(new LazyLoadingRemoteInvocationAspect());
              factoryBean.setRemoteRoutingHandler(new ScriptingRemoteRoutingHandler());
              factoryBean.setServiceInterface(ScriptingExecutor.class);
              factoryBean.afterPropertiesSet();
              field.setAccessible(true);
              field.set(bean, factoryBean.getObject());
            }
            EventDrivenProxy eventDrivenProxy = field.getAnnotation(EventDrivenProxy.class);
            if (eventDrivenProxy != null) {
              EventDrivenSpaceRemotingProxyFactoryBean factoryBean =
                  new EventDrivenSpaceRemotingProxyFactoryBean();
              factoryBean.setTimeout(eventDrivenProxy.timeout());
              factoryBean.setFifo(eventDrivenProxy.fifo());
              factoryBean.setGigaSpace(findGigaSpaceByName(eventDrivenProxy.gigaSpace()));
              factoryBean.setAsyncMethodPrefix(eventDrivenProxy.asyncMethodPrefix());
              factoryBean.setMetaArgumentsHandler(
                  (MetaArgumentsHandler)
                      createByClassOrFindByName(
                          applicationContext,
                          eventDrivenProxy.metaArgumentsHandler(),
                          eventDrivenProxy.metaArgumentsHandlerType()));
              factoryBean.setRemoteInvocationAspect(
                  (RemoteInvocationAspect)
                      createByClassOrFindByName(
                          applicationContext,
                          eventDrivenProxy.remoteInvocationAspect(),
                          eventDrivenProxy.remoteInvocationAspectType()));
              factoryBean.setRemoteRoutingHandler(
                  (RemoteRoutingHandler)
                      createByClassOrFindByName(
                          applicationContext,
                          eventDrivenProxy.remoteRoutingHandler(),
                          eventDrivenProxy.remoteRoutingHandlerType()));
              factoryBean.setServiceInterface(field.getType());
              factoryBean.afterPropertiesSet();
              field.setAccessible(true);
              field.set(bean, factoryBean.getObject());
            }
            ExecutorProxy executorProxy = field.getAnnotation(ExecutorProxy.class);
            if (executorProxy != null) {
              ExecutorSpaceRemotingProxyFactoryBean factoryBean =
                  new ExecutorSpaceRemotingProxyFactoryBean();
              factoryBean.setGigaSpace(findGigaSpaceByName(executorProxy.gigaSpace()));
              factoryBean.setTimeout(executorProxy.timeout());
              factoryBean.setBroadcast(executorProxy.broadcast());
              factoryBean.setMetaArgumentsHandler(
                  (MetaArgumentsHandler)
                      createByClassOrFindByName(
                          applicationContext,
                          executorProxy.metaArgumentsHandler(),
                          executorProxy.metaArgumentsHandlerType()));
              factoryBean.setRemoteInvocationAspect(
                  (RemoteInvocationAspect)
                      createByClassOrFindByName(
                          applicationContext,
                          executorProxy.remoteInvocationAspect(),
                          executorProxy.remoteInvocationAspectType()));
              factoryBean.setRemoteRoutingHandler(
                  (RemoteRoutingHandler)
                      createByClassOrFindByName(
                          applicationContext,
                          executorProxy.remoteRoutingHandler(),
                          executorProxy.remoteRoutingHandlerType()));
              factoryBean.setRemoteResultReducer(
                  (RemoteResultReducer)
                      createByClassOrFindByName(
                          applicationContext,
                          executorProxy.remoteResultReducer(),
                          executorProxy.remoteResultReducerType()));
              factoryBean.setReturnFirstResult(executorProxy.returnFirstResult());
              factoryBean.setServiceInterface(field.getType());
              factoryBean.afterPropertiesSet();
              field.setAccessible(true);
              field.set(bean, factoryBean.getObject());
            }
          }
        });

    return true;
  }
  public Object invoke(final MethodInvocation invocation) throws Throwable {
    // Work out the target class: may be {@code null}.
    // The TransactionAttributeSource should be passed the target class
    // as well as the method, which may be from an interface.
    Class<?> targetClass =
        (invocation.getThis() != null ? AopUtils.getTargetClass(invocation.getThis()) : null);

    // If the transaction attribute is null, the method is non-transactional.
    final TransactionAttribute txAttr =
        getTransactionAttributeSource()
            .getTransactionAttribute(invocation.getMethod(), targetClass);
    final PlatformTransactionManager tm = determineTransactionManager(txAttr);
    final String joinpointIdentification =
        methodIdentification(invocation.getMethod(), targetClass);

    if (txAttr == null || !(tm instanceof CallbackPreferringPlatformTransactionManager)) {
      // Standard transaction demarcation with getTransaction and commit/rollback calls.
      TransactionInfo txInfo = createTransactionIfNecessary(tm, txAttr, joinpointIdentification);
      Object retVal = null;
      try {
        // This is an around advice: Invoke the next interceptor in the chain.
        // This will normally result in a target object being invoked.
        retVal = invocation.proceed();
      } catch (Throwable ex) {
        // target invocation exception
        completeTransactionAfterThrowing(txInfo, ex);
        throw ex;
      } finally {
        cleanupTransactionInfo(txInfo);
      }
      commitTransactionAfterReturning(txInfo);
      return retVal;
    } else {
      // It's a CallbackPreferringPlatformTransactionManager: pass a TransactionCallback in.
      try {
        Object result =
            ((CallbackPreferringPlatformTransactionManager) tm)
                .execute(
                    txAttr,
                    new TransactionCallback<Object>() {
                      public Object doInTransaction(TransactionStatus status) {
                        TransactionInfo txInfo =
                            prepareTransactionInfo(tm, txAttr, joinpointIdentification, status);
                        try {
                          return invocation.proceed();
                        } catch (Throwable ex) {
                          if (txAttr.rollbackOn(ex)) {
                            // A RuntimeException: will lead to a rollback.
                            if (ex instanceof RuntimeException) {
                              throw (RuntimeException) ex;
                            } else {
                              throw new ThrowableHolderException(ex);
                            }
                          } else {
                            // A normal return value: will lead to a commit.
                            return new ThrowableHolder(ex);
                          }
                        } finally {
                          cleanupTransactionInfo(txInfo);
                        }
                      }
                    });

        // Check result: It might indicate a Throwable to rethrow.
        if (result instanceof ThrowableHolder) {
          throw ((ThrowableHolder) result).getThrowable();
        } else {
          return result;
        }
      } catch (ThrowableHolderException ex) {
        throw ex.getCause();
      }
    }
  }
  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();
            }

            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;
  }
 private Class<?> getBeanClass(Object bean) {
   Class<?> targetClass = AopUtils.getTargetClass(bean);
   return (targetClass != null) ? targetClass : bean.getClass();
 }