List of usage examples for java.lang.reflect Proxy newProxyInstance
private static Object newProxyInstance(Class<?> caller, Constructor<?> cons, InvocationHandler h)
From source file:com.cloud.bridge.service.controller.s3.ServiceProvider.java
@SuppressWarnings("unchecked") private static <T> T getProxy(Class<?> serviceInterface, final T serviceObject) { return (T) Proxy.newProxyInstance(serviceObject.getClass().getClassLoader(), new Class[] { serviceInterface }, new InvocationHandler() { @Override/*from w w w .j a va 2s . c o m*/ public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Object result = null; try { result = method.invoke(serviceObject, args); } catch (Throwable e) { // Rethrow the exception to Axis: // Check if the exception is an AxisFault or a // RuntimeException // enveloped AxisFault and if so, pass it on as // such. Otherwise // log to help debugging and throw as is. if (e.getCause() != null && e.getCause() instanceof AxisFault) throw e.getCause(); else if (e.getCause() != null && e.getCause().getCause() != null && e.getCause().getCause() instanceof AxisFault) throw e.getCause().getCause(); else { logger.warn("Unhandled exception " + e.getMessage(), e); throw e; } } finally { } return result; } }); }
From source file:net.joshdevins.rabbitmq.client.ha.HaConnectionFactory.java
/** * Creates an {@link HaConnectionProxy} around a raw {@link Connection}. *///from w w w . ja v a 2 s .c o m protected ConnectionSet createConnectionProxy(final Address[] addrs, final Integer maxRedirects, final Connection targetConnection) { ClassLoader classLoader = Connection.class.getClassLoader(); Class<?>[] interfaces = { Connection.class }; HaConnectionProxy proxy = new HaConnectionProxy(addrs, maxRedirects, targetConnection, retryStrategy); if (LOG.isDebugEnabled()) { LOG.debug("Creating connection proxy: " + (targetConnection == null ? "none" : targetConnection.toString())); } Connection target = (Connection) Proxy.newProxyInstance(classLoader, interfaces, proxy); HaShutdownListener listener = new HaShutdownListener(proxy); // failed initial connections will have this set later upon successful connection if (targetConnection != null) { target.addShutdownListener(listener); } return new ConnectionSet(target, proxy, listener); }
From source file:org.apache.olingo.ext.proxy.commons.AbstractStructuredInvocationHandler.java
@SuppressWarnings({ "unchecked", "rawtypes" }) protected Object getPropertyValue(final String name, final Type type) { try {//from w w w . j a v a 2 s . co m Object res; final Class<?> ref = ClassUtils.getTypeClass(type); if (ref == EdmStreamValue.class) { if (streamedPropertyCache.containsKey(name)) { res = streamedPropertyCache.get(name); } else if (streamedPropertyChanges.containsKey(name)) { res = streamedPropertyChanges.get(name); } else { res = Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class<?>[] { EdmStreamValue.class }, new EdmStreamValueHandler(baseURI == null ? null : getClient().newURIBuilder(baseURI.toASCIIString()).appendPropertySegment(name) .build(), service)); streamedPropertyCache.put(name, EdmStreamValue.class.cast(res)); } return res; } else { if (propertyChanges.containsKey(name)) { res = propertyChanges.get(name); } else if (propertyCache.containsKey(name)) { res = propertyCache.get(name); } else { final ClientProperty property = getInternalProperty(name); if (ref != null && ClassUtils.getTypeClass(type).isAnnotationPresent(ComplexType.class)) { res = getComplex(name, property == null || property.hasNullValue() ? null : property.getValue(), ref, getEntityHandler(), baseURI, false); } else if (ref != null && ComplexCollection.class.isAssignableFrom(ref)) { final ComplexCollectionInvocationHandler<?> collectionHandler; final Class<?> itemRef = ClassUtils.extractTypeArg(ref, ComplexCollection.class); if (property == null || property.hasNullValue()) { collectionHandler = new ComplexCollectionInvocationHandler(itemRef, service, baseURI == null ? null : getClient().newURIBuilder(baseURI.toASCIIString()) .appendPropertySegment(name)); } else { List items = new ArrayList(); for (ClientValue item : property.getValue().asCollection()) { items.add(getComplex(name, item, itemRef, getEntityHandler(), null, true)); } collectionHandler = new ComplexCollectionInvocationHandler(service, items, itemRef, baseURI == null ? null : getClient().newURIBuilder(baseURI.toASCIIString()) .appendPropertySegment(name)); } res = Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class<?>[] { ref }, collectionHandler); } else if (ref != null && PrimitiveCollection.class.isAssignableFrom(ref)) { PrimitiveCollectionInvocationHandler collectionHandler; if (property == null || property.hasNullValue()) { collectionHandler = new PrimitiveCollectionInvocationHandler(service, null, baseURI == null ? null : getClient().newURIBuilder(baseURI.toASCIIString()) .appendPropertySegment(name)); } else { List items = new ArrayList(); for (ClientValue item : property.getValue().asCollection()) { items.add(item.asPrimitive().toValue()); } collectionHandler = new PrimitiveCollectionInvocationHandler(service, items, null, baseURI == null ? null : getClient().newURIBuilder(baseURI.toASCIIString()) .appendPropertySegment(name)); } res = Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class<?>[] { PrimitiveCollection.class }, collectionHandler); } else { res = property == null || property.hasNullValue() ? null : CoreUtils.getObjectFromODataValue(property.getValue(), type, service); } } if (res != null) { propertyCache.put(name, res); } return res; } } catch (Exception e) { throw new IllegalArgumentException("Error getting value for property '" + name + "'", e); } }
From source file:io.coala.enterprise.Actor.java
/** * @param actorType the type of {@link Actor} to mimic * @param callObserver an {@link Observer} of method call, or {@code null} * @return the {@link Proxy} instance//from w ww .ja v a2 s. c o m */ @SuppressWarnings("unchecked") static <A extends Actor<T>, F extends Fact, T extends F> A proxyAs(final Actor<F> impl, final Class<A> actorType, final Observer<Method> callObserver) { final A proxy = (A) Proxy.newProxyInstance(actorType.getClassLoader(), new Class<?>[] { actorType }, (self, method, args) -> { try { final Object result = method.isDefault() && Proxy.isProxyClass(self.getClass()) ? ReflectUtil.invokeDefaultMethod(self, method, args) : method.invoke(impl, args); if (callObserver != null) callObserver.onNext(method); return result; } catch (Throwable e) { if (e instanceof IllegalArgumentException) try { return ReflectUtil.invokeAsBean(impl.properties(), actorType, method, args); } catch (final Exception ignore) { LogUtil.getLogger(Fact.class).warn("{}method call failed: {}", method.isDefault() ? "default " : "", method, ignore); } if (e instanceof InvocationTargetException) e = e.getCause(); if (callObserver != null) callObserver.onError(e); throw e; } }); return proxy; }
From source file:ome.tools.hibernate.SessionStatus.java
public EmptySessionHolder() { super((Session) Proxy.newProxyInstance(Session.class.getClassLoader(), new Class[] { Session.class }, new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { String name = method.getName(); if (name.equals("toString")) { return "NULL SESSION PROXY"; }//from w w w .ja v a2 s. c o m else if (name.equals("hashCode")) { return 0; } else if (name.equals("equals")) { return args[0] == null ? false : proxy == args[0]; } else { throw new RuntimeException("No methods allowed"); } } })); }
From source file:com.msopentech.odatajclient.proxy.api.impl.EntitySetInvocationHandler.java
@SuppressWarnings("unchecked") public <S extends T, SEC extends AbstractEntityCollection<S>> SEC fetchWholeEntitySet(final URI entitySetURI, final Class<S> typeRef, final Class<SEC> collTypeRef) { final List<S> items = new ArrayList<S>(); URI nextURI = entitySetURI;//www.j a v a2s . c o m while (nextURI != null) { final Map.Entry<List<S>, URI> entitySet = fetchPartialEntitySet(nextURI, typeRef); nextURI = entitySet.getValue(); items.addAll(entitySet.getKey()); } return (SEC) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class<?>[] { collTypeRef }, new EntityCollectionInvocationHandler<S>(containerHandler, items, typeRef, containerHandler.getEntityContainerName(), entitySetURI)); }
From source file:org.apache.jxtadoop.ipc.RPC.java
/** Construct a client-side proxy object that implements the named protocol, * talking to a server at the named address. */ public static VersionedProtocol getProxy(Class<?> protocol, long clientVersion, PeerGroup pg, JxtaSocketAddress jsocka, UserGroupInformation ticket, Configuration conf, SocketFactory factory) throws IOException { VersionedProtocol proxy = (VersionedProtocol) Proxy.newProxyInstance(protocol.getClassLoader(), new Class[] { protocol }, new Invoker(pg, jsocka, ticket, conf, factory)); long serverVersion = proxy.getProtocolVersion(protocol.getName(), clientVersion); if (serverVersion == clientVersion) { return proxy; } else {/*from w w w.j a v a2 s . c om*/ throw new VersionMismatch(protocol.getName(), clientVersion, serverVersion); } }
From source file:gov.nih.nci.firebird.proxy.PoolingHandlerTest.java
private ITestClient newProxy(PoolableObjectFactory<Object> factory) { PoolingHandler handler = new PoolingHandler(factory, 5, 1); handler.getValidExceptions().add(IllegalArgumentException.class); return (ITestClient) Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class<?>[] { ITestClient.class }, handler); }
From source file:be.idamediafoundry.sofa.livecycle.dsc.util.AnnotationDrivenQDoxComponentInfoExtractor.java
private <T extends java.lang.annotation.Annotation> T convertToJavaLang(final Annotation annotation, final Class<T> expectedType) { try {// w w w . jav a 2 s .c om final Class<?> annotationClass = Class.forName(annotation.getType().getFullyQualifiedName()); @SuppressWarnings("unchecked") T proxy = (T) Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[] { annotationClass }, new InvocationHandler() { public Object invoke(Object instance, Method method, Object[] args) throws Throwable { if (method.getName().equals("toString")) { return "Proxied annotation of type " + annotationClass; } else if (method.getName().equals("getClass")) { return annotationClass; } Object value = annotation.getProperty(method.getName()); if (value == null) { return method.getDefaultValue(); } if (value instanceof Annotation) { java.lang.annotation.Annotation sub = convertToJavaLang((Annotation) value, java.lang.annotation.Annotation.class); return sub; } else { AnnotationConstant constant = (AnnotationConstant) value; value = constant.getValue(); return value; } } }); return proxy; } catch (ClassNotFoundException e) { throw new IllegalArgumentException( "The source code is annotated with a class that could not be found on your project's classpath, please fix this!", e); } }