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.broadleafcommerce.common.cache.AbstractCacheMissAware.java

/**
 * Retrieve a null representation of the cache item. This representation is the same for
 * all cache misses and is used as the object representation to store in the cache for a
 * cache miss.//from   ww w .  j  ava 2 s  . co m
 *
 * @param responseClass the class representing the type of the cache item
 * @param <T> the type of the cache item
 * @return the null representation for the cache item
 */
protected synchronized <T> T getNullObject(final Class<T> responseClass) {
    if (nullObject == null) {
        Class<?>[] interfaces = (Class<?>[]) ArrayUtils.add(ClassUtils.getAllInterfacesForClass(responseClass),
                Serializable.class);
        nullObject = Proxy.newProxyInstance(getClass().getClassLoader(), interfaces, new InvocationHandler() {
            @Override
            public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
                if (method.getName().equals("equals")) {
                    return !(objects[0] == null) && objects[0].hashCode() == 31;
                } else if (method.getName().equals("hashCode")) {
                    return 31;
                } else if (method.getName().equals("toString")) {
                    return "Null_" + responseClass.getSimpleName();
                }
                throw new IllegalAccessException("Not a real object");
            }
        });
    }
    return (T) nullObject;
}

From source file:org.summercool.mybatis.spring.support.SqlSessionTemplate.java

/**
 * Constructs a Spring managed {@code SqlSession} with the given {@code SqlSessionFactory} and {@code ExecutorType}.
 * A custom {@code SQLExceptionTranslator} can be provided as an argument so any {@code PersistenceException} thrown
 * by MyBatis can be custom translated to a {@code RuntimeException} The {@code SQLExceptionTranslator} can also be
 * null and thus no exception translation will be done and MyBatis exceptions will be thrown
 * //from   w ww .j a  va  2s.  c o m
 * @param sqlSessionFactory
 * @param executorType
 * @param exceptionTranslator
 */
public SqlSessionTemplate(SqlSessionFactory sqlSessionFactory, ExecutorType executorType,
        PersistenceExceptionTranslator exceptionTranslator) {

    Assert.notNull(sqlSessionFactory, "Property 'sqlSessionFactory' is required");
    Assert.notNull(executorType, "Property 'executorType' is required");

    this.sqlSessionFactory = sqlSessionFactory;
    this.executorType = executorType;
    this.exceptionTranslator = exceptionTranslator;
    this.sqlSessionProxy = (SqlSession) Proxy.newProxyInstance(SqlSessionFactory.class.getClassLoader(),
            new Class[] { SqlSession.class }, new SqlSessionInterceptor());
}

From source file:org.kuali.rice.core.framework.persistence.jdbc.datasource.PrimaryDataSourceFactoryBean.java

/**
 * <p>returns the new DataSource instance, or a lazy proxy to it (see {@link #setForceLazy(boolean)}.</p>
 *
 * @return the new DataSource/*from w w w .  j av a 2s  .c o  m*/
 * @throws Exception see superclass method
 * @see org.springframework.beans.factory.config.AbstractFactoryBean#createInstance()
 */
@Override
protected Object createInstance() throws Exception {
    DataSource dataSource = null;
    if (!isForceLazy()) {
        dataSource = createDataSourceInstance();
    } else {
        dataSource = (DataSource) Proxy.newProxyInstance(getClass().getClassLoader(),
                new Class[] { DataSource.class }, new LazyInvocationHandler());
    }

    return dataSource;
}

From source file:com.google.gdt.eclipse.designer.uibinder.parser.UiBinderRenderer.java

private void setObjects(Object binder) throws Exception {
    ClassLoader classLoader = binder.getClass().getClassLoader();
    String handlerClassName = binder.getClass().getName() + "$DTObjectHandler";
    Class<?> handlerClass = classLoader.loadClass(handlerClassName);
    Object handler = Proxy.newProxyInstance(classLoader, new Class[] { handlerClass }, new InvocationHandler() {
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            if (method.getName().equals("handle")) {
                String path = (String) args[0];
                Object object = args[1];
                XmlObjectInfo objectInfo = m_pathToModelMap.get(path);
                objectInfo.setObject(object);
            }/*from ww  w  .jav a2 s .c  om*/
            if (method.getName().equals("provideFactory")) {
                Class<?> factoryType = (Class<?>) args[0];
                String methodName = (String) args[1];
                Object[] factoryArgs = (Object[]) args[2];
                return UiBinderParser.createProvidedFactory(m_context, factoryType, methodName, factoryArgs);
            }
            if (method.getName().equals("provideField")) {
                Class<?> fieldType = (Class<?>) args[0];
                String fieldName = (String) args[1];
                return UiBinderParser.createProvidedField(m_context, fieldType, fieldName);
            }
            return null;
        }
    });
    ReflectionUtils.setField(binder, "dtObjectHandler", handler);
}

From source file:com.mystudy.source.spring.aop.JdkDynamicAopProxy.java

/**
 * findDefinedEqualsAndHashCodeMethods//from w ww.  j  a v  a 2  s  . c  om
 * 1:??:????:
 * 2:findDefinedEqualsAndHashCodeMethods:???equalhashcode
 * 3: Proxy.newProxyInstance()??
 * @param classLoader
 * @return
 */
public Object getProxy(ClassLoader classLoader) {
    if (logger.isDebugEnabled()) {
        logger.debug("Creating JDK dynamic proxy: target source is " + this.advised.getTargetSource());
    }
    Class<?>[] proxiedInterfaces = AopProxyUtils.completeProxiedInterfaces(this.advised);
    findDefinedEqualsAndHashCodeMethods(proxiedInterfaces);
    return Proxy.newProxyInstance(classLoader, proxiedInterfaces, this);
}

From source file:com.stehno.sjdbcx.reflection.ReflectionImplementationProvider.java

@Override
public Object instantiate() {
    // FIXME: needs to handle abstract prototype classes too
    return Proxy.newProxyInstance(prototype.getClassLoader(), new Class[] { prototype }, invocationHandler);
}

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

private Object openSession() {
    LOG.debug("Openning new session for actual session factory, currently active open sessions: {}",
            currentOpenedSessions);/*from   ww w.ja v  a  2s . co m*/
    Session realSession = this.realSessionFactory.openSession();
    currentOpenedSessions++;

    SessionObserver observer = null;
    try {
        observer = ((SessionFactoryImplementor) realSessionFactory).getServiceRegistry()
                .getService(SessionObserver.class);
    } catch (UnknownServiceException e) {
        // Do nothing
    }

    SessionProxyHandler proxyHandler = new SessionProxyHandler(this.realSessionFactory, realSession, observer);
    Session proxy = (Session) Proxy.newProxyInstance(Session.class.getClassLoader(),
            new Class<?>[] { Session.class, SessionImplementor.class }, proxyHandler);

    if (observer != null) {
        observer.sessionCreated(proxy);
    }

    return proxy;

}

From source file:com.github.jknack.handlebars.internal.BaseTemplate.java

/**
 * Creates a new {@link TypeSafeTemplate}.
 *
 * @param rootType The target type.//ww  w.j ava  2  s .co  m
 * @param template The target template.
 * @return A new {@link TypeSafeTemplate}.
 */
private static Object newTypeSafeTemplate(final Class<?> rootType, final Template template) {
    return Proxy.newProxyInstance(template.getClass().getClassLoader(), new Class[] { rootType },
            new InvocationHandler() {
                private Map<String, Object> attributes = new HashMap<String, Object>();

                @Override
                public Object invoke(final Object proxy, final Method method, final Object[] args)
                        throws IOException {
                    String methodName = method.getName();
                    if ("apply".equals(methodName)) {
                        Context context = Context.newBuilder(args[0]).combine(attributes).build();
                        attributes.clear();
                        if (args.length == 2) {
                            template.apply(context, (Writer) args[1]);
                            return null;
                        }
                        return template.apply(context);
                    }

                    if (Modifier.isPublic(method.getModifiers()) && methodName.startsWith("set")) {
                        String attrName = StringUtils.uncapitalize(methodName.substring("set".length()));
                        if (args != null && args.length == 1 && attrName.length() > 0) {
                            attributes.put(attrName, args[0]);
                            if (TypeSafeTemplate.class.isAssignableFrom(method.getReturnType())) {
                                return proxy;
                            }
                            return null;
                        }
                    }
                    String message = String.format(
                            "No handler method for: '%s(%s)', expected method signature is: 'setXxx(value)'",
                            methodName, args == null ? "" : join(args, ", "));
                    throw new UnsupportedOperationException(message);
                }
            });
}

From source file:com.futureplatforms.kirin.internal.attic.ProxyGenerator.java

public <T> T javascriptProxyForResponse(final JSONObject obj, Class<T> baseInterface,
        Class<?>... otherClasses) {
    Class<?>[] allClasses;//from  www  .ja  v a 2  s  .  c  o  m

    if (otherClasses.length == 0) {
        allClasses = new Class[] { baseInterface };
    } else {
        allClasses = new Class[otherClasses.length + 1];
        allClasses[0] = baseInterface;
        System.arraycopy(otherClasses, 0, allClasses, 1, otherClasses.length);
    }
    InvocationHandler h = new InvocationHandler() {

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            String methodName = method.getName();
            Class<?> returnType = method.getReturnType();
            if (void.class.equals(returnType) && args.length == 1) {
                String propertyName = findSetter(methodName);
                if (propertyName != null) {
                    handleSetter(obj, propertyName, args[0]);
                }
            }

            String propertyName = findGetter(methodName);
            if (propertyName != null) {
                return handleGetter(obj, returnType, propertyName);
            }

            if ("toString".equals(methodName) && String.class.equals(returnType)) {
                return obj.toString();
            }

            return null;
        }

    };
    Object proxy = Proxy.newProxyInstance(baseInterface.getClassLoader(), allClasses, h);
    return baseInterface.cast(proxy);
}

From source file:no.kantega.publishing.common.util.database.dbConnectionFactory.java

public static void loadConfiguration() {
    try {/*from  w w w .  j  a va2  s  .c  o  m*/

        setConfiguration();

        verifyCompleteDatabaseConfiguration();

        DriverManagerDataSource rawDataSource = new DriverManagerDataSource();
        rawDataSource.setDriverClassName(dbDriver);
        rawDataSource.setUrl(dbUrl);

        if (!dbNTMLAuthentication) {
            rawDataSource.setUsername(dbUsername);
            rawDataSource.setPassword(dbPassword);
        }

        if (dbEnablePooling) {
            // Enable DBCP pooling
            BasicDataSource bds = new BasicDataSource();
            bds.setMaxTotal(dbMaxConnections);
            bds.setMaxIdle(dbMaxIdleConnections);
            bds.setMinIdle(dbMinIdleConnections);
            if (dbMaxWait != -1) {
                bds.setMaxWaitMillis(1000 * dbMaxWait);
            }

            if (dbDefaultQueryTimeout != -1) {
                bds.setDefaultQueryTimeout(dbDefaultQueryTimeout);
            }

            bds.setDriverClassName(dbDriver);
            if (!dbNTMLAuthentication) {
                bds.setUsername(dbUsername);
                bds.setPassword(dbPassword);
            }
            bds.setUrl(dbUrl);

            if (dbUseTransactions) {
                bds.setDefaultTransactionIsolation(dbTransactionIsolationLevel);
            }

            if (dbCheckConnections) {
                // Gjr at connections frigjres ved lukking fra database/brannmur
                bds.setValidationQuery("SELECT max(ContentId) from content");
                bds.setTimeBetweenEvictionRunsMillis(1000 * 60 * 2);
                bds.setMinEvictableIdleTimeMillis(1000 * 60 * 5);
                bds.setNumTestsPerEvictionRun(dbMaxConnections);
                if (dbRemoveAbandonedTimeout > 0) {
                    bds.setRemoveAbandonedTimeout(dbRemoveAbandonedTimeout);
                    bds.setLogAbandoned(true);
                }
            }

            ds = bds;
        } else {
            ds = rawDataSource;
        }

        // Use non-pooled datasource for table creation since validation query might fail
        ensureDatabaseExists(rawDataSource);
        if (shouldMigrateDatabase) {
            migrateDatabase(servletContext, rawDataSource);
        }

        if (dbUseTransactions) {
            log.info("Using transactions, database transaction isolation level set to "
                    + dbTransactionIsolationLevel);
        } else {
            log.info("Not using transactions");
        }

        if (debugConnections) {
            proxyDs = (DataSource) Proxy.newProxyInstance(DataSource.class.getClassLoader(),
                    new Class[] { DataSource.class }, new DataSourceWrapper(ds));
        }

    } catch (Exception e) {
        log.error("********* could not read aksess.conf **********", e);
    }

}