@Override
  public Object getObject() throws Exception {

    final ProxyFactory factory =
        new ProxyFactory(
            proxyObjectType,
            new org.aopalliance.intercept.MethodInterceptor() {
              @Override
              public Object invoke(final org.aopalliance.intercept.MethodInvocation arg0)
                  throws Throwable {

                final ModelMap modelMap =
                    (ModelMap)
                        ReflectionUtils.invokeMethod(getModelMapMethod, arg0.getArguments()[2]);
                final String view =
                    (String)
                        ReflectionUtils.invokeMethod(getViewNameMethod, arg0.getArguments()[2]);
                final Object result =
                    getAdaptee()
                        .beforeView(
                            (HttpServletRequest) arg0.getArguments()[0],
                            (HttpServletResponse) arg0.getArguments()[1],
                            modelMap,
                            view);

                if (result != view) {
                  ReflectionUtils.invokeMethod(setViewNameMethod, arg0.getArguments()[2], result);
                }
                return null;
              }
            });
    return factory.getProxy();
  }
  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;
    }
  }
  @Test
  public void compatibleConversionService() throws Exception {
    HttpRequestExecutingMessageHandler handler =
        new HttpRequestExecutingMessageHandler("http://www.springsource.org/spring-integration");
    ConfigurableListableBeanFactory bf = new DefaultListableBeanFactory();
    ProxyFactory pf =
        new ProxyFactory(new Class<?>[] {ConversionService.class, ConverterRegistry.class});
    final AtomicInteger converterCount = new AtomicInteger();
    pf.addAdvice(
        new MethodInterceptor() {

          public Object invoke(MethodInvocation invocation) throws Throwable {
            if (invocation.getMethod().getName().equals("addConverter")) {
              converterCount.incrementAndGet();
            }
            return null;
          }
        });
    ConversionService mockConversionService = (ConversionService) pf.getProxy();
    bf.registerSingleton("integrationConversionService", mockConversionService);
    handler.setBeanFactory(bf);
    handler.afterPropertiesSet();
    assertEquals(2, converterCount.get());
    assertSame(mockConversionService, TestUtils.getPropertyValue(handler, "conversionService"));
  }
 @Override
 public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
   ProxyFactory factory = new ProxyFactory();
   factory.addAdvice(new TimeLoggingMethodInterceptor());
   factory.setTarget(bean);
   return (Object) factory.getProxy();
 }
  @Test
  public void demoMethodNameMappingExpressionSource() {
    Map<String, String> expressionMap = new HashMap<String, String>();
    expressionMap.put("test", "#return");
    MethodNameMappingPublisherMetadataSource metadataSource =
        new MethodNameMappingPublisherMetadataSource(expressionMap);
    Map<String, String> channelMap = new HashMap<String, String>();
    channelMap.put("test", "c");
    metadataSource.setChannelMap(channelMap);

    Map<String, Map<String, String>> headerExpressionMap =
        new HashMap<String, Map<String, String>>();
    Map<String, String> headerExpressions = new HashMap<String, String>();
    headerExpressions.put("bar", "#return");
    headerExpressions.put("name", "'oleg'");
    headerExpressionMap.put("test", headerExpressions);
    metadataSource.setHeaderExpressionMap(headerExpressionMap);

    MessagePublishingInterceptor interceptor = new MessagePublishingInterceptor(metadataSource);
    interceptor.setBeanFactory(beanFactory);
    interceptor.setChannelResolver(channelResolver);
    ProxyFactory pf = new ProxyFactory(new TestBeanImpl());
    pf.addAdvice(interceptor);
    TestBean proxy = (TestBean) pf.getProxy();
    proxy.test();
    Message<?> message = testChannel.receive(0);
    assertNotNull(message);
    assertEquals("foo", message.getPayload());
    assertEquals("foo", message.getHeaders().get("bar"));
    assertEquals("oleg", message.getHeaders().get("name"));
  }
 /** Create an empty pointcut, populating instance variables. */
 @Before
 public void setUp() {
   ProxyFactory pf = new ProxyFactory(new SerializablePerson());
   nop = new SerializableNopInterceptor();
   pc = new NameMatchMethodPointcut();
   pf.addAdvisor(new DefaultPointcutAdvisor(pc, nop));
   proxied = (Person) pf.getProxy();
 }
  private static RedisConnection createConnectionProxy(
      RedisConnection connection, RedisConnectionFactory factory) {

    ProxyFactory proxyFactory = new ProxyFactory(connection);
    proxyFactory.addAdvice(new ConnectionSplittingInterceptor(factory));

    return RedisConnection.class.cast(proxyFactory.getProxy());
  }
  private static KeyGenerator getKeyGenerator() {
    KeyGenerator target = new KeyGenerator();

    ProxyFactory pf = new ProxyFactory();
    pf.addAdvice(new WeakKeyCheckAdvice());
    pf.setTarget(target);
    return (KeyGenerator) pf.getProxy();
  }
 public static void main(String[] args) {
   MessageWriter target = new MessageWriter();
   ProxyFactory pf = new ProxyFactory();
   pf.addAdvice(new SimpleBeforeAdvice());
   pf.setTarget(target);
   MessageWriter proxy = (MessageWriter) pf.getProxy();
   proxy.writeMessage();
 }
 @Override
 public synchronized Object getObject() throws Exception {
   if (this.proxy == null) {
     ProxyFactory factory = new ProxyFactory(this.type, this);
     this.proxy = factory.getProxy();
   }
   return this.proxy;
 }
Exemple #11
0
  public static void main(String[] args) {
    ProxyFactory proxyFactory = new ProxyFactory();
    proxyFactory.setTarget(new GreetingImpl());
    proxyFactory.addAdvice(new GreetingBeforeAdvice());
    proxyFactory.addAdvice(new GreetingAfterAdvice());

    Greeting greeting = (Greeting) proxyFactory.getProxy();
    greeting.sayHello("Jack");
  }
Exemple #12
0
 private <T> T makeActoidProxy(Object actoidImplementation, ProxyFactory pf) {
   Actoid actoid = new Actoid(actoidImplementation, this);
   ActoidInterceptor handler = new ActoidInterceptor(actoid);
   pf.addAdvice(handler);
   Advised proxy = (Advised) pf.getProxy();
   actoid.setSelf(proxy);
   @SuppressWarnings("unchecked")
   T r = (T) proxy;
   return r;
 }
 /**
  * Creates a default transactional proxy for service with default transacction attributes
  *
  * @param <T>
  * @param service
  * @return a Tx Proxy for service with default tx attributes
  */
 @SuppressWarnings("unchecked")
 public <T> PersistentManager<T, Serializable> makeTransactionalProxy(
     PersistentManager<T, Serializable> service) {
   ProxyFactory factory = new ProxyFactory(service);
   factory.setInterfaces(new Class[] {Dao.class});
   TransactionInterceptor interceptor =
       new TransactionInterceptor(transactionManager, new MatchAlwaysTransactionAttributeSource());
   factory.addAdvice(interceptor);
   factory.setTarget(service);
   return (PersistentManager<T, Serializable>) factory.getProxy();
 }
  private MessageGroupProcessor createGroupTimeoutProcessor() {
    MessageGroupProcessor processor = new ForceReleaseMessageGroupProcessor();

    if (this.groupTimeoutExpression != null
        && !CollectionUtils.isEmpty(this.forceReleaseAdviceChain)) {
      ProxyFactory proxyFactory = new ProxyFactory(processor);
      for (Advice advice : this.forceReleaseAdviceChain) {
        proxyFactory.addAdvice(advice);
      }
      return (MessageGroupProcessor)
          proxyFactory.getProxy(getApplicationContext().getClassLoader());
    }
    return processor;
  }
 @Test
 public void returnValue() {
   PublisherMetadataSource metadataSource = new TestPublisherMetadataSource();
   MessagePublishingInterceptor interceptor = new MessagePublishingInterceptor(metadataSource);
   interceptor.setBeanFactory(beanFactory);
   interceptor.setChannelResolver(channelResolver);
   ProxyFactory pf = new ProxyFactory(new TestBeanImpl());
   pf.addAdvice(interceptor);
   TestBean proxy = (TestBean) pf.getProxy();
   proxy.test();
   Message<?> message = testChannel.receive(0);
   assertNotNull(message);
   assertEquals("test-foo", message.getPayload());
 }
  public void run() {
    TestBean target = new TestBean();
    Pointcut pc = new ControlFlowPointcut(ControlFlowPointcutExample.class, "test"); //
    Advisor advisor = new DefaultPointcutAdvisor(pc, new SimpleBeforeAdvice());
    ProxyFactory pf = new ProxyFactory();
    pf.setTarget(target);
    pf.addAdvisor(advisor);
    TestBean proxy = (TestBean) pf.getProxy();
    System.out.println("Trying normal invoke");
    proxy.foo();

    System.out.println("Trying under ControlFlowExample.test()");
    // 只有从ControlFlowExample.test() 中调用的代理对象的方法,才被增强
    test(proxy);
  }
  @Test
  public void exportAdvisedChannel() throws Exception {

    DummyInterceptor interceptor = new DummyInterceptor();
    NameMatchMethodPointcutAdvisor advisor = new NameMatchMethodPointcutAdvisor(interceptor);
    advisor.addMethodName("send");

    ProxyFactory factory = new ProxyFactory(channel);
    factory.addAdvisor(advisor);
    MessageChannel advised = (MessageChannel) factory.getProxy();

    MessageChannel exported =
        (MessageChannel) mBeanExporter.postProcessAfterInitialization(advised, "test");
    exported.send(MessageBuilder.withPayload("test").build());
  }
  public void afterPropertiesSet() {
    if (this.target == null) {
      throw new IllegalArgumentException("Property 'target' is required");
    }
    if (this.target instanceof String) {
      throw new IllegalArgumentException(
          "'target' needs to be a bean reference, not a bean name as value");
    }

    ClassLoader proxyClassLoader = target.getClass().getClassLoader();

    ProxyFactory proxyFactory = new ProxyFactory();

    if (this.preInterceptors != null) {
      for (Object interceptor : this.preInterceptors) {
        proxyFactory.addAdvisor(this.advisorAdapterRegistry.wrap(interceptor));
      }
    }

    // Add the main interceptor (typically an Advisor).
    proxyFactory.addAdvisor(this.advisorAdapterRegistry.wrap(createMainInterceptor()));

    if (this.postInterceptors != null) {
      for (Object interceptor : this.postInterceptors) {
        proxyFactory.addAdvisor(this.advisorAdapterRegistry.wrap(interceptor));
      }
    }

    proxyFactory.copyFrom(this);

    TargetSource targetSource = createTargetSource(this.target);
    proxyFactory.setTargetSource(targetSource);

    if (this.proxyInterfaces != null) {
      proxyFactory.setInterfaces(this.proxyInterfaces);
    } else if (!isProxyTargetClass()) {
      // Rely on AOP infrastructure to tell us what interfaces to proxy.
      proxyFactory.setInterfaces(
          ClassUtils.getAllInterfacesForClass(targetSource.getTargetClass(), proxyClassLoader));
    }

    /**
     * use this option to let proxyFactory user cglib to create proxy,otherwise in dynamic script
     * ,this is no dynamic interface 使用这个选荋 将使用cglib 产生代理类,否则在动动的java中,没有动态的接口
     */
    proxyFactory.setOptimize(true);
    this.proxy = proxyFactory.getProxy(proxyClassLoader);
  }
  @Test
  public void invokeListenerInvalidProxy() {
    Object target = new InvalidProxyTestBean();
    ProxyFactory proxyFactory = new ProxyFactory();
    proxyFactory.setTarget(target);
    proxyFactory.addInterface(SimpleService.class);
    Object bean = proxyFactory.getProxy(getClass().getClassLoader());

    Method method =
        ReflectionUtils.findMethod(InvalidProxyTestBean.class, "handleIt2", ApplicationEvent.class);
    StaticApplicationListenerMethodAdapter listener =
        new StaticApplicationListenerMethodAdapter(method, bean);
    this.thrown.expect(IllegalStateException.class);
    this.thrown.expectMessage("handleIt2");
    listener.onApplicationEvent(createGenericTestEvent("test"));
  }
  @Test
  public void resolveArgumentTypeVariableWithNonGenericConverter() throws Exception {
    Method method = MyParameterizedController.class.getMethod("handleDto", Identifiable.class);
    HandlerMethod handlerMethod = new HandlerMethod(new MySimpleParameterizedController(), method);
    MethodParameter methodParam = handlerMethod.getMethodParameters()[0];

    String content = "{\"name\" : \"Jad\"}";
    this.servletRequest.setContent(content.getBytes("UTF-8"));
    this.servletRequest.setContentType(MediaType.APPLICATION_JSON_VALUE);

    List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();
    HttpMessageConverter target = new MappingJackson2HttpMessageConverter();
    HttpMessageConverter proxy =
        ProxyFactory.getProxy(HttpMessageConverter.class, new SingletonTargetSource(target));
    converters.add(proxy);
    RequestResponseBodyMethodProcessor processor =
        new RequestResponseBodyMethodProcessor(converters);

    SimpleBean result =
        (SimpleBean)
            processor.resolveArgument(methodParam, mavContainer, webRequest, binderFactory);

    assertNotNull(result);
    assertEquals("Jad", result.getName());
  }
 @Override
 protected void applyReceiveOnlyAdviceChain(Collection<Advice> chain) {
   if (AopUtils.isAopProxy(this.source)) {
     for (Advice advice : chain) {
       NameMatchMethodPointcutAdvisor sourceAdvice = new NameMatchMethodPointcutAdvisor(advice);
       sourceAdvice.addMethodName("receive");
       ((Advised) this.source).addAdvice(advice);
     }
   } else {
     ProxyFactory proxyFactory = new ProxyFactory(this.source);
     for (Advice advice : chain) {
       proxyFactory.addAdvice(advice);
     }
     this.source = (MessageSource<?>) proxyFactory.getProxy(getBeanClassLoader());
   }
 }
Exemple #22
0
    /**
     * Executes a {@link SqkWork} in transaction.
     *
     * @param work Non-null.
     * @return
     */
    public Object executeSql(final SqlWork work) {

      if (principalHolder.size() > 0) {
        throw new IllegalStateException(
            "Currently logged in. \n"
                + "JDBC will then take part in transaction directly. \n"
                + "Please have the proper JDBC or data source injected.");
      }

      ProxyFactory factory = new ProxyFactory();
      factory.setTarget(work);
      factory.setInterfaces(new Class[] {SqlWork.class});
      factory.addAdvice(advices.get(2)); // TX FIXME
      SqlWork wrapper = (SqlWork) factory.getProxy();
      return wrapper.doWork(this.sqlAction);
    }
 @Override
 public JobRepository getObject() throws Exception {
   if (proxyFactory == null) {
     afterPropertiesSet();
   }
   return (JobRepository) proxyFactory.getProxy(getClass().getClassLoader());
 }
 @Override
 protected final void onInit() throws Exception {
   super.onInit();
   if (!CollectionUtils.isEmpty(this.adviceChain)) {
     ProxyFactory proxyFactory = new ProxyFactory(new AdvisedRequestHandler());
     boolean advised = false;
     for (Advice advice : this.adviceChain) {
       if (!(advice instanceof HandleMessageAdvice)) {
         proxyFactory.addAdvice(advice);
         advised = true;
       }
     }
     if (advised) {
       this.advisedRequestHandler = (RequestHandler) proxyFactory.getProxy(this.beanClassLoader);
     }
   }
   doInit();
 }
 public Visitor findVisitorFromClassName(Object instance) {
   try {
     Class<Visitor> visitorClass = nameResolvers.peek().findVisitingClassFromClassName(instance);
     Object target = visitorClass.newInstance();
     if (target instanceof AbstractPatternVisitor) {
       ((AbstractPatternVisitor) target).setVisitorFactory(this);
     }
     ProxyFactory proxyFactory = new ProxyFactory();
     proxyFactory.addInterface(Visitor.class);
     proxyFactory.addAdvice(advice);
     proxyFactory.setTarget(target);
     return (Visitor) proxyFactory.getProxy(this.getClass().getClassLoader());
   } catch (Exception ex) {
     log.info(
         "Could not find visitor class for element named [{}]",
         instance.getClass()); // $NON-NLS-1$
     return new ExceptionThrowingVisitor(ex);
   }
 }
  public static void main(String[] args) {
    NameBean target = new NameBean();

    // create advisor
    NameMatchMethodPointcutAdvisor advisor = new NameMatchMethodPointcutAdvisor(new SimpleAdvice());
    advisor.addMethodName("foo");
    advisor.addMethodName("bar");

    // create the proxy
    ProxyFactory pf = new ProxyFactory();
    pf.setTarget(target);
    pf.addAdvisor(advisor);
    NameBean proxy = (NameBean) pf.getProxy();

    proxy.foo();
    proxy.foo(999);
    proxy.bar();
    proxy.yup();
  }
 @SuppressWarnings("unchecked")
 private static <T> T initProxy(Class<?> type, ControllerMethodInvocationInterceptor interceptor) {
   if (type.isInterface()) {
     ProxyFactory factory = new ProxyFactory(EmptyTargetSource.INSTANCE);
     factory.addInterface(type);
     factory.addInterface(MethodInvocationInfo.class);
     factory.addAdvice(interceptor);
     return (T) factory.getProxy();
   } else {
     Enhancer enhancer = new Enhancer();
     enhancer.setSuperclass(type);
     enhancer.setInterfaces(new Class<?>[] {MethodInvocationInfo.class});
     enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE);
     enhancer.setCallbackType(org.springframework.cglib.proxy.MethodInterceptor.class);
     Factory factory = (Factory) objenesis.newInstance(enhancer.createClass());
     factory.setCallbacks(new Callback[] {interceptor});
     return (T) factory;
   }
 }
 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;
 }
  protected Object buildLazyResolutionProxy(
      final DependencyDescriptor descriptor, final String beanName) {
    Assert.state(
        getBeanFactory() instanceof DefaultListableBeanFactory,
        "BeanFactory needs to be a DefaultListableBeanFactory");
    final DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) getBeanFactory();
    TargetSource ts =
        new TargetSource() {
          @Override
          public Class<?> getTargetClass() {
            return descriptor.getDependencyType();
          }

          @Override
          public boolean isStatic() {
            return false;
          }

          @Override
          public Object getTarget() {
            Object target = beanFactory.doResolveDependency(descriptor, beanName, null, null);
            if (target == null) {
              throw new NoSuchBeanDefinitionException(
                  descriptor.getDependencyType(),
                  "Optional dependency not present for lazy injection point");
            }
            return target;
          }

          @Override
          public void releaseTarget(Object target) {}
        };
    ProxyFactory pf = new ProxyFactory();
    pf.setTargetSource(ts);
    Class<?> dependencyType = descriptor.getDependencyType();
    if (dependencyType.isInterface()) {
      pf.addInterface(dependencyType);
    }
    return pf.getProxy(beanFactory.getBeanClassLoader());
  }
 private void initializeProxy() throws Exception {
   if (proxyFactory == null) {
     proxyFactory = new ProxyFactory();
     TransactionInterceptor advice =
         new TransactionInterceptor(
             transactionManager,
             PropertiesConverter.stringToProperties(
                 "create*=PROPAGATION_REQUIRES_NEW,"
                     + isolationLevelForCreate
                     + "\ngetLastJobExecution*=PROPAGATION_REQUIRES_NEW,"
                     + isolationLevelForCreate
                     + "\n*=PROPAGATION_REQUIRED"));
     if (validateTransactionState) {
       DefaultPointcutAdvisor advisor =
           new DefaultPointcutAdvisor(
               new MethodInterceptor() {
                 @Override
                 public Object invoke(MethodInvocation invocation) throws Throwable {
                   if (TransactionSynchronizationManager.isActualTransactionActive()) {
                     throw new IllegalStateException(
                         "Existing transaction detected in JobRepository. "
                             + "Please fix this and try again (e.g. remove @Transactional annotations from client).");
                   }
                   return invocation.proceed();
                 }
               });
       NameMatchMethodPointcut pointcut = new NameMatchMethodPointcut();
       pointcut.addMethodName("create*");
       advisor.setPointcut(pointcut);
       proxyFactory.addAdvisor(advisor);
     }
     proxyFactory.addAdvice(advice);
     proxyFactory.setProxyTargetClass(false);
     proxyFactory.addInterface(JobRepository.class);
     proxyFactory.setTarget(getTarget());
   }
 }