Java Code Examples for javassist.util.proxy.ProxyFactory#setFilter()

The following examples show how to use javassist.util.proxy.ProxyFactory#setFilter() . 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: ProxyUtils.java    From chrome-devtools-java-client with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a proxy class to a given abstract clazz supplied with invocation handler for
 * un-implemented/abstrat methods.
 *
 * @param clazz Proxy to class.
 * @param paramTypes Ctor param types.
 * @param args Ctor args.
 * @param invocationHandler Invocation handler.
 * @param <T> Class type.
 * @return Proxy instance.
 */
@SuppressWarnings("unchecked")
public static <T> T createProxyFromAbstract(
    Class<T> clazz, Class[] paramTypes, Object[] args, InvocationHandler invocationHandler) {
  ProxyFactory proxyFactory = new ProxyFactory();
  proxyFactory.setSuperclass(clazz);
  proxyFactory.setFilter(method -> Modifier.isAbstract(method.getModifiers()));
  try {
    return (T)
        proxyFactory.create(
            paramTypes,
            args,
            (o, method, method1, objects) -> invocationHandler.invoke(o, method, objects));
  } catch (Exception e) {
    LOGGER.error("Failed creating proxy from abstract class", e);
    throw new RuntimeException("Failed creating proxy from abstract class", e);
  }
}
 
Example 2
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 3
Source File: JavassistLazyInitializer.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public static Class getProxyFactory(
		Class persistentClass,
        Class[] interfaces) throws HibernateException {
	// note: interfaces is assumed to already contain HibernateProxy.class

	try {
		ProxyFactory factory = new ProxyFactory();
		factory.setSuperclass( interfaces.length == 1 ? persistentClass : null );
		factory.setInterfaces( interfaces );
		factory.setFilter( FINALIZE_FILTER );
		return factory.createClass();
	}
	catch ( Throwable t ) {
		LogFactory.getLog( BasicLazyInitializer.class ).error(
				"Javassist Enhancement failed: "
				+ persistentClass.getName(), t
		);
		throw new HibernateException(
				"Javassist Enhancement failed: "
				+ persistentClass.getName(), t
		);
	}
}
 
Example 4
Source File: Partial.java    From FreeBuilder with Apache License 2.0 6 votes vote down vote up
/**
 * Constructs a partial instance of abstract type {@code cls}, passing {@code args} into its
 * constructor.
 *
 * <p>The returned object will throw an {@link UnsupportedOperationException} from any
 * unimplemented methods.
 */
public static <T> T of(Class<T> cls, Object... args) {
  checkIsValidPartial(cls);
  try {
    Constructor<?> constructor = cls.getDeclaredConstructors()[0];
    ProxyFactory factory = new ProxyFactory();
    factory.setSuperclass(cls);
    factory.setFilter(new MethodFilter() {
      @Override public boolean isHandled(Method m) {
        return Modifier.isAbstract(m.getModifiers());
      }
    });
    @SuppressWarnings("unchecked")
    T partial = (T) factory.create(
        constructor.getParameterTypes(), args, new ThrowingMethodHandler());
    return partial;
  } catch (Exception e) {
    throw new RuntimeException("Failed to instantiate " + cls, e);
  }
}
 
Example 5
Source File: TransactionalClassProxy.java    From seed with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Create a transactional proxy around the provided {@link TransactionalLink}.
 *
 * @param <T>               the interface used to create the proxy.
 * @param clazz             the class representing the transacted resource.
 * @param transactionalLink the link to access the instance of the transacted resource.
 * @return the proxy.
 */
@SuppressWarnings("unchecked")
public static <T> T create(Class<T> clazz, final TransactionalLink<T> transactionalLink) {
    try {
        ProxyFactory factory = new ProxyFactory();
        factory.setSuperclass(clazz);
        if (AutoCloseable.class.isAssignableFrom(clazz)) {
            factory.setInterfaces(new Class<?>[]{IgnoreAutoCloseable.class});
        }
        factory.setFilter(method -> !method.getDeclaringClass().equals(Object.class));
        return (T) factory.create(new Class<?>[0], new Object[0], new TransactionalClassProxy<>(transactionalLink));
    } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {
        throw SeedException.wrap(e, TransactionErrorCode.UNABLE_TO_CREATE_TRANSACTIONAL_PROXY).put("class",
                clazz.getName());
    }
}
 
Example 6
Source File: TrivialClassCreationBenchmark.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * Performs a benchmark for a trivial class creation using javassist proxies.
 *
 * @return The created instance, in order to avoid JIT removal.
 */
@Benchmark
public Class<?> benchmarkJavassist() {
    ProxyFactory proxyFactory = new ProxyFactory() {
        protected ClassLoader getClassLoader() {
            return newClassLoader();
        }
    };
    proxyFactory.setUseCache(false);
    proxyFactory.setUseWriteReplace(false);
    proxyFactory.setSuperclass(baseClass);
    proxyFactory.setFilter(new MethodFilter() {
        public boolean isHandled(Method method) {
            return false;
        }
    });
    return proxyFactory.createClass();
}
 
Example 7
Source File: JavassistProxifier.java    From vraptor4 with Apache License 2.0 6 votes vote down vote up
@Override
public <T> T proxify(Class<T> type, MethodInvocation<? super T> handler) {
	final ProxyFactory factory = new ProxyFactory();
	factory.setFilter(IGNORE_BRIDGE_AND_OBJECT_METHODS);
	Class<?> rawType = extractRawType(type);

	if (type.isInterface()) {
		factory.setInterfaces(new Class[] { rawType });
	} else {
		factory.setSuperclass(rawType);
	}

	Object instance = createInstance(type, handler, factory);
	logger.debug("a proxy for {} was created as {}", type, instance.getClass());

	return (T) instance;
}
 
Example 8
Source File: ProxyDetectionTest.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
@Test
public void testJavassistProxy() throws IllegalAccessException, InstantiationException {
    ProxyFactory f = new ProxyFactory();
    f.setSuperclass(User.class);
    f.setFilter(m -> !m.getName().equals("finalize"));
    Class proxyClass = f.createClass();
    assertTrue(ClassUtils.isProxy(proxyClass));
}
 
Example 9
Source File: JavassistPartialObjectFactory.java    From spearal-java with Apache License 2.0 5 votes vote down vote up
@Override
public Class<?> createValue(SpearalContext context, Class<?> key, Object unused) {
	context.getSecurizer().checkDecodable(key);
	
	ProxyFactory proxyFactory = new ProxyFactory();
	proxyFactory.setFilter(new PartialObjectFilter(context, key));
	proxyFactory.setSuperclass(key);
	proxyFactory.setInterfaces(new Class<?>[] { ExtendedPartialObjectProxy.class });
	return proxyFactory.createClass();
}
 
Example 10
Source File: ClassByExtensionBenchmark.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * Performs a benchmark of a class extension using javassist proxies.
 *
 * @return The created instance, in order to avoid JIT removal.
 * @throws java.lang.Exception If the invocation causes an exception.
 */
@Benchmark
public ExampleClass benchmarkJavassist() throws Exception {
    ProxyFactory proxyFactory = new ProxyFactory() {
        protected ClassLoader getClassLoader() {
            return newClassLoader();
        }
    };
    proxyFactory.setUseCache(false);
    proxyFactory.setUseWriteReplace(false);
    proxyFactory.setSuperclass(baseClass);
    proxyFactory.setFilter(new MethodFilter() {
        public boolean isHandled(Method method) {
            return method.getDeclaringClass() == baseClass;
        }
    });
    @SuppressWarnings("unchecked")
    Object instance = proxyFactory.createClass().getDeclaredConstructor().newInstance();
    ((javassist.util.proxy.Proxy) instance).setHandler(new MethodHandler() {
        public Object invoke(Object self,
                             Method thisMethod,
                             Method proceed,
                             Object[] args) throws Throwable {
            return proceed.invoke(self, args);
        }
    });
    return (ExampleClass) instance;
}
 
Example 11
Source File: JavassistLazyInitializer.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public static HibernateProxy getProxy(
		final String entityName,
        final Class persistentClass,
        final Class[] interfaces,
        final Method getIdentifierMethod,
        final Method setIdentifierMethod,
        AbstractComponentType componentIdType,
        final Serializable id,
        final SessionImplementor session) throws HibernateException {
	// note: interface is assumed to already contain HibernateProxy.class
	try {
		final JavassistLazyInitializer instance = new JavassistLazyInitializer(
				entityName,
		        persistentClass,
		        interfaces,
		        id,
		        getIdentifierMethod,
		        setIdentifierMethod,
		        componentIdType,
		        session
		);
		ProxyFactory factory = new ProxyFactory();
		factory.setSuperclass( interfaces.length == 1 ? persistentClass : null );
		factory.setInterfaces( interfaces );
		factory.setFilter( FINALIZE_FILTER );
		Class cl = factory.createClass();
		final HibernateProxy proxy = ( HibernateProxy ) cl.newInstance();
		( ( ProxyObject ) proxy ).setHandler( instance );
		instance.constructed = true;
		return proxy;
	}
	catch ( Throwable t ) {
		LogFactory.getLog( BasicLazyInitializer.class ).error(
				"Javassist Enhancement failed: " + entityName, t
		);
		throw new HibernateException(
				"Javassist Enhancement failed: "
				+ entityName, t
		);
	}
}
 
Example 12
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 13
Source File: ClassByImplementationBenchmark.java    From byte-buddy with Apache License 2.0 4 votes vote down vote up
/**
 * Performs a benchmark of an interface implementation using javassist proxies.
 *
 * @return The created instance, in order to avoid JIT removal.
 * @throws java.lang.Exception If the reflective invocation causes an exception.
 */
@Benchmark
public ExampleInterface benchmarkJavassist() throws Exception {
    ProxyFactory proxyFactory = new ProxyFactory() {
        protected ClassLoader getClassLoader() {
            return newClassLoader();
        }
    };
    proxyFactory.setUseCache(false);
    proxyFactory.setUseWriteReplace(false);
    proxyFactory.setSuperclass(Object.class);
    proxyFactory.setInterfaces(new Class<?>[]{baseClass});
    proxyFactory.setFilter(new MethodFilter() {
        public boolean isHandled(Method method) {
            return true;
        }
    });
    @SuppressWarnings("unchecked")
    Object instance = proxyFactory.createClass().getDeclaredConstructor().newInstance();
    ((javassist.util.proxy.Proxy) instance).setHandler(new MethodHandler() {
        public Object invoke(Object self,
                             Method thisMethod,
                             Method proceed,
                             Object[] args) throws Throwable {
            Class<?> returnType = thisMethod.getReturnType();
            if (returnType.isPrimitive()) {
                if (returnType == boolean.class) {
                    return defaultBooleanValue;
                } else if (returnType == byte.class) {
                    return defaultByteValue;
                } else if (returnType == short.class) {
                    return defaultShortValue;
                } else if (returnType == char.class) {
                    return defaultCharValue;
                } else if (returnType == int.class) {
                    return defaultIntValue;
                } else if (returnType == long.class) {
                    return defaultLongValue;
                } else if (returnType == float.class) {
                    return defaultFloatValue;
                } else {
                    return defaultDoubleValue;
                }
            } else {
                return defaultReferenceValue;
            }
        }
    });
    return (ExampleInterface) instance;
}