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.openadmin.web.rulebuilder.service.AbstractRuleBuilderFieldService.java

@Override
@SuppressWarnings("unchecked")
public void setFields(final List<FieldData> fields) {
    List<FieldData> proxyFields = (List<FieldData>) Proxy.newProxyInstance(getClass().getClassLoader(),
            new Class<?>[] { List.class }, new InvocationHandler() {
                @Override//  w w  w  .ja  v  a 2s . c  o m
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    if (method.getName().equals("add")) {
                        FieldData fieldData = (FieldData) args[0];
                        testFieldName(fieldData);
                    }
                    if (method.getName().equals("addAll")) {
                        Collection<FieldData> addCollection = (Collection<FieldData>) args[0];
                        Iterator<FieldData> itr = addCollection.iterator();
                        while (itr.hasNext()) {
                            FieldData fieldData = itr.next();
                            testFieldName(fieldData);
                        }
                    }
                    return method.invoke(fields, args);
                }

                private void testFieldName(FieldData fieldData) throws ClassNotFoundException {
                    if (!StringUtils.isEmpty(fieldData.getFieldName()) && dynamicEntityDao != null) {
                        Class<?>[] dtos = dynamicEntityDao
                                .getAllPolymorphicEntitiesFromCeiling(Class.forName(getDtoClassName()));
                        if (ArrayUtils.isEmpty(dtos)) {
                            dtos = new Class<?>[] { Class.forName(getDtoClassName()) };
                        }
                        Field field = null;
                        for (Class<?> dto : dtos) {
                            field = dynamicEntityDao.getFieldManager().getField(dto, fieldData.getFieldName());
                            if (field != null) {
                                break;
                            }
                        }
                        if (field == null) {
                            throw new IllegalArgumentException(
                                    "Unable to find the field declared in FieldData ("
                                            + fieldData.getFieldName() + ") on the target class ("
                                            + getDtoClassName()
                                            + "), or any registered entity class that derives from it.");
                        }
                    }
                }
            });
    this.fields = proxyFields;
}

From source file:org.apache.ode.utils.LoggingInterceptor.java

public static DataSource createLoggingDS(DataSource ds, Log log) {
    return (DataSource) Proxy.newProxyInstance(ds.getClass().getClassLoader(), new Class[] { DataSource.class },
            new LoggingInterceptor<DataSource>(ds, log));
}

From source file:org.kuali.kfs.module.tem.service.CsvRecordFactory.java

public RecordType newInstance(final Map<String, List<Integer>> header, final String[] record) throws Exception {
    return (RecordType) Proxy.newProxyInstance(recordType.getClassLoader(), new Class[] { recordType },
            new CsvRecordInvocationHandler(header, record));
}

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

@SuppressWarnings("unchecked")
public <NE extends EntityType<?>> NE newEntityInstance(final Class<NE> ref) {
    final EntityInvocationHandler handler = EntityInvocationHandler.getInstance(ref, getService());

    return (NE) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class<?>[] { ref },
            handler);/*w ww  . j  av a2s . c om*/
}

From source file:com.github.jinahya.codec.commons.AbstractEncoderProxy.java

/**
 * Creates a new proxy instance./*  ww  w  . j  av  a  2 s.  c  o  m*/
 *
 * @param <P> proxy type parameter
 * @param <T> encoder type parameter
 * @param loader class loader
 * @param interfaces interfaces
 * @param proxyType proxy type
 * @param encoderType encoder type
 * @param encoder encoder
 *
 * @return a new proxy instance.
 */
protected static <P extends AbstractEncoderProxy<T>, T> Object newInstance(final ClassLoader loader,
        final Class<?>[] interfaces, final Class<P> proxyType, final Class<T> encoderType, final T encoder) {

    if (loader == null) {
        throw new NullPointerException("loader");
    }

    if (interfaces == null) {
        throw new NullPointerException("interfaces");
    }

    if (proxyType == null) {
        throw new NullPointerException("proxyType");
    }

    if (encoderType == null) {
        throw new NullPointerException("encoderType");
    }

    if (encoder == null) {
        //throw new NullPointerException("encoder");
    }

    try {
        final Constructor<P> constructor = proxyType.getDeclaredConstructor(encoderType);
        if (!constructor.isAccessible()) {
            constructor.setAccessible(true);
        }
        try {
            return Proxy.newProxyInstance(loader, interfaces, constructor.newInstance(encoder));
        } catch (final IllegalAccessException iae) {
            throw new RuntimeException(iae);
        } catch (final InstantiationException ie) {
            throw new RuntimeException(ie);
        } catch (final InvocationTargetException ite) {
            throw new RuntimeException(ite);
        }
    } catch (final NoSuchMethodException nsme) {
        throw new RuntimeException(nsme);
    }
}

From source file:com.github.jinahya.codec.commons.AbstractDecoderProxy.java

/**
 * Creates a new proxy instance./*from w w  w. j a  v a  2s.  co m*/
 *
 * @param <P> proxy type parameter
 * @param <T> decoder type parameter
 * @param loader class loader
 * @param interfaces interfaces
 * @param proxyType proxy type
 * @param decoderType decoder type
 * @param decoder decoder
 *
 * @return a new proxy instance.
 */
protected static <P extends AbstractDecoderProxy<T>, T> Object newInstance(final ClassLoader loader,
        final Class<?>[] interfaces, final Class<P> proxyType, final Class<T> decoderType, final T decoder) {

    if (loader == null) {
        throw new NullPointerException("loader");
    }

    if (interfaces == null) {
        throw new NullPointerException("interfaces");
    }

    if (proxyType == null) {
        throw new NullPointerException("proxyType");
    }

    if (decoderType == null) {
        throw new NullPointerException("decoderType");
    }

    if (decoder == null) {
        //throw new NullPointerException("decoder");
    }

    try {
        final Constructor<P> constructor = proxyType.getDeclaredConstructor(decoderType);
        if (!constructor.isAccessible()) {
            constructor.setAccessible(true);
        }
        try {
            return Proxy.newProxyInstance(loader, interfaces, constructor.newInstance(decoder));
        } catch (final InstantiationException ie) {
            throw new RuntimeException(ie);
        } catch (final IllegalAccessException iae) {
            throw new RuntimeException(iae);
        } catch (final InvocationTargetException ite) {
            throw new RuntimeException(ite);
        }
    } catch (final NoSuchMethodException nsme) {
        throw new RuntimeException(nsme);
    }
}

From source file:org.resthub.rpc.AMQPProxyFactory.java

/**
 * Creates a new proxy from the specified interface.
 * @param api the interface//from  w  w w  .  java  2 s.  com
 * @return the proxy to the object with the specified interface
 */
@SuppressWarnings("unchecked")
public <T> T create(Class<T> api) {
    if (null == api || !api.isInterface()) {
        throw new IllegalArgumentException("Parameter 'api' is required");
    }
    this.serviceInterface = api;
    this.afterPropertiesSet();
    AMQPProxy handler = new AMQPProxy(this);
    return (T) Proxy.newProxyInstance(api.getClassLoader(), new Class[] { api }, handler);
}

From source file:de.dfki.kiara.jsonrpc.JsonRpcProtocol.java

@Override
public InterfaceCodeGen createInterfaceCodeGen(final ConnectionBase connection) {
    final JsonRpcProtocol thisProtocol = this;
    return new InterfaceCodeGen() {
        @Override/* w  ww.  j  a va 2  s.c o m*/
        public <T> T generateInterfaceImpl(Class<T> interfaceClass, InterfaceMapping<T> mapping) {
            Object impl = Proxy.newProxyInstance(interfaceClass.getClassLoader(),
                    new Class<?>[] { interfaceClass, RemoteInterface.class },
                    new DefaultInvocationHandler(connection, mapping, thisProtocol));
            return interfaceClass.cast(impl);
        }
    };
}

From source file:com._4dconcept.springframework.data.marklogic.datasource.LazySessionContentSourceProxy.java

/**
 * Return a Session handle that lazily fetches an actual XDBC Session
 * when asked for a Statement (or PreparedStatement or CallableStatement).
 * <p>The returned Session handle implements the SessionProxy interface,
 * allowing to retrieve the underlying target Session.
 * @return a lazy Session handle/*ww w  .  ja  v  a2s.co  m*/
 * @see SessionProxy#getTargetSession()
 */
@Override
public Session newSession() {
    return (Session) Proxy.newProxyInstance(SessionProxy.class.getClassLoader(),
            new Class<?>[] { SessionProxy.class }, new LazySessionInvocationHandler());
}

From source file:com.espertech.esper.epl.annotation.AnnotationUtil.java

private static Annotation createProxy(AnnotationDesc desc, EngineImportService engineImportService)
        throws AnnotationException {
    // resolve class
    final Class annotationClass;
    try {/*from ww w.  ja v a2  s. c  o  m*/
        annotationClass = engineImportService.resolveAnnotation(desc.getName());
    } catch (EngineImportException e) {
        throw new AnnotationException("Failed to resolve @-annotation class: " + e.getMessage());
    }

    // obtain Annotation class properties
    List<AnnotationAttribute> annotationAttributeLists = getAttributes(annotationClass);
    Set<String> allAttributes = new HashSet<String>();
    Set<String> requiredAttributes = new LinkedHashSet<String>();
    for (AnnotationAttribute annotationAttribute : annotationAttributeLists) {
        allAttributes.add(annotationAttribute.getName());
        if (annotationAttribute.getDefaultValue() != null) {
            requiredAttributes.add(annotationAttribute.getName());
        }
    }

    // get attribute values
    List<String> providedValues = new ArrayList<String>();
    for (Pair<String, Object> annotationValuePair : desc.getAttributes()) {
        providedValues.add(annotationValuePair.getFirst());
    }

    // for all attributes determine value
    final Map<String, Object> properties = new LinkedHashMap<String, Object>();
    for (AnnotationAttribute annotationAttribute : annotationAttributeLists) {
        // find value pair for this attribute
        String attributeName = annotationAttribute.getName();
        Pair<String, Object> pairFound = null;
        for (Pair<String, Object> annotationValuePair : desc.getAttributes()) {
            if (annotationValuePair.getFirst().equals(attributeName)) {
                pairFound = annotationValuePair;
            }
        }

        Object valueProvided = pairFound == null ? null : pairFound.getSecond();
        Object value = getFinalValue(annotationClass, annotationAttribute, valueProvided, engineImportService);
        properties.put(attributeName, value);
        providedValues.remove(attributeName);
        requiredAttributes.remove(attributeName);
    }

    if (requiredAttributes.size() > 0) {
        List<String> required = new ArrayList<String>(requiredAttributes);
        Collections.sort(required);
        throw new AnnotationException("Annotation '" + annotationClass.getSimpleName()
                + "' requires a value for attribute '" + required.iterator().next() + "'");
    }

    if (providedValues.size() > 0) {
        List<String> provided = new ArrayList<String>(providedValues);
        Collections.sort(provided);
        if (allAttributes.contains(provided.get(0))) {
            throw new AnnotationException("Annotation '" + annotationClass.getSimpleName()
                    + "' has duplicate attribute values for attribute '" + provided.get(0) + "'");
        } else {
            throw new AnnotationException("Annotation '" + annotationClass.getSimpleName()
                    + "' does not have an attribute '" + provided.get(0) + "'");
        }
    }

    // return handler
    InvocationHandler handler = new EPLAnnotationInvocationHandler(annotationClass, properties);
    return (Annotation) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
            new Class[] { annotationClass }, handler);
}