Exemple #1
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 #2
0
    /**
     * Executes a {@link Work} instance wrapped in two layers of AOP. The first is intended to
     * acquire the proper arguments for {@link Work#doWork(TransactionStatus, Session,
     * ServiceFactory)} for the {@link OmeroContext}, and the second performs all the standard
     * service actions for any normal method call.
     *
     * <p>If the {@link Principal} argument is not null, then additionally, a login/logout sequence
     * will be performed in a try/finally block.
     *
     * @param callContext Possibly null key-value map. See #3529
     * @param p
     * @param work
     */
    public Object execute(
        final Map<String, String> callContext, final Principal p, final Work work) {

      if (work instanceof SimpleWork) {
        ((SimpleWork) work).setSqlAction(sqlAction);
      }

      Interceptor i = new Interceptor(factory);
      ProxyFactory factory = new ProxyFactory();
      factory.setTarget(work);
      factory.setInterfaces(new Class[] {Work.class});

      for (Advice advice : advices) {
        factory.addAdvice(advice);
      }
      factory.addAdvice(i);

      Work wrapper = (Work) factory.getProxy();

      // First we guarantee that this will cause one and only
      // login to take place.
      if (p == null && principalHolder.size() == 0) {
        throw new IllegalStateException("Must provide principal");
      } else if (p != null && principalHolder.size() > 0) {
        throw new IllegalStateException("Already logged in. Use Executor.submit() and .get().");
      }

      // Don't need to worry about the login stack below since
      // already checked.
      if (p != null) {
        this.principalHolder.login(p);
      }
      if (callContext != null) {
        this.principalHolder.setContext(callContext);
      }

      try {
        // Arguments will be replaced after hibernate is in effect
        return wrapper.doWork(null, isf);
      } finally {
        if (callContext != null) {
          this.principalHolder.setContext(null);
        }
        if (p != null) {
          int left = this.principalHolder.logout();
          if (left > 0) {
            log.warn("Logins left: " + left);
            for (int j = 0; j < left; j++) {
              this.principalHolder.logout();
            }
          }
        }
      }
    }
 @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 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"));
  }
  @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"));
  }
  private static KeyGenerator getKeyGenerator() {
    KeyGenerator target = new KeyGenerator();

    ProxyFactory pf = new ProxyFactory();
    pf.addAdvice(new WeakKeyCheckAdvice());
    pf.setTarget(target);
    return (KeyGenerator) 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());
  }
 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();
 }
Exemple #9
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();
 }
  public static void main(String[] args) {
    Class[] interfaces = new Class[] {HelloService.class};
    ProxyFactory proxyFactory = new ProxyFactory(interfaces);
    proxyFactory.setTarget(new HelloServiceImpl());
    proxyFactory.setOpaque(true);
    // 可以添加过个前置通知
    proxyFactory.addAdvice(
        new MethodBeforeAdvice() {
          @Override
          public void before(Method method, Object[] args, Object target) throws Throwable {
            System.out.println("before method :" + method.getName());
          }
        });
    proxyFactory.addAdvice(
        new AfterReturningAdvice() {
          @Override
          public void afterReturning(
              Object returnValue, Method method, Object[] args, Object target) throws Throwable {
            System.out.println("after method :" + method.getName());
          }
        });

    proxyFactory.addAdvice(
        new MethodInterceptor() {
          @Override
          public Object invoke(MethodInvocation methodInvocation) throws Throwable {
            System.out.println("before interceptor...");
            Object result =
                methodInvocation
                    .getMethod()
                    .invoke(methodInvocation.getThis(), methodInvocation.getArguments());
            System.out.println("interceptor: " + result);
            System.out.println("after interceptor...");
            return result;
          }
        });

    HelloService helloService = (HelloService) proxyFactory.getProxy();
    String result = helloService.hello("gaohuan");
    System.out.println("result:" + result);
  }
  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());
 }
  /*
   * (non-Javadoc)
   * @see org.springframework.data.repository.core.support.RepositoryProxyPostProcessor#postProcess(org.springframework.aop.framework.ProxyFactory, org.springframework.data.repository.core.RepositoryInformation)
   */
  public void postProcess(ProxyFactory factory, RepositoryInformation repositoryInformation) {

    CustomAnnotationTransactionAttributeSource transactionAttributeSource =
        new CustomAnnotationTransactionAttributeSource();
    transactionAttributeSource.setRepositoryInformation(repositoryInformation);
    transactionAttributeSource.setEnableDefaultTransactions(enableDefaultTransactions);

    TransactionInterceptor transactionInterceptor =
        new TransactionInterceptor(null, transactionAttributeSource);
    transactionInterceptor.setTransactionManagerBeanName(transactionManagerName);
    transactionInterceptor.setBeanFactory(beanFactory);
    transactionInterceptor.afterPropertiesSet();

    factory.addAdvice(transactionInterceptor);
  }
  /**
   * Enhances the object on load.
   *
   * @param <T> Type of the object to enhance.
   * @param obj Object to augment/enhance.
   * @return Enhanced object.
   */
  @SuppressWarnings({"unchecked"})
  public static <T> T enhance(T obj) {
    ProxyFactory proxyFac = new ProxyFactory(obj);

    proxyFac.addAdvice(dfltAsp);
    proxyFac.addAdvice(setToValAsp);
    proxyFac.addAdvice(setToSetAsp);

    while (proxyFac.getAdvisors().length > 0) {
      proxyFac.removeAdvisor(0);
    }

    proxyFac.addAdvisor(
        new DefaultPointcutAdvisor(
            new GridifySpringPointcut(GridifySpringPointcutType.DFLT), dfltAsp));
    proxyFac.addAdvisor(
        new DefaultPointcutAdvisor(
            new GridifySpringPointcut(GridifySpringPointcutType.SET_TO_VALUE), setToValAsp));
    proxyFac.addAdvisor(
        new DefaultPointcutAdvisor(
            new GridifySpringPointcut(GridifySpringPointcutType.SET_TO_SET), setToSetAsp));

    return (T) proxyFac.getProxy();
  }
 @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 #17
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
 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);
   }
 }
 @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 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());
   }
 }
  public TestEngine(TestEngineConfig config)
      throws CannotCreateSessionException, PermissionDeniedException, ServerError {
    this.config = config;
    ProxyFactory pf = new ProxyFactory(new OMEROMetadataStoreClient());
    pf.addAdvice(interceptor);
    pf.setProxyTargetClass(true);
    store = (OMEROMetadataStoreClient) pf.getProxy();
    wrapper = new OMEROWrapper(new ImportConfig());

    login_url = config.getFeedbackLoginUrl();
    login_username = config.getFeedbackLoginUsername();
    login_password = config.getFeedbackLoginPassword();
    message_url = config.getFeedbackMessageUrl();
    comment_url = config.getCommentUrl();

    // Login
    if (config.getSessionKey() != null) {
      store.initialize(config.getHostname(), config.getPort(), config.getSessionKey());
    } else {
      store.initialize(
          config.getUsername(), config.getPassword(), config.getHostname(), config.getPort());
    }
    importLibrary = new ImportLibrary(store, wrapper);
  }
  /*
   * (non-Javadoc)
   *
   * @see
   * org.springframework.data.repository.support.RepositoryProxyPostProcessor
   * #postProcess(org.springframework.aop.framework.ProxyFactory)
   */
  public void postProcess(ProxyFactory factory) {

    factory.addAdvice(petInterceptor);
    factory.addAdvice(transactionInterceptor);
  }