Example usage for java.lang.reflect Proxy newProxyInstance

List of usage examples for java.lang.reflect Proxy newProxyInstance

Introduction

In this page you can find the example usage for java.lang.reflect Proxy newProxyInstance.

Prototype

private static Object newProxyInstance(Class<?> caller, 
            Constructor<?> cons, InvocationHandler h) 

Source Link

Usage

From source file:com.amazonaws.hal.client.HalJsonResourceUnmarshallerTest.java

@Test
public void testTypes() throws Exception {
    HalResource halResource = parseHalResourceFromClasspath("types.resource");

    Assert.assertNotNull(halResource);/* ww w .j a v a2s . c  o m*/

    Types types = (Types) Proxy.newProxyInstance(Types.class.getClassLoader(), new Class<?>[] { Types.class },
            new HalResourceInvocationHandler(halResource, halResource._getSelfHref(), null));

    Assert.assertNotNull(types.getIntegerList());
    Assert.assertEquals(3, types.getIntegerList().size());
    Assert.assertEquals(1, (long) types.getIntegerList().get(0));

    Assert.assertNotNull(types.getIntegerMap());
    Assert.assertEquals(3, types.getIntegerMap().size());
    Assert.assertEquals(1, (long) types.getIntegerMap().get("one"));
}

From source file:org.jboss.spring.vfs.VFSResourcePatternResolvingHelper.java

/**
 * Get VFS resources.//from ww w.  ja va 2s .c o  m
 *
 * @param rootURL     the root URL
 * @param subPattern  the sub pattern
 * @param pathMatcher the PathMatcher used for matching directories
 * @return vfs resources list
 * @throws java.io.IOException for any error
 */
public static Set<Resource> getVFSResources(URL rootURL, String subPattern, PathMatcher pathMatcher)
        throws IOException {
    log.debug("Scanning url: " + rootURL + ", sub-pattern: " + subPattern);
    Object root = VFSResource.getChild(rootURL);
    String pathName = VFSUtil.invokeVfsMethod(VFSUtil.VIRTUAL_FILE_METHOD_GET_PATH_NAME, root);
    PatternVirtualFileVisitorInvocationHandler visitorInvocationHandler = new PatternVirtualFileVisitorInvocationHandler(
            pathName, subPattern, pathMatcher);
    Object visitor = Proxy.newProxyInstance(VFSUtil.VIRTUAL_FILE_VISITOR_CLASS.getClassLoader(),
            new Class<?>[] { VFSUtil.VIRTUAL_FILE_VISITOR_CLASS }, visitorInvocationHandler);
    VFSUtil.invokeVfsMethod(VFSUtil.VIRTUAL_FILE_METHOD_VISIT, root, visitor);
    if (log.isTraceEnabled()) {
        log.trace("Found resources: " + visitor);
    }
    return visitorInvocationHandler.getResources();
}

From source file:com.wantscart.jade.core.JadeDaoFactoryBean.java

@SuppressWarnings("unchecked")
protected T createDAO(Class<T> daoClass) {
    Definition definition = new Definition(daoClass);
    DataAccess dataAccess = dataAccessProvider.createDataAccess(daoClass);
    JadeDaoInvocationHandler handler = new JadeDaoInvocationHandler(applicationContext, dataAccess, definition);
    return (T) Proxy.newProxyInstance(ClassUtils.getDefaultClassLoader(), new Class[] { daoClass }, handler);
}

From source file:com.healthmarketscience.rmiio.RemoteWrapper.java

/**
 * Simple wrapper generator which creates a Proxy for the given remote
 * interface. This proxy will make all the remote calls through the {@link #invoke} method which makes the actual method calls on the
 * underlying stub within the retry logic.
 * /*  w ww.ja  v a 2  s .c o m*/
 * @param iface
 *           the remote interface to be implemented
 * @param stub
 *           the underlying implementation of the remote interface which
 *           will actually make the remote calls
 * @param retry
 *           the retry policy to use for the remote calls
 * @param log
 *           the log to use during retry handling
 * @return a proxy for the given interface using the given retry strategy
 */
public static <R> R wrap(Class<R> iface, R stub, RemoteRetry retry, Log log) {
    RemoteWrapper<R> wrapper = new RemoteWrapper<R>(stub, retry, log);
    return iface.cast(Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
            new Class<?>[] { iface }, wrapper));
}

From source file:org.openeos.hibernate.internal.SessionFactoryManagerOsgiService.java

@Override
public void init() {
    LOG.debug("Initializing session factory proxy and registering it as OSGi Service");
    proxyHandler = new SessionFactoryProxyHandler(this);
    proxySessionFactory = (SessionFactory) Proxy.newProxyInstance(this.getClass().getClassLoader(),
            new Class<?>[] { SessionFactory.class }, proxyHandler);
    sessionFactoryRegistration = bundleContext.registerService(SessionFactory.class, proxySessionFactory, null);

    LOG.debug("Retrieving new session to establish initial session factory");
    proxySessionFactory.openSession().close();
}

From source file:org.apache.ode.utils.LoggingInterceptor.java

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    try {/*  w  w w .  j a  v a2 s .  c  o m*/
        if (method.getDeclaringClass() == DataSource.class && "getConnection".equals(method.getName())) {
            Connection conn = (Connection) method.invoke(_delegate, args);
            print("getConnection (tx=" + conn.getTransactionIsolation() + ")");
            return Proxy.newProxyInstance(_delegate.getClass().getClassLoader(),
                    new Class[] { Connection.class }, new LoggingInterceptor<Connection>(conn, _log));
        } else if (method.getDeclaringClass() == Connection.class
                && Statement.class.isAssignableFrom(method.getReturnType())) {
            Statement stmt = (Statement) method.invoke(_delegate, args);
            print(method, args);
            return Proxy.newProxyInstance(_delegate.getClass().getClassLoader(),
                    new Class[] { method.getReturnType() }, new LoggingInterceptor<Statement>(stmt, _log));
        } else {
            print(method, args);
            return method.invoke(_delegate, args);
        }
    } catch (InvocationTargetException e) {
        throw e.getTargetException();
    }
}

From source file:com.nineteendrops.tracdrops.client.core.TracClientObjectFactoryImpl.java

protected Object newInstance(ClassLoader classLoader, final Class aClass, final String remoteName) {

    return Proxy.newProxyInstance(classLoader, new Class[] { aClass }, new InvocationHandler() {

        public Object invoke(Object pProxy, Method pMethod, Object[] pArgs) throws Throwable {

            String tracClassName = Utils.findTracClassName(aClass);
            if (tracClassName == null) {
                throw new TracException(
                        MessageUtils.registerErrorLog(log, "core.no.trac.classname.found", aClass.getName()));
            }//from w  w w.  j a  va2 s.  c  o m

            TracClassMethod tracClassMethodMetadata = Utils.getTracClassMethodAnnotation(pMethod);

            String tracClassMethodName = Utils.buildTracMethodNameInvocation(tracClassName,
                    tracClassMethodMetadata);

            Class returnDecoder = tracClassMethodMetadata.returnDecoder();

            ArrayList encodedPARGS = new ArrayList();
            Annotation[][] parameterAnnotations = pMethod.getParameterAnnotations();

            int parameterOrder = 0;
            ArrayList keptParametersForDecoder = new ArrayList();
            for (Annotation[] annotations : parameterAnnotations) {

                Object currentParameter = pArgs[parameterOrder];
                boolean skipInvocationRegistration = false;
                for (Annotation annotation : annotations) {
                    if (annotation instanceof TracParameterEncoder) {
                        Class encoder = ((TracParameterEncoder) annotation).encoder();
                        ParameterEncoder parameterEncoder = (ParameterEncoder) encoder.newInstance();
                        currentParameter = parameterEncoder.encode(tracProperties, currentParameter);
                    }
                    if (annotation instanceof TracParameterPolicy) {
                        TracParameterPolicy tracParameterPolicy = (TracParameterPolicy) annotation;
                        if (tracParameterPolicy.keptForDecoder()) {
                            keptParametersForDecoder.add(currentParameter);
                        }
                        if (tracParameterPolicy.removeFromInvocation()) {
                            skipInvocationRegistration = true;
                        }
                    }
                }
                if (!skipInvocationRegistration) {
                    if (currentParameter instanceof MultiParameter) {
                        MultiParameter multiParameter = (MultiParameter) currentParameter;
                        for (Object objectFromMultiparameter : multiParameter.getParameters()) {
                            encodedPARGS.add(objectFromMultiparameter);
                        }

                    } else {
                        encodedPARGS.add(currentParameter);
                    }
                }
                parameterOrder++;
            }

            if (MulticallManager.multicallActive()) {

                MulticallManager.multicallRegisterCall(aClass, tracClassMethodName, encodedPARGS.toArray(),
                        returnDecoder, keptParametersForDecoder);

                if (log.isDebugEnabled()) {
                    log.debug(MessageUtils.getMessage("core.invocation.multicall"));
                }

                return null;

            } else {

                MulticallManager.multicallStart(tracInvocationObjectFactory);
                MulticallManager.multicallRegisterCall(aClass, tracClassMethodName, encodedPARGS.toArray(),
                        returnDecoder, keptParametersForDecoder);

                ArrayList result = MulticallManager.launchMulticall(tracProperties);

                if (log.isDebugEnabled()) {
                    log.debug(MessageUtils.getMessage("core.invocation.singlecall"));
                }

                return result.get(0);

            }
        }
    });

}

From source file:org.apache.olingo.ext.proxy.utils.ProxyUtils.java

public static Object getEntitySetProxy(final AbstractService<?> service, final Class<?> typeRef,
        final URI uri) {

    return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class<?>[] { typeRef },
            EntitySetInvocationHandler.getInstance(typeRef, service, uri));
}

From source file:org.bytesoft.openjtcc.supports.marshall.TerminatorMarshallerImpl.java

@Override
public RemoteTerminator unmarshallTerminator(TerminatorInfo info) throws IOException {
    RemoteTerminatorHandler handler = new RemoteTerminatorHandler();
    handler.setRemoteTerminatorInfo(info);
    String beanName = this.getBeanName(info);
    RemoteInvocationService remoteService = null;
    try {/*w  w w  . j  a va2 s .  c  o m*/
        remoteService = (RemoteInvocationService) this.applicationContext.getBean(beanName);
        handler.setRemoteInvocationService(remoteService);
    } catch (BeansException ex) {
        handler.setRemoteServiceFactory(this);
    }
    return (RemoteTerminator) Proxy.newProxyInstance(RemoteTerminator.class.getClassLoader(),
            new Class[] { RemoteTerminator.class }, handler);
}

From source file:org.blocks4j.feature.toggle.factory.FeatureToggleFactory.java

private <T> T createFeatureProxy(String featureName, Class<? super T> commonInterface, T featureOn,
        T featureOff) {//from w  w w  .  j a v  a2  s  .  c o m
    this.validateParams(featureName, commonInterface, featureOn, featureOff);
    Feature<T> feature;

    if (this.allowProbabilisticFeatures) {
        feature = new ProbabilisticFeature<T>();
    } else {
        feature = new Feature<T>();
    }

    feature.setConfig(this.config);
    feature.setCommonsInterface(commonInterface);
    feature.setOn(featureOn);
    feature.setOff(featureOff);
    feature.setName(featureName);
    feature.init();

    @SuppressWarnings("unchecked")
    T proxy = (T) Proxy.newProxyInstance(commonInterface.getClassLoader(), new Class[] { commonInterface },
            feature);

    LOGGER.info(String.format("Feature [%s] initialized , Object for ON is [%s] and Object for OFF is [%s]",
            featureName, featureOn.getClass().getSimpleName(), featureOff.getClass().getSimpleName()));
    toggleList.add(feature);
    return proxy;
}