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:org.apache.hadoop.hbase.ipc.ProtobufRpcClientEngine.java

@Override
public IpcProtocol getProxy(Class<? extends IpcProtocol> protocol, InetSocketAddress addr, User ticket,
        Configuration conf, SocketFactory factory, int rpcTimeout) throws IOException {
    final Invoker invoker = new Invoker(protocol, addr, ticket, conf, factory, rpcTimeout);
    return (IpcProtocol) Proxy.newProxyInstance(protocol.getClassLoader(), new Class[] { protocol }, invoker);
}

From source file:org.example.mybatis.spring.MultipleSqlSessionTemplate.java

private void resetSqlSessionProxy() {

    // Create new proxy.
    SqlSession sqlSessionProxy = (SqlSession) Proxy.newProxyInstance(SqlSessionFactory.class.getClassLoader(),
            new Class[] { SqlSession.class }, new MultipleSqlSessionInterceptor());

    // Overwrite to current proxy.
    try {/* ww  w  . ja  v a 2 s . co m*/

        Field field = this.getClass().getSuperclass().getDeclaredField("sqlSessionProxy"); //$NON-NLS-1$
        field.setAccessible(true);
        field.set(this, sqlSessionProxy);
    } catch (Throwable e) {

        throw new RuntimeException(e);
    }
}

From source file:org.ebayopensource.twin.ElementImpl.java

/** 
 * For internal use only. Creates an Element wrapping the given RemoteObject 
 * This should be used instead of new Element(), as it will instantiate the correct subclass.
 *///from  w ww . j  av a2 s.c  om
public static Element create(RemoteObject o) {
    if (o == null)
        return null;

    List<Class<?>> interfaces = new ArrayList<Class<?>>();
    interfaces.add(Element.class);
    interfaces.add(RemoteResourceInterface.class);

    final Class<? extends ControlType> controlTypeInterface = NameMappings
            .getTypeInterface((String) o.properties.get("controlType"));
    if (controlTypeInterface.equals(Desktop.class))
        return new DesktopImpl(o.session);
    if (controlTypeInterface != null)
        interfaces.add(controlTypeInterface);

    List<Class<? extends ControlPattern>> controlPatternInterfaces = getControlPatternInterfaces(o);
    interfaces.addAll(controlPatternInterfaces);

    final ElementImpl impl = new ElementImpl(o, controlTypeInterface, controlPatternInterfaces);
    if (interfaces.isEmpty())
        return impl;

    final HashSet<Class<?>> implementedPatterns = new HashSet<Class<?>>();
    for (Class<?> iface : interfaces)
        if (isInterfaceExtending(iface, ControlPattern.class))
            implementedPatterns.add(iface);

    return (Element) Proxy.newProxyInstance(ElementImpl.class.getClassLoader(),
            interfaces.toArray(new Class[interfaces.size()]), new InvocationHandler() {
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    Method implMethod = null;
                    try {
                        implMethod = impl.getClass().getMethod(method.getName(), method.getParameterTypes());
                    } catch (NoSuchMethodException e) {
                        implMethod = impl.getClass().getDeclaredMethod(method.getName(),
                                method.getParameterTypes());
                    }
                    Require requirement = implMethod.getAnnotation(Require.class);
                    if (requirement != null) {
                        for (Class<?> pattern : requirement.pattern())
                            if (!implementedPatterns.contains(pattern))
                                throw new TwinException("This "
                                        + (impl.getControlType() == null ? "Unknown" : impl.getControlType())
                                        + " does not implement the control pattern " + pattern.getSimpleName());
                        if (requirement.type() != Void.class)
                            if (controlTypeInterface != requirement.type())
                                throw new TwinException("This "
                                        + (impl.getControlType() == null ? "Unknown" : impl.getControlType())
                                        + " is not of ControlType " + requirement.type().getSimpleName());
                    }
                    try {
                        return implMethod.invoke(impl, args);
                    } catch (InvocationTargetException e) {
                        throw e.getCause();
                    }
                }
            });
}

From source file:com.mirth.connect.connectors.jms.xa.ConnectionFactoryWrapper.java

public Connection createConnection() throws JMSException {
    XAConnection xac = ((XAConnectionFactory) factory).createXAConnection();
    Connection proxy = (Connection) Proxy.newProxyInstance(Connection.class.getClassLoader(),
            new Class[] { Connection.class }, new ConnectionInvocationHandler(xac));
    return proxy;
}

From source file:edu.vt.middleware.gator.util.StaxIndentationHandler.java

/**
 * Convenience method for creating a {@link XMLStreamWriter} that emits
 * indented output using an instance of this class.
 * //from   w w  w.  j  av  a2s.c om
 * @param  out  Output stream that receives written XML.
 *
 * @return  Proxy to a {@link XMLStreamWriter} that has an instance of this
 * class as an invocation handler to provided indented output.
 * 
 * @throws  FactoryConfigurationError
 * On serious errors creating an XMLOutputFactory
 * @throws  XMLStreamException  On errors creating a an XMLStreamWriter from
 * the default factory.
 */
public static XMLStreamWriter createIndentingStreamWriter(final OutputStream out)
        throws XMLStreamException, FactoryConfigurationError {
    final XMLOutputFactory factory = XMLOutputFactory.newInstance();
    factory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true);
    final XMLStreamWriter writer = factory.createXMLStreamWriter(out, "UTF-8");
    return (XMLStreamWriter) Proxy.newProxyInstance(XMLStreamWriter.class.getClassLoader(),
            new Class[] { XMLStreamWriter.class }, new StaxIndentationHandler(writer));
}

From source file:org.bytesoft.openjtcc.supports.spring.PropagateBeanFactoryImpl.java

@SuppressWarnings("unchecked")
public <T> T getBean(Class<T> interfaceClass, String beanId) {
    Object beanInst = this.applicationContext.getBean(beanId);
    if (interfaceClass.isInstance(beanInst) //
            && Compensable.class.isInstance(beanInst)//
    ) {/*  w  w  w. j  a  v  a 2  s . com*/
        PropagateCompensableProxy<Serializable> proxy = new PropagateCompensableProxy<Serializable>();
        proxy.setBeanName(beanId);
        proxy.setTarget((Compensable<Serializable>) beanInst);
        proxy.setProxyId(atomic.incrementAndGet());
        proxy.setTransactionManager(this.transactionManager);

        ClassLoader classLoader = beanInst.getClass().getClassLoader();
        Class<?>[] interfaces = null;
        if (Compensable.class.equals(interfaceClass)) {
            interfaces = new Class[] { interfaceClass };
        } else {
            interfaces = new Class[] { interfaceClass, Compensable.class };
        }
        Object proxyInst = Proxy.newProxyInstance(classLoader, interfaces, proxy);

        proxy.setFacade((Compensable<Serializable>) proxyInst);

        return interfaceClass.cast(proxyInst);
    }
    throw new RuntimeException();
}

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

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

    final Class<?> entityTypeRef = ClassUtils.extractTypeArg(typeRef, AbstractEntitySet.class,
            AbstractSingleton.class);

    final List<Object> items = extractItems(service, entityTypeRef, entitySet, uri, checkInTheContext);

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

From source file:org.cryptomator.ui.Cryptomator.java

private static void addOsxFileOpenHandler() {
    /*/*from  www  .  j a  v  a  2s.  c  o  m*/
     * On OSX we're in an awkward position. We need to register a handler in the main thread of this application. However, we can't
     * even pass objects to the application, so we're forced to use a static CompletableFuture for the handler, which actually opens
     * the file in the application.
     * 
     * Code taken from https://github.com/axet/desktop/blob/master/src/main/java/com/github/axet/desktop/os/mac/AppleHandlers.java
     */
    try {
        final Class<?> applicationClass = Class.forName("com.apple.eawt.Application");
        final Class<?> openFilesHandlerClass = Class.forName("com.apple.eawt.OpenFilesHandler");
        final Method getApplication = applicationClass.getMethod("getApplication");
        final Object application = getApplication.invoke(null);
        final Method setOpenFileHandler = applicationClass.getMethod("setOpenFileHandler",
                openFilesHandlerClass);

        final ClassLoader openFilesHandlerClassLoader = openFilesHandlerClass.getClassLoader();
        final OpenFilesHandlerClassHandler openFilesHandlerHandler = new OpenFilesHandlerClassHandler();
        final Object openFilesHandlerObject = Proxy.newProxyInstance(openFilesHandlerClassLoader,
                new Class<?>[] { openFilesHandlerClass }, openFilesHandlerHandler);

        setOpenFileHandler.invoke(application, openFilesHandlerObject);
    } catch (ReflectiveOperationException | RuntimeException e) {
        // Since we're trying to call OS-specific code, we'll just have
        // to hope for the best.
        LOG.error("exception adding OSX file open handler", e);
    }
}

From source file:org.zenoss.zep.dao.impl.EventArchiveDaoImpl.java

public EventArchiveDaoImpl(DataSource dataSource, PartitionConfig partitionConfig,
        DatabaseCompatibility databaseCompatibility) {
    this.template = (SimpleJdbcOperations) Proxy.newProxyInstance(SimpleJdbcOperations.class.getClassLoader(),
            new Class<?>[] { SimpleJdbcOperations.class }, new SimpleJdbcTemplateProxy(dataSource));
    this.partitionTableConfig = partitionConfig.getConfig(TABLE_EVENT_ARCHIVE);
    this.databaseCompatibility = databaseCompatibility;
    this.uuidConverter = databaseCompatibility.getUUIDConverter();
    this.partitioner = databaseCompatibility.getRangePartitioner(dataSource, TABLE_EVENT_ARCHIVE,
            COLUMN_LAST_SEEN, partitionTableConfig.getPartitionDuration(),
            partitionTableConfig.getPartitionUnit());
}

From source file:org.dimitrovchi.conf.service.ServiceParameterUtils.java

@SuppressWarnings({ "element-type-mismatch" })
public static <P> P mergeAnnotationParameters() {
    final AnnotationParameters aParameters = annotationParameters();
    return (P) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
            aParameters.annotations.toArray(new Class[aParameters.annotations.size()]),
            new InvocationHandler() {
                @Override//from w  ww.j a va 2 s  . c o m
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    if ("toString".equals(method.getName())) {
                        return reflectToString(aParameters.topCaller.getSimpleName(), proxy);
                    }
                    final Class<?> annotationClass = method.getDeclaringClass();
                    final List<Annotation> annotations = aParameters.annotationMap.containsKey(annotationClass)
                            ? aParameters.annotationMap.get(annotationClass)
                            : Collections.<Annotation>emptyList();
                    for (final Annotation annotation : annotations) {
                        final Object value = method.invoke(annotation, args);
                        if (!Objects.deepEquals(method.getDefaultValue(), value)) {
                            return value;
                        }
                    }
                    return method.getDefaultValue();
                }
            });
}