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:net.sf.farrago.namespace.jdbc.MedJdbcDataServer.java

private void initMetaData() {
    try {//from w  w w  .  j a  v a2 s  .c  o m
        databaseMetaData = connection.getMetaData();
        supportsMetaData = true;
    } catch (Exception ex) {
        Util.swallow(ex, logger);
    }

    if (databaseMetaData == null) {
        // driver can't even support getMetaData(); treat it
        // as brain-damaged
        databaseMetaData = (DatabaseMetaData) Proxy.newProxyInstance(null,
                new Class[] { DatabaseMetaData.class },
                new SqlUtil.DatabaseMetaDataInvocationHandler("UNKNOWN", ""));
        supportsMetaData = false;
    }
}

From source file:org.apache.oozie.client.rest.JsonToBean.java

/**
 * Creates a coordinator action bean from a JSON object.
 *
 * @param json json object.//from w ww .  j  a  va2s  . com
 * @return a coordinator action bean populated with the JSON object values.
 */
public static CoordinatorAction createCoordinatorAction(JSONObject json) {
    return (CoordinatorAction) Proxy.newProxyInstance(JsonToBean.class.getClassLoader(),
            new Class[] { CoordinatorAction.class }, new JsonInvocationHandler(COORD_ACTION, json));
}

From source file:com.apdplat.platform.compass.APDPlatLocalCompassBean.java

public void afterPropertiesSet() throws Exception {
    CompassConfiguration config = this.config;
    if (config == null) {
        config = newConfiguration();/*w  w  w.ja va2  s .c om*/
    }

    if (classLoader != null) {
        config.setClassLoader(getClassLoader());
    }

    if (this.configLocation != null) {
        config.configure(this.configLocation.getURL());
    }

    if (this.configLocations != null) {
        for (Resource configLocation1 : configLocations) {
            config.configure(configLocation1.getURL());
        }
    }

    if (this.mappingScan != null) {
        config.addScan(this.mappingScan);
    }

    if (this.compassSettings != null) {
        config.getSettings().addSettings(this.compassSettings);
    }

    if (this.settings != null) {
        config.getSettings().addSettings(this.settings);
    }

    if (resourceLocations != null) {
        for (Resource resourceLocation : resourceLocations) {
            config.addInputStream(resourceLocation.getInputStream(), resourceLocation.getFilename());
        }
    }

    if (resourceJarLocations != null && !"".equals(resourceJarLocations.trim())) {
        log.info("apdplatcompass2");
        log.info("compass resourceJarLocations:" + resourceJarLocations);
        String[] jars = resourceJarLocations.split(",");
        for (String jar : jars) {
            try {
                FileSystemResource resource = new FileSystemResource(FileUtils.getAbsolutePath(jar));
                config.addJar(resource.getFile());
                log.info("compass resourceJarLocations  find:" + jar);
            } catch (Exception e) {
                log.info("compass resourceJarLocations not exists:" + jar);
            }
        }
    }

    if (classMappings != null) {
        for (String classMapping : classMappings) {
            config.addClass(ClassUtils.forName(classMapping, getClassLoader()));
        }
    }

    if (resourceDirectoryLocations != null && !"".equals(resourceDirectoryLocations.trim())) {
        log.info("apdplatcompass3");
        log.info("compass resourceDirectoryLocations:" + resourceDirectoryLocations);
        String[] dirs = resourceDirectoryLocations.split(",");
        for (String dir : dirs) {
            ClassPathResource resource = new ClassPathResource(dir);
            try {
                File file = resource.getFile();
                if (!file.isDirectory()) {
                    log.info("Resource directory location [" + dir + "] does not denote a directory");
                } else {
                    config.addDirectory(file);
                }
                log.info("compass resourceDirectoryLocations find:" + dir);
            } catch (Exception e) {
                log.info("compass resourceDirectoryLocations not exists:" + dir);
            }
        }
    }

    if (mappingResolvers != null) {
        for (InputStreamMappingResolver mappingResolver : mappingResolvers) {
            config.addMappingResover(mappingResolver);
        }
    }

    if (dataSource != null) {
        ExternalDataSourceProvider.setDataSource(dataSource);
        if (config.getSettings().getSetting(LuceneEnvironment.JdbcStore.DataSourceProvider.CLASS) == null) {
            config.getSettings().setSetting(LuceneEnvironment.JdbcStore.DataSourceProvider.CLASS,
                    ExternalDataSourceProvider.class.getName());
        }
    }

    String compassTransactionFactory = config.getSettings().getSetting(CompassEnvironment.Transaction.FACTORY);
    if (compassTransactionFactory == null && transactionManager != null) {
        // if the transaciton manager is set and a transcation factory is not set, default to the SpringSync one.
        config.getSettings().setSetting(CompassEnvironment.Transaction.FACTORY,
                SpringSyncTransactionFactory.class.getName());
    }
    if (compassTransactionFactory != null
            && compassTransactionFactory.equals(SpringSyncTransactionFactory.class.getName())) {
        if (transactionManager == null) {
            throw new IllegalArgumentException(
                    "When using SpringSyncTransactionFactory the transactionManager property must be set");
        }
    }
    SpringSyncTransactionFactory.setTransactionManager(transactionManager);

    if (convertersByName != null) {
        for (Map.Entry<String, Converter> entry : convertersByName.entrySet()) {
            config.registerConverter(entry.getKey(), entry.getValue());
        }
    }
    if (config.getSettings().getSetting(CompassEnvironment.NAME) == null) {
        config.getSettings().setSetting(CompassEnvironment.NAME, beanName);
    }

    if (config.getSettings().getSetting(CompassEnvironment.CONNECTION) == null && connection != null) {
        config.getSettings().setSetting(CompassEnvironment.CONNECTION, connection.getFile().getAbsolutePath());
    }

    if (applicationContext != null) {
        String[] names = applicationContext.getBeanNamesForType(PropertyPlaceholderConfigurer.class);
        for (String name : names) {
            try {
                PropertyPlaceholderConfigurer propConfigurer = (PropertyPlaceholderConfigurer) applicationContext
                        .getBean(name);
                Method method = findMethod(propConfigurer.getClass(), "mergeProperties");
                method.setAccessible(true);
                Properties props = (Properties) method.invoke(propConfigurer);
                method = findMethod(propConfigurer.getClass(), "convertProperties", Properties.class);
                method.setAccessible(true);
                method.invoke(propConfigurer, props);
                method = findMethod(propConfigurer.getClass(), "parseStringValue", String.class,
                        Properties.class, Set.class);
                method.setAccessible(true);
                String nullValue = null;
                try {
                    Field field = propConfigurer.getClass().getDeclaredField("nullValue");
                    field.setAccessible(true);
                    nullValue = (String) field.get(propConfigurer);
                } catch (NoSuchFieldException e) {
                    // no field (old spring version)
                }
                for (Map.Entry entry : config.getSettings().getProperties().entrySet()) {
                    String key = (String) entry.getKey();
                    String value = (String) entry.getValue();
                    value = (String) method.invoke(propConfigurer, value, props, new HashSet());
                    config.getSettings().setSetting(key, value.equals(nullValue) ? null : value);
                }
            } catch (Exception e) {
                log.debug("Failed to apply property placeholder defined in bean [" + name + "]", e);
            }
        }
    }

    if (postProcessor != null) {
        postProcessor.process(config);
    }
    this.compass = newCompass(config);
    this.compass = (Compass) Proxy.newProxyInstance(SpringCompassInvocationHandler.class.getClassLoader(),
            new Class[] { InternalCompass.class }, new SpringCompassInvocationHandler(this.compass));
}

From source file:com.google.gdt.eclipse.designer.uibinder.model.util.NameSupport.java

/**
 * Adds <code>JField</code> with given name and @UiField annotation into "form" <code>JType</code>
 * .//from  w  w  w .  jav a2  s.  c o  m
 */
private void addFormJField(Class<?> componentClass, String name) throws Exception {
    IDevModeBridge bridge = m_context.getState().getDevModeBridge();
    ClassLoader devClassLoader = bridge.getDevClassLoader();
    // prepare "form" JType
    Object formType = bridge.findJType(m_context.getFormType().getFullyQualifiedName());
    // prepare @UiField annotation instance
    Class<?> uiFieldAnnotationClass = devClassLoader.loadClass("com.google.gwt.uibinder.client.UiField");
    java.lang.annotation.Annotation annotation = (java.lang.annotation.Annotation) Proxy.newProxyInstance(
            uiFieldAnnotationClass.getClassLoader(), new Class[] { uiFieldAnnotationClass },
            new InvocationHandler() {
                public Object invoke(Object proxy, Method method, Object[] args) {
                    return Boolean.TRUE;
                }
            });
    // add new JField
    Object newField;
    {
        Constructor<?> fieldConstructor;
        Class<?> fieldClass;
        if (m_context.getState().getVersion().isHigherOrSame(Utils.GWT_2_2)) {
            fieldClass = devClassLoader.loadClass("com.google.gwt.dev.javac.typemodel.JField");
            fieldConstructor = ReflectionUtils.getConstructorBySignature(fieldClass,
                    "<init>(com.google.gwt.dev.javac.typemodel.JClassType,java.lang.String,java.util.Map)");
        } else {
            fieldClass = devClassLoader.loadClass("com.google.gwt.core.ext.typeinfo.JField");
            fieldConstructor = ReflectionUtils.getConstructorBySignature(fieldClass,
                    "<init>(com.google.gwt.core.ext.typeinfo.JClassType,java.lang.String,java.util.Map)");
        }
        newField = fieldConstructor.newInstance(formType, name,
                ImmutableMap.of(uiFieldAnnotationClass, annotation));
    }
    // set "widget" JType for JField
    Object widgetType = bridge.findJType(ReflectionUtils.getCanonicalName(componentClass));
    ReflectionUtils.invokeMethod(newField, "setType(com.google.gwt.core.ext.typeinfo.JType)", widgetType);
}

From source file:org.apache.oozie.client.rest.JsonToBean.java

/**
 * Creates a coordinator job bean from a JSON object.
 *
 * @param json json object./*  www . java  2  s  . co m*/
 * @return a coordinator job bean populated with the JSON object values.
 */
public static CoordinatorJob createCoordinatorJob(JSONObject json) {
    return (CoordinatorJob) Proxy.newProxyInstance(JsonToBean.class.getClassLoader(),
            new Class[] { CoordinatorJob.class }, new JsonInvocationHandler(COORD_JOB, json));
}

From source file:org.apache.oozie.client.rest.JsonToBean.java

/**
 * Creates a JMSInfo bean from a JSON object.
 *
 * @param json json object.//from  ww w.ja  v a  2 s. co  m
 * @return a coordinator job bean populated with the JSON object values.
 */
public static JMSConnectionInfo createJMSConnectionInfo(JSONObject json) {
    final JMSConnectionInfoWrapper jmsInfo = (JMSConnectionInfoWrapper) Proxy.newProxyInstance(
            JsonToBean.class.getClassLoader(), new Class[] { JMSConnectionInfoWrapper.class },
            new JsonInvocationHandler(JMS_CONNECTION_INFO, json));

    return new JMSConnectionInfo() {
        @Override
        public String getTopicPrefix() {
            return jmsInfo.getTopicPrefix();
        }

        @Override
        public String getTopicPattern(AppType appType) {
            return (String) jmsInfo.getTopicPatternProperties().get(appType.name());
        }

        @Override
        public Properties getJNDIProperties() {
            return jmsInfo.getJNDIProperties();
        }
    };
}

From source file:com.sworddance.beans.ProxyMapperImpl.java

@SuppressWarnings("unchecked")
protected I createExternalFacingProxy() {
    Class<?>[] interfaces;/*from  www .java 2  s .c om*/
    if (getRealClass().isInterface()) {
        interfaces = new Class<?>[] { getRealClass() };
    } else {
        interfaces = getRealClass().getInterfaces();
    }
    if (interfaces.length == 0) {
        throw new IllegalArgumentException(
                this.getRealClass() + " is not an interface or does not have any interfaces.");
    }
    return (I) Proxy.newProxyInstance(getRealClass().getClassLoader(), interfaces, this);
}

From source file:org.springextensions.db4o.Db4oTemplate.java

/**
 * Create a close-suppressing proxy for the given ObjectContainer.
 *
 * @param container the Db4o ObjectContainer to create a proxy for
 * @return the ObjectContainer proxy/*from   ww w.j a v  a  2  s. com*/
 * @see com.db4o.ObjectContainer#close()
 */
protected ObjectContainer createContainerProxy(ObjectContainer container) {
    // every db4o ObjectContainer always is an ExtObjectContainer
    Class intrface = ExtObjectContainer.class;
    if (container instanceof ExtClient) {
        // both Db4oClientServer.openClient() methods always return an ExtClient object
        intrface = ExtClient.class;
    }
    return (ObjectContainer) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[] { intrface },
            new CloseSuppressingInvocationHandler(container));
}

From source file:org.apache.oozie.client.rest.JsonToBean.java

/**
 * Creates a bundle job bean from a JSON object.
 *
 * @param json json object.// w ww  .  ja  va  2 s. c  o m
 * @return a bundle job bean populated with the JSON object values.
 */
public static BundleJob createBundleJob(JSONObject json) {
    return (BundleJob) Proxy.newProxyInstance(JsonToBean.class.getClassLoader(),
            new Class[] { BundleJob.class }, new JsonInvocationHandler(BUNDLE_JOB, json));
}

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

@SuppressWarnings({ "unchecked" })
private static void populate(final EdmEnabledODataClient client, final EntityInvocationHandler typeHandler,
        final Object bean, final Class<?> typeRef, final Class<? extends Annotation> getterAnn,
        final Iterator<? extends ClientProperty> propItor) {

    if (bean != null) {
        while (propItor.hasNext()) {
            final ClientProperty property = propItor.next();

            final Method getter = ClassUtils.findGetterByAnnotatedName(typeRef, getterAnn, property.getName());

            if (getter == null) {
                LOG.warn("Could not find any property annotated as {} in {}", property.getName(),
                        bean.getClass().getName());
            } else {
                try {
                    if (property.hasNullValue()) {
                        setPropertyValue(bean, getter, null);
                    } else if (property.hasPrimitiveValue()) {
                        setPropertyValue(bean, getter, primitiveValueToObject(property.getPrimitiveValue(),
                                getPropertyClass(typeRef, property.getName())));
                    } else if (property.hasComplexValue()) {
                        final Object complex = Proxy.newProxyInstance(
                                Thread.currentThread().getContextClassLoader(),
                                new Class<?>[] { getter.getReturnType() },
                                ComplexInvocationHandler.getInstance(typeHandler, getter.getReturnType()));

                        populate(client, typeHandler, complex, Property.class,
                                property.getValue().asComplex().iterator());
                        setPropertyValue(bean, getter, complex);
                    } else if (property.hasCollectionValue()) {
                        final ParameterizedType collType = (ParameterizedType) getter.getGenericReturnType();
                        final Class<?> collItemClass = (Class<?>) collType.getActualTypeArguments()[0];

                        Collection<Object> collection = (Collection<Object>) getter.invoke(bean);
                        if (collection == null) {
                            collection = new ArrayList<Object>();
                            setPropertyValue(bean, getter, collection);
                        }//from w  w  w . ja v  a2 s. c o  m

                        final Iterator<ClientValue> collPropItor = property.getValue().asCollection()
                                .iterator();
                        while (collPropItor.hasNext()) {
                            final ClientValue value = collPropItor.next();
                            if (value.isPrimitive()) {
                                collection.add(primitiveValueToObject(value.asPrimitive(),
                                        getPropertyClass(typeRef, property.getName())));
                            } else if (value.isComplex()) {
                                final Object collItem = Proxy.newProxyInstance(
                                        Thread.currentThread().getContextClassLoader(),
                                        new Class<?>[] { collItemClass },
                                        ComplexInvocationHandler.getInstance(typeHandler, collItemClass));

                                populate(client, typeHandler, collItem, Property.class,
                                        value.asComplex().iterator());
                                collection.add(collItem);
                            }
                        }
                    }
                } catch (Exception e) {
                    LOG.error("Could not set property {} on {}", getter, bean, e);
                }
            }
        }
    }
}