@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();
 }
 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();
 }
  private static KeyGenerator getKeyGenerator() {
    KeyGenerator target = new KeyGenerator();

    ProxyFactory pf = new ProxyFactory();
    pf.addAdvice(new WeakKeyCheckAdvice());
    pf.setTarget(target);
    return (KeyGenerator) pf.getProxy();
  }
Exemple #4
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 #5
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();
            }
          }
        }
      }
    }
 /**
  * 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 void initializeProxy() {
   if (adviceChain.length == 0) {
     return;
   }
   ProxyFactory factory = new ProxyFactory();
   for (Advice advice : getAdviceChain()) {
     factory.addAdvisor(new DefaultPointcutAdvisor(Pointcut.TRUE, advice));
   }
   factory.setProxyTargetClass(false);
   factory.addInterface(ContainerDelegate.class);
   factory.setTarget(delegate);
   proxy = (ContainerDelegate) factory.getProxy();
 }
  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);
  }
Exemple #9
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);
    }
  @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"));
  }
  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();
  }
 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) {
    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 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());
   }
 }