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.netflix.spinnaker.clouddriver.aws.security.sdkclient.ProxyHandlerBuilder.java

public <T extends AwsClientBuilder<T, U>, U> U getProxyHandler(Class<U> interfaceKlazz, Class<T> impl,
        NetflixAmazonCredentials amazonCredentials, String region, boolean skipEdda) {
    requireNonNull(amazonCredentials, "Credentials cannot be null");
    try {//w ww  . j  a va2  s .c om
        U delegate = awsSdkClientSupplier.getClient(impl, interfaceKlazz, amazonCredentials.getName(),
                amazonCredentials.getCredentialsProvider(), region);
        if (skipEdda || !amazonCredentials.getEddaEnabled()
                || eddaTimeoutConfig.getDisabledRegions().contains(region)) {
            return delegate;
        }
        return interfaceKlazz.cast(Proxy.newProxyInstance(getClass().getClassLoader(),
                new Class[] { interfaceKlazz },
                getInvocationHandler(delegate, interfaceKlazz.getSimpleName(), region, amazonCredentials)));
    } catch (RuntimeException re) {
        throw re;
    } catch (Exception e) {
        throw new RuntimeException("Instantiation of client implementation failed!", e);
    }
}

From source file:org.apache.hadoop.hbase.ipc.ProtobufRpcEngine.java

@Override
public VersionedProtocol getProxy(Class<? extends VersionedProtocol> protocol, long clientVersion,
        InetSocketAddress addr, User ticket, Configuration conf, SocketFactory factory, int rpcTimeout)
        throws IOException {
    final Invoker invoker = new Invoker(protocol, addr, ticket, conf, factory, rpcTimeout);
    return (VersionedProtocol) Proxy.newProxyInstance(protocol.getClassLoader(), new Class[] { protocol },
            invoker);/* w  w  w  .ja v  a 2  s . c  o m*/
}

From source file:com.delphix.session.module.rmi.impl.RmiFactoryImpl.java

@Override
public <T> T createProxy(final Class<T> type, final ServiceNexus nexus, final UUID objectId) {
    Object proxy = Proxy.newProxyInstance(RmiFactoryImpl.class.getClassLoader(), new Class[] { type },
            new InvocationHandler() {
                private RmiMethodOrdering ifm = new RmiMethodOrdering(type);

                @Override//from w  w  w. j a  v a2  s .c o  m
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    if (args == null) {
                        args = new Object[0];
                    }

                    if (method.getName().equals("close") && args.length == 0) {
                        ObjectDestroyRequest request = new ObjectDestroyRequest();
                        request.setObjectId(objectId);

                        try {
                            nexus.execute(request).get();
                        } catch (InterruptedException e) {
                            throw new DelphixInterruptedException(e);
                        } catch (ExecutionException e) {
                            throw new RuntimeException(ExceptionUtil.unwrap(e));
                        }
                        return null;
                    } else {
                        MethodCallRequest request = new MethodCallRequest();
                        request.setObjectId(objectId);
                        request.setMethod(ifm.getPlacement(method));
                        request.setArguments(args);

                        MethodCallResponse response;
                        try {
                            response = (MethodCallResponse) nexus.execute(request).get();
                        } catch (InterruptedException e) {
                            throw new DelphixInterruptedException(e);
                        } catch (ExecutionException e) {
                            throw new RuntimeException(ExceptionUtil.unwrap(e));
                        }

                        if (response.getException()) {
                            throw ExceptionUtil.unwrap(new ExecutionException((Throwable) response.getValue()));
                        } else {
                            return response.getValue();
                        }
                    }
                }
            });

    return type.cast(proxy);
}

From source file:org.jboss.rusheye.result.writer.PrettyXMLStreamWriter.java

public static XMLStreamWriter pretty(XMLStreamWriter writer) {
    return (XMLStreamWriter) Proxy.newProxyInstance(writer.getClass().getClassLoader(),
            new Class[] { XMLStreamWriter.class }, new PrettyXMLStreamWriter(writer));
}

From source file:com.edmunds.autotest.ClassUtil.java

public static Object instanceClass(Class cls, String msg) {
    if (cls.isInterface()) {
        return Proxy.newProxyInstance(cls.getClassLoader(), new Class[] { cls }, NOOP_HANDLER);
    } else if (isStandardClass(cls) && hasDefaultConstructor(cls)) {
        try {/*from  w  w  w.  j ava 2 s .  c  o  m*/
            Constructor constructor = getDefaultConstructor(cls);
            constructor.setAccessible(true);

            return constructor.newInstance();

        } catch (InvocationTargetException e) {
            log.error(msg, e);
            throw new RuntimeException(msg, e);
        } catch (InstantiationException e) {
            log.error(msg, e);
            throw new RuntimeException(msg, e);
        } catch (IllegalAccessException e) {
            log.error(msg, e);
            throw new RuntimeException(msg, e);
        }
    }
    return null;
}

From source file:org.jdag.config.ConfigurationProvider.java

/**
 *  A factory method that creates a proxy to read from underlying
 *  property configuration.// ww w.  j  av  a  2 s.  c  o  m
 */
@SuppressWarnings("unchecked")
public static <T> T makeConfiguration(Class<T> configDefinitionClass, String propertyFile) {
    Source s = configDefinitionClass.getAnnotation(Source.class);
    try {
        ConfigurationProvider provider = propertyFile != null
                ? new ConfigurationProvider(propertyFile, s.prefix(), configDefinitionClass)
                : new ConfigurationProvider(s.prefix(), configDefinitionClass);

        return (T) Proxy.newProxyInstance(configDefinitionClass.getClassLoader(),
                new Class<?>[] { configDefinitionClass }, provider);
    } catch (IllegalArgumentException e) {
        throw new RuntimeException(e);
    } catch (ConfigurationException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.eclipse.wb.internal.rcp.model.rcp.ViewPartInfo.java

/**
 * Initializes this {@link ViewPart} with {@link IViewSite}.
 *//*from w w w  .j a  v a  2s . c  o m*/
@Override
protected void applyActionBars() throws Exception {
    ClassLoader editorLoader = JavaInfoUtils.getClassLoader(this);
    Class<?> viewSiteClass = editorLoader.loadClass("org.eclipse.ui.IViewSite");
    // create IViewSite
    Object viewSite = Proxy.newProxyInstance(editorLoader, new Class<?>[] { viewSiteClass },
            new InvocationHandler() {
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    String signature = ReflectionUtils.getMethodSignature(method);
                    if (signature.equals("toString()")) {
                        return "IViewSite_stub";
                    }
                    if (signature.equals("hashCode()")) {
                        return 0;
                    }
                    if (signature.equals("getActionBars()")) {
                        return m_actionBars;
                    }
                    if (signature.equals("getId()")) {
                        return getID();
                    }
                    if (signature.equals("getSecondaryId()")) {
                        return null;
                    }
                    if (signature.equals("getWorkbenchWindow()")) {
                        return DesignerPlugin.getActiveWorkbenchWindow();
                    }
                    throw new NotImplementedException(method.toString());
                }
            });
    // call init(IViewSite)
    ReflectionUtils.invokeMethod(getObject(), "init(org.eclipse.ui.IViewSite)", viewSite);
}

From source file:com.google.code.guice.repository.configuration.PersistenceUnitConfiguration.java

/**
 * Represents current configuration as an EntityManager proxy. This is required for cases where
 * Configuration's EM can be changed at runtime - such as in Web-environments (see {@link PersistFilter}.
 *
 * @return proxy with EntityManager interface bound to current EM instance
 *
 * @see PersistenceUnitsConfigurationManager#changeEntityManager(String, EntityManager)
 * @see PersistFilter/*from  w ww  .  j a v a  2  s . c o m*/
 */
public EntityManager asEntityManagerProxy() {
    return (EntityManager) Proxy.newProxyInstance(getClass().getClassLoader(),
            new Class[] { EntityManager.class }, new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    try {
                        return method.invoke(getEntityManager(), args);
                    } catch (InvocationTargetException e) {
                        Throwable t = e.getCause();
                        if (t != null) {
                            throw t;
                        } else {
                            throw e;
                        }
                    }
                }
            });
}

From source file:com.microsoft.tfs.util.listeners.MulticastListenerProxy.java

/**
 * Creates a new multicasting listener proxy that implements the specified
 * listener interface and uses the specified {@link ListenerList}. The proxy
 * listener will use the specified {@link ListenerExceptionHandler} for
 * exception handling.// www  .java 2  s. c o m
 *
 * @param listenerInterface
 *        The listener interface that the returned object will implement
 *        (must not be <code>null</code>)
 * @param listenerList
 *        The {@link ListenerList} that is delegated to by the proxy (must
 *        not be <code>null</code>)
 * @param exceptionHandler
 *        the {@link ListenerExceptionHandler} used to handle any exceptions
 *        thrown by the real listeners
 * @return a new proxy instance as described above
 */
public static Object createProxy(final Class listenerInterface, final ListenerList listenerList,
        final ListenerExceptionHandler exceptionHandler) {
    Check.notNull(listenerInterface, "listenerInterface"); //$NON-NLS-1$
    Check.notNull(listenerList, "listenerList"); //$NON-NLS-1$
    Check.notNull(exceptionHandler, "exceptionHandler"); //$NON-NLS-1$

    final Class[] classesToProxy = new Class[] { listenerInterface };

    final InvocationHandler invocationHandler = new MLPInvocationHandler(listenerList, exceptionHandler);

    return Proxy.newProxyInstance(listenerInterface.getClassLoader(), classesToProxy, invocationHandler);
}

From source file:se.trillian.goodies.spring.DomainObjectFactoryFactoryBean.java

@Override
protected Object createInstance() throws Exception {
    return Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[] { factoryClass },
            new FactoryInvocationHandler());
}