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:jp.go.nict.langrid.client.soap.SoapClientFactory.java

private <T> T create(Class<T> interfaceClass, AxisStublessInvocationHandler h) {
    return interfaceClass.cast(Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
            new Class<?>[] { interfaceClass, SoapRequestAttributes.class, ResponseAttributes.class }, h));
}

From source file:org.kuali.student.common.spring.WebServiceAwareSpringBeanPostProcessor.java

@Override
public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {

    Class<? extends Object> beanClass = bean.getClass();

    try {//from   w  w  w.j  a v a 2 s.c  om
        super.processInjection(bean);

    } catch (BeansException e2) {
        // any resolved beans from the local applicationContext will have been injected into the bean by now
        // so fall through.
        // we will only update the @Autowired fields that are null and declare @WebService annotations.
    }

    Field[] fields = beanClass.getDeclaredFields();

    for (Field field : fields) {

        // check for the @Autowired, @Resource, or @Value annotation
        if (!fieldHasInjectionAnnotation(field))
            continue; // skip fields that don't have an injection annotation

        Object currentValue = null;
        try {

            ReflectionUtils.makeAccessible(field);

            currentValue = field.get(bean);

        } catch (IllegalArgumentException e1) {
            log.warn("get error", e1);
            continue;

        } catch (SecurityException e1) {
            log.warn("get error", e1);
            continue;
        } catch (IllegalAccessException e1) {
            log.warn("get error", e1);
            continue;
        }

        // Only resolve using KSB if the object value has not been set.
        if (currentValue != null)
            continue; // was handled already

        Class<?> fieldType = field.getType();

        WebService webServiceAnnotation = (WebService) fieldType.getAnnotation(WebService.class);

        if (webServiceAnnotation != null) {

            // we can only auto resolve if the @WebService annotation is
            // present.

            String namespace = webServiceAnnotation.targetNamespace();
            String serviceName = webServiceAnnotation.serviceName();

            if (serviceName.isEmpty())
                serviceName = webServiceAnnotation.name();

            if (namespace != null) {

                // First check to see if the application context has a reference 
                // using the serivceName

                try {

                    Object service = null;
                    try {
                        service = beanFactory.getBean(serviceName, fieldType);
                    } catch (NoSuchBeanDefinitionException e) {
                        service = null;
                        // fall through
                    }

                    if (service != null) {
                        injectServiceReference(bean, beanName, field, service,
                                " from ApplicationContext using BeanName: " + serviceName);
                        continue; // skip to the next field
                    }
                    // else service == null
                    // now try to resolve using the ksb

                    final QName name = new QName(namespace, serviceName);

                    try {
                        SerializableProxyInvokationHandler invocationHandler = new SerializableProxyInvokationHandler();

                        invocationHandler.setServiceName(name);

                        service = Proxy.newProxyInstance(getClass().getClassLoader(), new Class[] { fieldType },
                                invocationHandler);

                        // now we have the service, try to inject it.
                        injectServiceReference(bean, beanName, field, service,
                                " from KSB using QName: " + name);

                    } catch (NullPointerException e1) {
                        log.warn("RiceResourceLoader is not configured/initialized properly.", e1);
                        // skip to the next field.
                        continue;
                    }

                } catch (Exception e) {
                    log.error("failed to lookup resource in GlobalResourceLoader (" + namespace + ", "
                            + serviceName + ")", e);
                    continue;
                }
            }

        }
    }

    // skip over any of the other post processors
    return false;
}

From source file:com.google.code.ssm.CacheFactory.java

/**
 * Only one cache is created./*  w  ww  .  ja  v  a  2s .  c o m*/
 * 
 * @return cache
 * @throws IOException
 */
protected Cache createCache() throws IOException {
    // this factory creates only one single cache and return it if someone invoked this method twice or
    // more
    if (cache != null) {
        throw new IllegalStateException(
                String.format("This factory has already created memcached client for cache %s", cacheName));
    }

    if (isCacheDisabled()) {
        LOGGER.warn("Cache {} is disabled", cacheName);
        cache = (Cache) Proxy.newProxyInstance(Cache.class.getClassLoader(), new Class[] { Cache.class },
                new DisabledCacheInvocationHandler(cacheName, cacheAliases));
        return cache;
    }

    if (configuration == null) {
        throw new RuntimeException(
                String.format("The MemcachedConnectionBean for cache %s must be defined!", cacheName));
    }

    List<InetSocketAddress> addrs = addressProvider.getAddresses();
    cache = new CacheImpl(cacheName, cacheAliases, createClient(addrs), defaultSerializationType,
            jsonTranscoder, javaTranscoder, customTranscoder,
            new CacheProperties(configuration.isUseNameAsKeyPrefix(), configuration.getKeyPrefixSeparator()));

    return cache;
}

From source file:org.apache.hadoop.hdfs.server.namenode.ha.RequestHedgingProxyProvider.java

@SuppressWarnings("unchecked")
@Override/*from  ww w . j a  v  a2s. co  m*/
public synchronized ProxyInfo<T> getProxy() {
    if (successfulProxy != null) {
        return successfulProxy;
    }
    Map<String, ProxyInfo<T>> targetProxyInfos = new HashMap<>();
    StringBuilder combinedInfo = new StringBuilder('[');
    for (int i = 0; i < proxies.size(); i++) {
        ProxyInfo<T> pInfo = super.getProxy();
        incrementProxyIndex();
        targetProxyInfos.put(pInfo.proxyInfo, pInfo);
        combinedInfo.append(pInfo.proxyInfo).append(',');
    }
    combinedInfo.append(']');
    T wrappedProxy = (T) Proxy.newProxyInstance(RequestHedgingInvocationHandler.class.getClassLoader(),
            new Class<?>[] { xface }, new RequestHedgingInvocationHandler(targetProxyInfos));
    return new ProxyInfo<T>(wrappedProxy, combinedInfo.toString());
}

From source file:gov.nih.nci.firebird.proxy.PoolingHandlerTest.java

@Test
public void testProvider() {
    @SuppressWarnings("unchecked")
    Provider<ITestClient> provider = mock(Provider.class);
    when(provider.get()).thenAnswer(new Answer<ITestClient>() {
        @Override/*  w ww  .  j  ava 2s .c  om*/
        public ITestClient answer(InvocationOnMock invocation) throws Throwable {
            return makeBaseMockClient();
        }
    });
    InvocationHandler handler = new PoolingHandler(provider, 3, 3);
    ITestClient proxy = (ITestClient) Proxy.newProxyInstance(this.getClass().getClassLoader(),
            new Class<?>[] { ITestClient.class }, handler);
    proxy.doSomethingUseful(null);
    verify(provider, times(1)).get();
}

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

@SuppressWarnings({ "unchecked", "rawtypes" })
public T execute() {
    if (operation == null || uri == null) {
        throw new IllegalStateException("Invalid operation");
    }//from  ww w  .ja  va2 s. com

    try {
        // 1. IMPORTANT: flush any pending change *before* invoke if this operation is side effecting
        if (operation.type() == OperationType.ACTION) {
            service.getPersistenceManager().flush();
        }

        // 2. invoke
        final ClientInvokeResult result = service.getClient().getInvokeRequestFactory()
                .getInvokeRequest(edmOperation instanceof EdmFunction ? HttpMethod.GET : HttpMethod.POST,
                        uri.build(), getResultReference(edmOperation.getReturnType()), parameters)
                .execute().getBody();

        // 3. process invoke result
        if (StringUtils.isBlank(operation.returnType())) {
            return (T) ClassUtils.returnVoid();
        }

        final EdmTypeInfo returnType = new EdmTypeInfo.Builder().setEdm(service.getClient().getCachedEdm())
                .setTypeExpression(operation.returnType()).build();

        if (returnType.isEntityType()) {
            if (returnType.isCollection()) {
                final Class<?> collItemType = ClassUtils.extractTypeArg(targetRef, EntityCollection.class);
                return (T) ProxyUtils.getEntityCollectionProxy(service, collItemType, targetRef, null,
                        (ClientEntitySet) result, this.baseURI, false);
            } else {
                return (T) ProxyUtils.getEntityProxy(service, (ClientEntity) result, null, targetRef, null,
                        false);
            }
        } else {
            Object res;

            final Class<?> ref = ClassUtils.getTypeClass(targetRef);
            final ClientProperty property = (ClientProperty) result;

            if (property == null || property.hasNullValue()) {
                res = null;
            } else if (returnType.isCollection()) {
                if (returnType.isComplexType()) {
                    final Class<?> itemRef = ClassUtils.extractTypeArg(ref, ComplexCollection.class);
                    final List items = new ArrayList();

                    for (ClientValue item : property.getValue().asCollection()) {
                        items.add(ProxyUtils.getComplexProxy(service, property.getName(), item, itemRef, null,
                                null, true));
                    }

                    res = Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                            new Class<?>[] { ref },
                            new ComplexCollectionInvocationHandler(service, items, itemRef, null));
                } else {
                    final List items = new ArrayList();

                    for (ClientValue item : property.getValue().asCollection()) {
                        items.add(item.asPrimitive().toValue());
                    }

                    res = Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                            new Class<?>[] { PrimitiveCollection.class },
                            new PrimitiveCollectionInvocationHandler(service, items, null, null));
                }
            } else {
                if (returnType.isComplexType()) {
                    res = ProxyUtils.getComplexProxy(service, property.getName(),
                            property.getValue().asComplex(), ref, null, null, false);
                } else {
                    res = CoreUtils.getObjectFromODataValue(property.getValue(), targetRef, service);
                }
            }

            return (T) res;
        }
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
}

From source file:org.apache.hadoop.hbase.ipc.WritableRpcEngine.java

/** Construct a client-side proxy object that implements the named protocol,
 * talking to a server at the named address. */
public VersionedProtocol getProxy(Class<? extends VersionedProtocol> protocol, long clientVersion,
        InetSocketAddress addr, User ticket, Configuration conf, SocketFactory factory, int rpcTimeout)
        throws IOException {

    VersionedProtocol proxy = (VersionedProtocol) Proxy.newProxyInstance(protocol.getClassLoader(),
            new Class[] { protocol }, new Invoker(protocol, addr, ticket, conf, factory, rpcTimeout));
    if (proxy instanceof VersionedProtocol) {
        long serverVersion = ((VersionedProtocol) proxy).getProtocolVersion(protocol.getName(), clientVersion);
        if (serverVersion != clientVersion) {
            throw new HBaseRPC.VersionMismatch(protocol.getName(), clientVersion, serverVersion);
        }//  ww w. jav  a  2s. c o  m
    }
    return proxy;
}

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.
 * @param username the per-Session username
 * @param password the per-Session password
 * @return a lazy Session handle/*from   w ww.j  a  v a2  s .  co m*/
 * @see SessionProxy#getTargetSession() ()
 */
@Override
public Session newSession(String username, String password) {
    return (Session) Proxy.newProxyInstance(SessionProxy.class.getClassLoader(),
            new Class<?>[] { SessionProxy.class }, new LazySessionInvocationHandler(username, password));
}

From source file:org.apache.openejb.cdi.OptimizedLoaderService.java

private List<? extends OpenWebBeansPlugin> loadWebBeansPlugins(final ClassLoader loader) {
    final List<OpenWebBeansPlugin> list = new ArrayList<>(2);
    list.add(new CdiPlugin());
    {/*from  w  w  w  .j  a v  a 2s .  c o  m*/
        final Class<?> clazz;
        try {
            clazz = loader.loadClass("org.apache.geronimo.openejb.cdi.GeronimoWebBeansPlugin");
            try {
                list.add(OpenWebBeansPlugin.class.cast(clazz.newInstance()));
            } catch (final Exception e) {
                log.error("Unable to load OpenWebBeansPlugin: GeronimoWebBeansPlugin");
            }
        } catch (final ClassNotFoundException e) {
            // ignore
        }
    }
    {
        final Class<?> clazz;
        try {
            clazz = loader.loadClass("org.apache.webbeans.jsf.plugin.OpenWebBeansJsfPlugin");
            try {
                list.add(OpenWebBeansPlugin.class.cast(Proxy.newProxyInstance(loader,
                        new Class<?>[] { OpenWebBeansPlugin.class },
                        new ClassLoaderAwareHandler(clazz.getSimpleName(), clazz.newInstance(), loader))));
            } catch (final Exception e) {
                log.error("Unable to load OpenWebBeansPlugin: OpenWebBeansJsfPlugin");
            }
        } catch (final ClassNotFoundException e) {
            // ignore
        }
    }
    return list;
}

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

@SuppressWarnings("unchecked")
public <T extends ComplexType<?>, NEC extends ComplexCollection<T, ?, ?>> NEC newComplexCollection(
        final Class<NEC> ref) {
    final Class<T> itemRef = (Class<T>) ClassUtils.extractTypeArg(ref, ComplexCollection.class);

    return (NEC) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class<?>[] { ref },
            new ComplexCollectionInvocationHandler<T>(getService(), itemRef));
}