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:uk.co.unclealex.persistence.jdo.spring.TransactionAwarePersistenceManagerFactoryProxy.java

/**
 * Set the target JDO PersistenceManagerFactory that this proxy should
 * delegate to. This should be the raw PersistenceManagerFactory, as accessed
 * by JdoTransactionManager./*from   www  .j ava 2  s .  c  om*/
 * 
 * @see org.springframework.orm.jdo.JdoTransactionManager
 */
public void setTargetPersistenceManagerFactory(JDOPersistenceManagerFactory target) {
    Assert.notNull(target, "Target PersistenceManagerFactory must not be null");
    this.target = target;
    Class[] ifcs = ClassUtils.getAllInterfacesForClass(target.getClass(), target.getClass().getClassLoader());
    this.proxy = (PersistenceManagerFactory) Proxy.newProxyInstance(target.getClass().getClassLoader(), ifcs,
            new PersistenceManagerFactoryInvocationHandler());
}

From source file:org.apache.hadoop.hbase.ipc.bak.SchedulableWritableRpcEngine.java

/** Construct a client-side proxy object that implements the named protocol,
 * talking to a server at the named address. */
@Override//from ww w  .  j a  v a  2 s .co  m
public <T extends VersionedProtocol> T getProxy(Class<T> protocol, long clientVersion, InetSocketAddress addr,
        Configuration conf, int rpcTimeout) throws IOException {
    if (this.client == null) {
        throw new IOException("Client must be initialized by calling setConf(Configuration)");
    }

    T proxy = (T) Proxy.newProxyInstance(protocol.getClassLoader(), new Class[] { protocol }, new Invoker(
            client, protocol, addr, userProvider.getCurrent(), conf, HBaseRPC.getRpcTimeout(rpcTimeout)));

    /*
     * TODO: checking protocol version only needs to be done once when we setup a new
     * HBaseClient.Connection.  Doing it every time we retrieve a proxy instance is resulting
     * in unnecessary RPC traffic.
     */
    long serverVersion = ((VersionedProtocol) proxy).getProtocolVersion(protocol.getName(), clientVersion);
    if (serverVersion != clientVersion) {
        throw new HBaseRPC.VersionMismatch(protocol.getName(), clientVersion, serverVersion);
    }

    return proxy;
}

From source file:es.logongas.ix3.util.FactoryHelper.java

/**
 * Obtiene la Implementacin de un objeto asociado a una clase de negocio.
 * El DAO debe tener el nombre siguiente DAONombreEntidad<<ImplSufi>>. Si no
 * existe una clase especfica con ese nombre se retornar
 * GenericDAOImplHibernate. Hay ncamente 3 paquetes donde debe estar la
 * clase DAONombreEntidadImplHibernate En el paquete
 * 'interfaceBasePackageName' , en el paquete interfaceBasePackageName y un
 * subpaquete igual a subtituir domainBasePackageName por
 * interfaceBasePackageName o en un subpaquete del interfaz llamado
 * "implSubPackageName"//from w ww .j  ava2 s.  co  m
 *
 * @param entityClass
 * @return El DAO de la entidad
 */
public T getImpl(Class entityClass) {
    //Hay 3 formas de encontrar el DAO
    String fqcn;
    T t;
    Class tClass;

    try {
        fqcn = getFQCNImplInSpecificPackage(entityClass, domainBasePackageName, implBasePackageName);
        tClass = Class.forName(fqcn);
        t = (T) context.getAutowireCapableBeanFactory().createBean(tClass);
    } catch (Exception ex) {
        //Si no existe probamos con la siguiente
        try {
            fqcn = getFQCNImplInSamePackage(entityClass, implBasePackageName);
            tClass = Class.forName(fqcn);
            t = (T) context.getAutowireCapableBeanFactory().createBean(tClass);
        } catch (Exception ex1) {
            try {
                fqcn = getFQCNImplInSubPackage(entityClass, domainBasePackageName, implBasePackageName);
                tClass = Class.forName(fqcn);
                t = (T) context.getAutowireCapableBeanFactory().createBean(tClass);
            } catch (Exception ex2) {

                Object bean;
                try {
                    bean = context.getAutowireCapableBeanFactory().createBean(defaultImplClass);

                    Object noProxyBean = unProxyObject(bean);
                    if (noProxyBean instanceof EntityType) {
                        EntityType entityType = (EntityType) noProxyBean;
                        entityType.setEntityType(entityClass);
                    }

                } catch (Exception ex3) {
                    throw new RuntimeException(ex3);
                }

                //Pero como es generico deberemos ver si existe el interfaz
                Class<? extends T> interfaceClass = getInterface(entityClass);
                if (interfaceClass == null) {
                    //Si no existe el interfaz no hace falta crear el Proxy pq
                    //sera perder rendimiento.
                    t = (T) bean;
                } else {
                    t = (T) Proxy.newProxyInstance(InvocationHandlerImpl.class.getClassLoader(),
                            new Class[] { interfaceClass }, new InvocationHandlerImpl(bean));
                }
            }
        }
    }

    return t;
}

From source file:com.smartitengineering.cms.spi.impl.events.EventConsumerImpl.java

@Override
public void consume(String eventContentType, String eventMessage) {
    BufferedReader reader = null;
    try {//from w w  w.ja  v  a  2s .  co  m
        reader = new BufferedReader(new StringReader(eventMessage));
        final Type sourceType = Type.valueOf(reader.readLine());
        final EventType type = EventType.valueOf(reader.readLine());
        if (logger.isDebugEnabled()) {
            logger.debug("Event source type " + sourceType);
            logger.debug("Event type " + type);
        }
        final StringBuilder idStr = new StringBuilder("");
        String line;
        do {
            line = reader.readLine();
            if (StringUtils.isNotBlank(line)) {
                idStr.append(line).append('\n');
            }
        } while (StringUtils.isNotBlank(line));
        final byte[] decodedIdString = Base64.decodeBase64(idStr.toString());
        final String idString = org.apache.commons.codec.binary.StringUtils.newStringUtf8(decodedIdString);
        if (logger.isInfoEnabled()) {
            logger.info("ID String from message " + idString);
        }
        switch (sourceType) {
        case CONTENT: {
            final ContentId contentId;
            final String[] idParams = idString.split("\n");
            if (idParams.length < 3) {
                logger.warn(
                        "Insufficient params for forming content id in id string. Thus ignoring the following message "
                                + idString);
                return;
            }
            final byte[] contentIdBytes = org.apache.commons.codec.binary.StringUtils.getBytesUtf8(idParams[2]);
            final WorkspaceId workspaceId = SmartContentAPI.getInstance().getWorkspaceApi()
                    .createWorkspaceId(idParams[0], idParams[1]);
            contentId = SmartContentAPI.getInstance().getContentLoader().createContentId(workspaceId,
                    contentIdBytes);
            Content content = contentId.getContent();
            if (content == null && EventType.DELETE.equals(type)) {
                content = (Content) Proxy.newProxyInstance(Content.class.getClassLoader(),
                        new Class[] { Content.class }, new InvocationHandler() {

                            @Override
                            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                                if (method.getName().equals("getContentId")) {
                                    return contentId;
                                }
                                return null;
                            }
                        });
            }
            if (content == null) {
                logger.warn("No Content for event thus ignoring it - " + idString);
                return;
            }
            final Event<Content> event = SmartContentAPI.getInstance().getEventRegistrar()
                    .<Content>createEvent(type, sourceType, content);
            contentListener.notify(event);
        }
            break;
        case CONTENT_TYPE: {
            final ContentTypeId typeId;
            final String[] idParams = idString.split("\n");
            if (idParams.length < 4) {
                logger.error(
                        "Insufficient params for forming content type id in id string. Thus ignoring the following message "
                                + idString);
                return;
            }
            final WorkspaceId workspaceId = SmartContentAPI.getInstance().getWorkspaceApi()
                    .createWorkspaceId(idParams[0], idParams[1]);
            typeId = SmartContentAPI.getInstance().getContentTypeLoader().createContentTypeId(workspaceId,
                    idParams[2], idParams[3]);
            ContentType contentType = typeId.getContentType();
            if (contentType == null && EventType.DELETE.equals(type)) {
                contentType = (ContentType) Proxy.newProxyInstance(ContentType.class.getClassLoader(),
                        new Class[] { ContentType.class }, new InvocationHandler() {

                            @Override
                            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                                if (method.getName().equals("getContentTypeID")) {
                                    return typeId;
                                }
                                return null;
                            }
                        });
            }
            if (contentType == null) {
                logger.warn("No Content Type for event thus ignoring it - " + idString);
                return;
            }
            final Event<ContentType> event = SmartContentAPI.getInstance().getEventRegistrar()
                    .<ContentType>createEvent(type, sourceType, contentType);
            contentTypeListener.notify(event);
        }
            break;
        case SEQUENCE: {
            final SequenceId seqId;
            final String[] idParams = idString.split("\n");
            if (idParams.length < 3) {
                logger.error(
                        "Insufficient params for forming sequence id in id string. Thus ignoring the following message "
                                + idString);
                return;
            }
            final WorkspaceId workspaceId = SmartContentAPI.getInstance().getWorkspaceApi()
                    .createWorkspaceId(idParams[0], idParams[1]);
            seqId = SmartContentAPI.getInstance().getWorkspaceApi().createSequenceId(workspaceId, idParams[2]);
            Sequence sequence = seqId.getSequence();
            if (sequence == null && EventType.DELETE.equals(type)) {
                sequence = (Sequence) Proxy.newProxyInstance(Sequence.class.getClassLoader(),
                        new Class[] { Sequence.class }, new InvocationHandler() {

                            @Override
                            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                                if (method.getName().equals("getSequenceId")) {
                                    return seqId;
                                }
                                return null;
                            }
                        });
            }
            if (sequence == null) {
                logger.warn("No Sequence for event thus ignoring it - " + idString);
                return;
            }
            final Event<Sequence> event = SmartContentAPI.getInstance().getEventRegistrar()
                    .<Sequence>createEvent(type, sourceType, sequence);
            sequenceListener.notify(event);
        }
            break;
        default:
            logger.info(new StringBuilder("Ignoring event source type ").append(sourceType).toString());
        }
    } catch (Exception ex) {
        logger.warn("Could not persist content ID!", ex);
        throw new RuntimeException(ex);
    } finally {
        try {
            reader.close();
        } catch (Exception ex) {
            logger.warn("Could not close reader!", ex);
        }
    }
}

From source file:org.apache.olingo.ext.proxy.commons.AbstractInvocationHandler.java

protected ComplexType<?> getComplex(final String name, final ClientValue value, final Class<?> ref,
        final EntityInvocationHandler handler, final URI baseURI, final boolean collectionItem) {

    final URIBuilder targetURI;
    if (collectionItem) {
        targetURI = null;/*from   w w  w . j a  va2 s  .  c  om*/
    } else {
        targetURI = baseURI == null ? null
                : getClient().newURIBuilder(baseURI.toASCIIString()).appendPropertySegment(name);
    }

    final ComplexInvocationHandler complexHandler;
    Class<?> actualRef = ref;
    if (value == null) {
        complexHandler = ComplexInvocationHandler.getInstance(actualRef, service, targetURI);
    } else {
        actualRef = CoreUtils.getComplexTypeRef(service, value); // handle derived types
        complexHandler = ComplexInvocationHandler.getInstance(value.asComplex(), actualRef, service, targetURI);
    }

    complexHandler.setEntityHandler(handler);

    final ComplexType<?> res = ComplexType.class.cast(Proxy.newProxyInstance(
            Thread.currentThread().getContextClassLoader(), new Class<?>[] { actualRef }, complexHandler));

    return res;
}

From source file:com.hortonworks.hbase.replication.bridge.WritableRpcEngine.java

/** Construct a client-side proxy object that implements the named protocol,
 * talking to a server at the named address. */
@Override/*from w  w  w .  j  a v a 2  s.  c  o m*/
public <T extends VersionedProtocol> T getProxy(Class<T> protocol, long clientVersion, InetSocketAddress addr,
        Configuration conf, int rpcTimeout) throws IOException {
    if (this.client == null) {
        throw new IOException("Client must be initialized by calling setConf(Configuration)");
    }

    T proxy = (T) Proxy.newProxyInstance(protocol.getClassLoader(), new Class[] { protocol },
            new Invoker(client, protocol, addr, User.getCurrent(), conf, HBaseRPC.getRpcTimeout(rpcTimeout)));

    /*
     * TODO: checking protocol version only needs to be done once when we setup a new
     * HBaseClient.Connection.  Doing it every time we retrieve a proxy instance is resulting
     * in unnecessary RPC traffic.
     */
    long serverVersion = ((VersionedProtocol) proxy).getProtocolVersion(protocol.getName(), clientVersion);
    if (serverVersion != clientVersion) {
        throw new HBaseRPC.VersionMismatch(protocol.getName(), clientVersion, serverVersion);
    }

    return proxy;
}

From source file:org.apache.hadoop.hive.metastore.RetryingMetaStoreClient.java

/**
 * This constructor is meant for Hive internal use only.
 * Please use getProxy(HiveConf hiveConf, HiveMetaHookLoader hookLoader) for external purpose.
 *//*from  www.  j  a va2  s .  c  om*/
public static IMetaStoreClient getProxy(HiveConf hiveConf, Class<?>[] constructorArgTypes,
        Object[] constructorArgs, Map<String, Long> metaCallTimeMap, String mscClassName) throws MetaException {

    Class<? extends IMetaStoreClient> baseClass = (Class<? extends IMetaStoreClient>) MetaStoreUtils
            .getClass(mscClassName);

    RetryingMetaStoreClient handler = new RetryingMetaStoreClient(hiveConf, constructorArgTypes,
            constructorArgs, metaCallTimeMap, baseClass);
    return (IMetaStoreClient) Proxy.newProxyInstance(RetryingMetaStoreClient.class.getClassLoader(),
            baseClass.getInterfaces(), handler);
}

From source file:com.interface21.aop.framework.AopProxy.java

/**
 * Creates a new Proxy object for the given object, proxying
 * the given interface. Uses the given class loader.
 *//*w  w w. j av  a  2 s  .  c  o  m*/
public Object getProxy(ClassLoader cl) {
    if (this.config.getProxiedInterfaces() != null && this.config.getProxiedInterfaces().length > 0) {
        // proxy specific interfaces: J2SE Proxy is sufficient
        logger.info("Creating J2SE proxy for [" + this.config.getTarget() + "]");
        return Proxy.newProxyInstance(cl, this.config.getProxiedInterfaces(), this);
    } else {
        if (this.config.getTarget() == null) {
            throw new IllegalArgumentException(
                    "Either an interface or a target is required for proxy creation");
        }
        // proxy the given class itself: CGLIB necessary
        logger.info("Creating CGLIB proxy for [" + this.config.getTarget() + "]");
        // delegate to inner class to avoid AopProxy runtime dependency on CGLIB
        // --> J2SE proxies work without cglib.jar then
        return (new CglibProxyFactory()).createProxy();
    }
}

From source file:org.apache.hadoop.hbase.ipc.bak.MonitoredRpcEngine.java

/**
 * Construct a client-side proxy object that implements the named protocol, talking to a server at
 * the named address.//from  ww w  .  ja v a 2  s . c  o  m
 */
@Override
public <T extends VersionedProtocol> T getProxy(Class<T> protocol, long clientVersion, InetSocketAddress addr,
        Configuration conf, int rpcTimeout) throws IOException {
    if (this.client == null) {
        throw new IOException("Client must be initialized by calling setConf(Configuration)");
    }

    T proxy = (T) Proxy.newProxyInstance(protocol.getClassLoader(), new Class[] { protocol }, new Invoker(
            client, protocol, addr, userProvider.getCurrent(), conf, HBaseRPC.getRpcTimeout(rpcTimeout)));

    /*
     * TODO: checking protocol version only needs to be done once when we setup a new
     * HBaseClient.Connection. Doing it every time we retrieve a proxy instance is resulting in
     * unnecessary RPC traffic.
     */
    long serverVersion = ((VersionedProtocol) proxy).getProtocolVersion(protocol.getName(), clientVersion);
    if (serverVersion != clientVersion) {
        throw new HBaseRPC.VersionMismatch(protocol.getName(), clientVersion, serverVersion);
    }

    return proxy;
}

From source file:net.pandoragames.far.ui.swing.component.MacOSXMenuAdapter.java

/**
 * Instantiates the <code>Application</code> class and initialises <i>this</i>
 * as a Proxy for interface <code>ApplicationListener</code>. Wires the two together.
 *//*from  w w  w  .  j  a v  a  2s.  c o  m*/
public MacOSXMenuAdapter() {
    // 1. get an instance of apples Application class
    Class applicationClass = null;
    try {
        applicationClass = Class.forName(CL_OSX_APP);
        macOSXApplication = applicationClass.newInstance();
    } catch (Exception x) {
        String message = x.getClass().getName() + " instantiating " + CL_OSX_APP + ": " + x.getMessage();
        logger.error(message);
        throw new IllegalStateException(message);
    }
    // 2. Make THIS a Proxy for an ApplicationListener instance
    try {
        Class applicationListenerClass = Class.forName(CL_OSX_APP_LSTR);
        applicationListenerProxy = Proxy.newProxyInstance(MacOSXMenuAdapter.class.getClassLoader(),
                new Class[] { applicationListenerClass }, this);
        Method addListenerMethod = applicationClass.getDeclaredMethod("addApplicationListener",
                new Class[] { applicationListenerClass });
        addListenerMethod.invoke(macOSXApplication, new Object[] { applicationListenerProxy });
    } catch (Exception x) {
        String message = x.getClass().getName() + " instantiating " + CL_OSX_APP_LSTR + ": " + x.getMessage();
        logger.error(message);
        throw new IllegalStateException(message);
    }
}