javassist.util.proxy.Proxy Java Examples

The following examples show how to use javassist.util.proxy.Proxy. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JavassistClientProxyFactory.java    From bowman with Apache License 2.0 6 votes vote down vote up
private static <T> T createProxyInstance(Class<T> entityType, MethodHandlerChain handlerChain) {
	ProxyFactory factory = new ProxyFactory();
	if (ProxyFactory.isProxyClass(entityType)) {
		factory.setInterfaces(getNonProxyInterfaces(entityType));
		factory.setSuperclass(entityType.getSuperclass());
	}
	else {
		factory.setSuperclass(entityType);
	}
	factory.setFilter(handlerChain);
	
	Class<?> clazz = factory.createClass();
	T proxy = instantiateClass(clazz);
	((Proxy) proxy).setHandler(handlerChain);
	return proxy;
}
 
Example #2
Source File: BaseExecutorTest.java    From mybatis with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldFetchPostsForBlog() throws Exception {
  
  Executor executor = createExecutor(new JdbcTransaction(ds, null, false));
  try {
    MappedStatement selectBlog = ExecutorTestHelper.prepareComplexSelectBlogMappedStatement(config);
    MappedStatement selectPosts = ExecutorTestHelper.prepareSelectPostsForBlogMappedStatement(config);
    config.addMappedStatement(selectBlog);
    config.addMappedStatement(selectPosts);
    List<Post> posts = executor.query(selectPosts, 1, RowBounds.DEFAULT, Executor.NO_RESULT_HANDLER);
    executor.flushStatements();
    assertEquals(2, posts.size());
    assertTrue(posts.get(1) instanceof Proxy);
    assertNotNull(posts.get(1).getBlog());
    assertEquals(1, posts.get(1).getBlog().getId());
    executor.rollback(true);
  } finally {
    executor.rollback(true);
    executor.close(false);
  }
}
 
Example #3
Source File: BindingTest.java    From mybaties with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldGetBlogsWithAuthorsAndPosts() {
  SqlSession session = sqlSessionFactory.openSession();
  try {
    BoundBlogMapper mapper = session.getMapper(BoundBlogMapper.class);
    List<Blog> blogs = mapper.selectBlogsWithAutorAndPosts();
    assertEquals(2, blogs.size());
    assertTrue(blogs.get(0) instanceof Proxy);
    assertEquals(101, blogs.get(0).getAuthor().getId());
    assertEquals(1, blogs.get(0).getPosts().size());
    assertEquals(1, blogs.get(0).getPosts().get(0).getId());
    assertTrue(blogs.get(1) instanceof Proxy);      
    assertEquals(102, blogs.get(1).getAuthor().getId());
    assertEquals(1, blogs.get(1).getPosts().size());
    assertEquals(2, blogs.get(1).getPosts().get(0).getId());
  } finally {
    session.close();
  }
}
 
Example #4
Source File: BindingTest.java    From mybatis with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldGetBlogsWithAuthorsAndPosts() {
  SqlSession session = sqlSessionFactory.openSession();
  try {
    BoundBlogMapper mapper = session.getMapper(BoundBlogMapper.class);
    List<Blog> blogs = mapper.selectBlogsWithAutorAndPosts();
    assertEquals(2, blogs.size());
    assertTrue(blogs.get(0) instanceof Proxy);
    assertEquals(101, blogs.get(0).getAuthor().getId());
    assertEquals(1, blogs.get(0).getPosts().size());
    assertEquals(1, blogs.get(0).getPosts().get(0).getId());
    assertTrue(blogs.get(1) instanceof Proxy);      
    assertEquals(102, blogs.get(1).getAuthor().getId());
    assertEquals(1, blogs.get(1).getPosts().size());
    assertEquals(2, blogs.get(1).getPosts().get(0).getId());
  } finally {
    session.close();
  }
}
 
Example #5
Source File: BaseExecutorTest.java    From mybaties with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldFetchPostsForBlog() throws Exception {
  
  Executor executor = createExecutor(new JdbcTransaction(ds, null, false));
  try {
    MappedStatement selectBlog = ExecutorTestHelper.prepareComplexSelectBlogMappedStatement(config);
    MappedStatement selectPosts = ExecutorTestHelper.prepareSelectPostsForBlogMappedStatement(config);
    config.addMappedStatement(selectBlog);
    config.addMappedStatement(selectPosts);
    List<Post> posts = executor.query(selectPosts, 1, RowBounds.DEFAULT, Executor.NO_RESULT_HANDLER);
    executor.flushStatements();
    assertEquals(2, posts.size());
    assertTrue(posts.get(1) instanceof Proxy);
    assertNotNull(posts.get(1).getBlog());
    assertEquals(1, posts.get(1).getBlog().getId());
    executor.rollback(true);
  } finally {
    executor.rollback(true);
    executor.close(false);
  }
}
 
Example #6
Source File: ContextClassLoaderInjector.java    From scheduling with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Create an injected object which has been injected with specifying the thread context class loader during all its methods invocation.
 *
 * @param superClass The class whose object methods need to be injected
 * @param contextClassLoader the thread context class loader to inject in all the methods of the class object
 * @return the created injected object
 */
public static Object createInjectedObject(Class<?> superClass, ClassLoader contextClassLoader) throws Exception {
    proxyFactory.setSuperclass(superClass);
    // The thread context class loader also needs to be sepecified during the object instantiation.
    Object object = switchContextClassLoader(contextClassLoader, () -> {
        Class<?> proxyClass = proxyFactory.createClass();
        return proxyClass.newInstance();
    });

    MethodHandler injectClassLoaderHandler = (self, method, proceed, args) -> {
        logger.debug("Delegating method: " + self.getClass().getSimpleName() + "." + method.getName());
        // inject setting of thread context classloader during execution of all the object original methods
        return switchContextClassLoader(contextClassLoader, () -> proceed.invoke(self, args));
    };
    ((Proxy) object).setHandler(injectClassLoaderHandler);

    return object;
}
 
Example #7
Source File: RidUtils.java    From guice-persist-orient with MIT License 6 votes vote down vote up
/**
 * Resolve rid from almost all possible objects.
 * Even if simple string provided, value will be checked for correctness.
 * <p>
 * Note: not saved object proxy, document or vertex will contain fake id and will be accepted
 * (but query result against such id will be empty).
 *
 * @param value value may be a mapped object (proxy or raw), document, vertex, ORID or simple string
 * @return correct rid string
 * @throws ru.vyarus.guice.persist.orient.db.PersistException if rid couldn't be resolved
 * @throws NullPointerException                               if value is null
 */
public static String getRid(final Object value) {
    Preconditions.checkNotNull(value, "Not null value required");
    final String res;
    if (value instanceof ORID) {
        res = value.toString();
    } else if (value instanceof OIdentifiable) {
        // ODocument, Vertex support
        res = ((OIdentifiable) value).getIdentity().toString();
    } else if (value instanceof String) {
        res = checkRid(value);
    } else if (value instanceof Proxy) {
        // object proxy
        res = OObjectEntitySerializer.getRid((Proxy) value).toString();
    } else {
        // raw (non proxy) object
        res = resolveIdFromObject(value);
    }
    return res;
}
 
Example #8
Source File: BootstrapProxyFactory.java    From dropwizard-guicey with MIT License 6 votes vote down vote up
/**
 * @param bootstrap dropwizard bootstrap object
 * @param context   guicey configuration context
 * @return dropwizard bootstrap proxy object
 */
@SuppressWarnings("unchecked")
public static Bootstrap create(final Bootstrap bootstrap, final ConfigurationContext context) {
    try {
        final ProxyFactory factory = new ProxyFactory();
        factory.setSuperclass(Bootstrap.class);
        final Class proxy = factory.createClass();

        final Bootstrap res = (Bootstrap) proxy.getConstructor(Application.class).newInstance(new Object[]{null});
        ((Proxy) res).setHandler((self, thisMethod, proceed, args) -> {
            // intercept only bundle addition
            if (thisMethod.getName().equals("addBundle")) {
                context.registerDropwizardBundles((ConfiguredBundle) args[0]);
                return null;
            }
            // other methods called as is
            return thisMethod.invoke(bootstrap, args);
        });
        return res;
    } catch (Exception e) {
        throw new IllegalStateException("Failed to create Bootstrap proxy", e);
    }
}
 
Example #9
Source File: ProxyFactoryFactoryImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public Object getProxy() {
	try {
		final Proxy proxy = (Proxy) proxyClass.newInstance();
		proxy.setHandler( new PassThroughHandler( proxy, proxyClass.getName() ) );
		return proxy;
	}
	catch ( Throwable t ) {
		throw new HibernateException( "Unable to instantiated proxy instance" );
	}
}
 
Example #10
Source File: ProxiesTest.java    From furnace with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testIsProxyType() throws Exception
{
   Assert.assertTrue(Proxies.isProxyType(new Proxy()
   {
      @Override
      public void setHandler(MethodHandler mi)
      {
      }
   }.getClass()));
}
 
Example #11
Source File: Proxies.java    From furnace with Eclipse Public License 1.0 5 votes vote down vote up
public static boolean isProxyType(Class<?> type)
{
   if (type != null)
   {
      if (type.getName().contains("$$EnhancerByCGLIB$$")
               || type.getName().contains("_jvst")
               || type.getName().contains("$Proxy$_$$_WeldClientProxy")
               || Proxy.class.isAssignableFrom(type)
               || ProxyObject.class.isAssignableFrom(type))
      {
         return true;
      }
   }
   return false;
}
 
Example #12
Source File: JavassistProxyTest.java    From mybatis with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldCreateAProxyForAPartiallyLoadedBean() throws Exception {
  ResultLoaderMap loader = new ResultLoaderMap();
  loader.addLoader("id", null, null);
  Object proxy = proxyFactory.createProxy(author, loader, new Configuration(), new DefaultObjectFactory(), new ArrayList<Class<?>>(), new ArrayList<Object>());
  Author author2 = (Author) deserialize(serialize((Serializable) proxy));
  assertTrue(author2 instanceof Proxy);
}
 
Example #13
Source File: JavassistTest.java    From mybatis with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldGetAUserAndGroups() {
  SqlSession sqlSession = sqlSessionFactory.openSession();
  try {
    Mapper mapper = sqlSession.getMapper(Mapper.class);
    User user = mapper.getUser(1);
    Assert.assertEquals("User1", user.getName());
    assertTrue(user instanceof Proxy);
    Assert.assertEquals(1, user.getGroups().size());
  } finally {
    sqlSession.close();
  }
}
 
Example #14
Source File: SqlSessionTest.java    From mybatis with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldSelectBlogWithPostsAndAuthorUsingSubSelectsLazily() throws Exception {
  SqlSession session = sqlMapper.openSession();
  try {
    Blog blog = session.selectOne("org.apache.ibatis.domain.blog.mappers.BlogMapper.selectBlogWithPostsUsingSubSelectLazily", 1);
    Assert.assertTrue(blog instanceof Proxy);
    assertEquals("Jim Business", blog.getTitle());
    assertEquals(2, blog.getPosts().size());
    assertEquals("Corn nuts", blog.getPosts().get(0).getSubject());
    assertEquals(101, blog.getAuthor().getId());
    assertEquals("jim", blog.getAuthor().getUsername());
  } finally {
    session.close();
  }
}
 
Example #15
Source File: BaseObjectCrudDelegate.java    From guice-persist-orient with MIT License 5 votes vote down vote up
@Override
public T detach(final T entity) {
    T res = null;
    if (entity != null) {
        res = objectDb.get().detachAll(entity, true);
        if (entity instanceof Proxy) {
            // when entity detached under transaction it gets temporal id
            // this logic will catch real id after commit and set to object
            RidUtils.trackIdChange((Proxy) entity, res);
        }
    }
    return res;
}
 
Example #16
Source File: DetachResultExtension.java    From guice-persist-orient with MIT License 5 votes vote down vote up
private Object detach(final Object pojo, final ODatabaseObject connection) {
    final Object res = connection.detachAll(pojo, true);
    if (pojo instanceof Proxy) {
        // when entity detached under transaction it gets temporal id
        // this logic will catch real id after commit and set to object
        RidUtils.trackIdChange((Proxy) pojo, res);
    }
    return res;
}
 
Example #17
Source File: JavassistProxyTest.java    From mybaties with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldCreateAProxyForAPartiallyLoadedBean() throws Exception {
  ResultLoaderMap loader = new ResultLoaderMap();
  loader.addLoader("id", null, null);
  Object proxy = proxyFactory.createProxy(author, loader, new Configuration(), new DefaultObjectFactory(), new ArrayList<Class<?>>(), new ArrayList<Object>());
  Author author2 = (Author) deserialize(serialize((Serializable) proxy));
  assertTrue(author2 instanceof Proxy);
}
 
Example #18
Source File: JavassistTest.java    From mybaties with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldGetAUserAndGroups() {
  SqlSession sqlSession = sqlSessionFactory.openSession();
  try {
    Mapper mapper = sqlSession.getMapper(Mapper.class);
    User user = mapper.getUser(1);
    Assert.assertEquals("User1", user.getName());
    assertTrue(user instanceof Proxy);
    Assert.assertEquals(1, user.getGroups().size());
  } finally {
    sqlSession.close();
  }
}
 
Example #19
Source File: SqlSessionTest.java    From mybaties with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldSelectBlogWithPostsAndAuthorUsingSubSelectsLazily() throws Exception {
  SqlSession session = sqlMapper.openSession();
  try {
    Blog blog = session.selectOne("org.apache.ibatis.domain.blog.mappers.BlogMapper.selectBlogWithPostsUsingSubSelectLazily", 1);
    Assert.assertTrue(blog instanceof Proxy);
    assertEquals("Jim Business", blog.getTitle());
    assertEquals(2, blog.getPosts().size());
    assertEquals("Corn nuts", blog.getPosts().get(0).getSubject());
    assertEquals(101, blog.getAuthor().getId());
    assertEquals("jim", blog.getAuthor().getUsername());
  } finally {
    session.close();
  }
}
 
Example #20
Source File: TestProxyResource.java    From jax-rs-pac4j with Apache License 2.0 5 votes vote down vote up
@Path("proxied/class")
public TestClassLevelResource proxiedResource() {
    try {
        final ProxyFactory factory = new ProxyFactory();
        factory.setSuperclass(TestClassLevelResource.class);
        final Proxy proxy = (Proxy) factory.createClass().newInstance();
        proxy.setHandler((self, overridden, proceed, args) -> {
            return proceed.invoke(self, args);
        });

        return (TestClassLevelResource) proxy;
    } catch (InstantiationException | IllegalAccessException e) {
        throw new AssertionError(e);
    }
}
 
Example #21
Source File: JavassistProxyFactory.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public HibernateProxy getProxy(
		Serializable id,
		SharedSessionContractImplementor session) throws HibernateException {
	final JavassistLazyInitializer initializer = new JavassistLazyInitializer(
			entityName,
			persistentClass,
			interfaces,
			id,
			getIdentifierMethod,
			setIdentifierMethod,
			componentIdType,
			session,
			overridesEquals
	);

	try {
		final HibernateProxy proxy = (HibernateProxy) proxyClass.newInstance();
		( (Proxy) proxy ).setHandler( initializer );
		initializer.constructed();

		return proxy;
	}
	catch (Throwable t) {
		LOG.error( LOG.bytecodeEnhancementFailed( entityName ), t );
		throw new HibernateException( LOG.bytecodeEnhancementFailed( entityName ), t );
	}
}
 
Example #22
Source File: ThriftClientImpl.java    From thrift-pool-client with Artistic License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 *
 * <p>
 * iface.
 * </p>
 */
@SuppressWarnings("unchecked")
@Override
public <X extends TServiceClient> X iface(Class<X> ifaceClass,
        Function<TTransport, TProtocol> protocolProvider, int hash) {
    List<ThriftServerInfo> servers = serverInfoProvider.get();
    if (servers == null || servers.isEmpty()) {
        throw new NoBackendException();
    }
    hash = Math.abs(hash);
    hash = Math.max(hash, 0);
    ThriftServerInfo selected = servers.get(hash % servers.size());
    logger.trace("get connection for [{}]->{} with hash:{}", ifaceClass, selected, hash);

    TTransport transport = poolProvider.getConnection(selected);
    TProtocol protocol = protocolProvider.apply(transport);

    ProxyFactory factory = new ProxyFactory();
    factory.setSuperclass(ifaceClass);
    factory.setFilter(m -> ThriftClientUtils.getInterfaceMethodNames(ifaceClass).contains(
            m.getName()));
    try {
        X x = (X) factory.create(new Class[] { org.apache.thrift.protocol.TProtocol.class },
                new Object[] { protocol });
        ((Proxy) x).setHandler((self, thisMethod, proceed, args) -> {
            boolean success = false;
            try {
                Object result = proceed.invoke(self, args);
                success = true;
                return result;
            } finally {
                if (success) {
                    poolProvider.returnConnection(selected, transport);
                } else {
                    poolProvider.returnBrokenConnection(selected, transport);
                }
            }
        });
        return x;
    } catch (NoSuchMethodException | IllegalArgumentException | InstantiationException
            | IllegalAccessException | InvocationTargetException e) {
        throw new RuntimeException("fail to create proxy.", e);
    }
}
 
Example #23
Source File: OutlineImpl.java    From datamill with ISC License 4 votes vote down vote up
public OutlineImpl(T members, boolean camelCased) {
    this.members = members;
    ((Proxy) members).setHandler(new OutlineMethodHandler());

    this.camelCased = camelCased;
}
 
Example #24
Source File: JavassistClientProxyFactory.java    From bowman with Apache License 2.0 4 votes vote down vote up
private static Class[] getNonProxyInterfaces(Class<?> entityType) {
	return Arrays.stream(entityType.getInterfaces())
		.filter(i -> !Proxy.class.isAssignableFrom(i))
		.toArray(Class[]::new);
}
 
Example #25
Source File: RidUtils.java    From guice-persist-orient with MIT License 3 votes vote down vote up
/**
 * Shortcut for {@link #trackIdChange(ODocument, Object)}.
 * Used when detaching pojo into pure object to fix temporal id in resulted pojo after commit.
 *
 * @param proxy object proxy
 * @param pojo  detached pure pojo
 */
public static void trackIdChange(final Proxy proxy, final Object pojo) {
    final ODocument doc = OObjectEntitySerializer.getDocument(proxy);
    if (doc != null) {
        trackIdChange(doc, pojo);
    }
}