List of usage examples for java.lang.reflect Proxy newProxyInstance
private static Object newProxyInstance(Class<?> caller, Constructor<?> cons, InvocationHandler h)
From source file:org.apache.oozie.client.rest.JsonToBean.java
/** * Creates a Bulk response object from a JSON object. * * @param json json object.//from w w w .jav a 2 s . c om * @return a Bulk response object populated with the JSON object values. */ public static BulkResponse createBulkResponse(JSONObject json) { return (BulkResponse) Proxy.newProxyInstance(JsonToBean.class.getClassLoader(), new Class[] { BulkResponse.class }, new JsonInvocationHandler(BULK_RESPONSE, json)); }
From source file:org.apache.olingo.ext.proxy.commons.AbstractStructuredInvocationHandler.java
protected Object retrieveNavigationProperty(final NavigationProperty property, final Method getter) { final Class<?> type = getter.getReturnType(); final Class<?> collItemType; if (EntityCollection.class.isAssignableFrom(type)) { collItemType = ClassUtils.extractTypeArg(type, EntityCollection.class, ComplexCollection.class); } else {/*from w ww . j a v a2 s . com*/ collItemType = type; } final Object navPropValue; URI targetEntitySetURI = CoreUtils.getTargetEntitySetURI(getClient(), property); final ClientLink link = ((ClientLinked) internal).getNavigationLink(property.name()); if (link instanceof ClientInlineEntity) { // return entity navPropValue = ProxyUtils.getEntityProxy(service, ((ClientInlineEntity) link).getEntity(), targetEntitySetURI, type, null, false); } else if (link instanceof ClientInlineEntitySet) { if (AbstractEntitySet.class.isAssignableFrom(type)) { navPropValue = ProxyUtils.getEntitySetProxy(service, type, ((ClientInlineEntitySet) link).getEntitySet(), targetEntitySetURI, false); } else { // return entity set navPropValue = ProxyUtils.getEntityCollectionProxy(service, collItemType, type, targetEntitySetURI, ((ClientInlineEntitySet) link).getEntitySet(), targetEntitySetURI, false); } } else { // navigate final URI targetURI = URIUtils.getURI(getEntityHandler().getEntityURI(), property.name()); if (EntityCollection.class.isAssignableFrom(type)) { navPropValue = ProxyUtils.getEntityCollectionProxy(service, collItemType, type, targetEntitySetURI, null, targetURI, true); } else if (AbstractEntitySet.class.isAssignableFrom(type)) { navPropValue = ProxyUtils.getEntitySetProxy(service, type, targetURI); // cannot be used standard target entity set URI } else { final EntityUUID uuid = new EntityUUID(targetEntitySetURI, collItemType, null); LOG.debug("Ask for '{}({})'", collItemType.getSimpleName(), null); EntityInvocationHandler handler = getContext().entityContext().getEntity(uuid); if (handler == null) { final ClientEntity entity = getClient().getObjectFactory() .newEntity(new FullQualifiedName(collItemType.getAnnotation(Namespace.class).value(), ClassUtils.getEntityTypeName(collItemType))); handler = EntityInvocationHandler.getInstance(entity, URIUtils.getURI(this.uri.build(), property.name()), targetEntitySetURI, collItemType, service); } else if (getContext().entityContext().getStatus(handler) == AttachedEntityStatus.DELETED) { // object deleted LOG.debug("Object '{}({})' has been deleted", collItemType.getSimpleName(), uuid); handler = null; } navPropValue = handler == null ? null : Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class<?>[] { collItemType }, handler); } } return navPropValue; }
From source file:org.auraframework.http.AuraTestFilter.java
private String buildJsTestTargetUri(DefDescriptor<?> targetDescriptor, TestCaseDef testDef) throws QuickFixException { Map<String, Object> targetAttributes = testDef.getAttributeValues(); // Force "legacy" style tests until ready if (!ENABLE_FREEFORM_TESTS && targetAttributes == null) { targetAttributes = ImmutableMap.of(); }/* w w w . j a v a2 s. c o m*/ if (targetAttributes != null) { // The test has attributes specified, so request for the target component with the test's attributes. String hash = ""; List<NameValuePair> newParams = Lists.newArrayList(); for (Entry<String, Object> entry : targetAttributes.entrySet()) { String key = entry.getKey(); String value; if (entry.getValue() instanceof Map<?, ?> || entry.getValue() instanceof List<?>) { value = JsonEncoder.serialize(entry.getValue()); } else { value = entry.getValue().toString(); } if (key.equals("__layout")) { hash = value; } else { newParams.add(new BasicNameValuePair(key, value)); } } String qs = URLEncodedUtils.format(newParams, "UTF-8") + hash; return createURI(targetDescriptor.getNamespace(), targetDescriptor.getName(), targetDescriptor.getDefType(), null, Format.HTML, Authentication.AUTHENTICATED.name(), NO_RUN, qs); } else { // Free-form tests will load only the target component's template. // TODO: Allow specifying the template on the test. // TODO: Load proxy app for cmps, apps must loadApplication. final BaseComponentDef originalDef = (BaseComponentDef) definitionService .getDefinition(targetDescriptor); final ComponentDef targetTemplate = originalDef.getTemplateDef(); String newDescriptorString = String.format("%s$%s", targetDescriptor.getDescriptorName(), testDef.getName()); final DefDescriptor<ApplicationDef> newDescriptor = definitionService .getDefDescriptor(newDescriptorString, ApplicationDef.class); final ApplicationDef dummyDef = definitionService.getDefinition("aurajstest:blank", ApplicationDef.class); BaseComponentDef targetDef = (BaseComponentDef) Proxy.newProxyInstance( originalDef.getClass().getClassLoader(), new Class<?>[] { ApplicationDef.class }, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { switch (method.getName()) { case "getDescriptor": return newDescriptor; case "getTemplateDef": return targetTemplate; case "isLocallyRenderable": return method.invoke(originalDef, args); default: return method.invoke(dummyDef, args); } } }); TestContext testContext = testContextAdapter.getTestContext(testDef.getQualifiedName()); testContext.getLocalDefs().add(targetDef); return createURI(newDescriptor.getNamespace(), newDescriptor.getName(), newDescriptor.getDefType(), null, Format.HTML, Authentication.AUTHENTICATED.name(), NO_RUN, null); } }
From source file:org.codehaus.groovy.grails.plugins.springsecurity.SpringSecurityUtils.java
private static Object createDelegate(final String configKey, Class<?> interfaceClass, Class<?> implClass) { try {// w w w . j av a 2 s . co m storeInContext(configKey, implClass.newInstance()); } catch (InstantiationException impossible) { // impossible with regular java.util classes } catch (IllegalAccessException impossible) { // impossible with regular java.util classes } return Proxy.newProxyInstance(implClass.getClassLoader(), new Class[] { interfaceClass }, new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { return method.invoke(getFromContext(configKey), args); } }); }
From source file:org.broadleafcommerce.core.catalog.domain.SkuImpl.java
@Override public Money getSalePrice() { Money returnPrice = null;/*from ww w.j a va 2s .c o m*/ Money optionValueAdjustments = null; if (SkuPricingConsiderationContext.hasDynamicPricing()) { // We have dynamic pricing, so we will pull the sale price from there if (dynamicPrices == null) { DefaultDynamicSkuPricingInvocationHandler handler = new DefaultDynamicSkuPricingInvocationHandler( this); Sku proxy = (Sku) Proxy.newProxyInstance(getClass().getClassLoader(), ClassUtils.getAllInterfacesForClass(getClass()), handler); dynamicPrices = SkuPricingConsiderationContext.getSkuPricingService().getSkuPrices(proxy, SkuPricingConsiderationContext.getSkuPricingConsiderationContext()); } returnPrice = dynamicPrices.getSalePrice(); optionValueAdjustments = dynamicPrices.getPriceAdjustment(); } else if (salePrice != null) { // We have an explicitly set sale price directly on this entity. We will not apply any adjustments returnPrice = new Money(salePrice, getCurrency()); } if (returnPrice == null && hasDefaultSku()) { returnPrice = lookupDefaultSku().getSalePrice(); optionValueAdjustments = getProductOptionValueAdjustments(); } if (returnPrice == null) { return null; } if (optionValueAdjustments != null) { returnPrice = returnPrice.add(optionValueAdjustments); } return returnPrice; }
From source file:net.wequick.small.ApkBundleLauncher.java
@Override public void setUp(Context context) { super.setUp(context); Field f;//from w w w . j av a2 s.c o m // AOP for pending intent try { f = TaskStackBuilder.class.getDeclaredField("IMPL"); f.setAccessible(true); final Object impl = f.get(TaskStackBuilder.class); InvocationHandler aop = new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Intent[] intents = (Intent[]) args[1]; for (Intent intent : intents) { sBundleInstrumentation.wrapIntent(intent); intent.setAction(Intent.ACTION_MAIN); intent.addCategory(Intent.CATEGORY_LAUNCHER); } return method.invoke(impl, args); } }; Object newImpl = Proxy.newProxyInstance(context.getClassLoader(), impl.getClass().getInterfaces(), aop); f.set(TaskStackBuilder.class, newImpl); } catch (Exception ignored) { ignored.printStackTrace(); } }
From source file:org.apache.juneau.rest.client.RestClient.java
/** * Same as {@link #getRemoteableProxy(Class, Object)} but allows you to override the serializer and parser used. * * @param interfaceClass The interface to create a proxy for. * @param restUrl The URL of the REST interface. * @param serializer The serializer used to serialize POJOs to the body of the HTTP request. * @param parser The parser used to parse POJOs from the body of the HTTP response. * @return The new proxy interface.//from www .j a v a 2 s . c o m */ @SuppressWarnings({ "unchecked", "hiding" }) public <T> T getRemoteableProxy(final Class<T> interfaceClass, Object restUrl, final Serializer serializer, final Parser parser) { if (restUrl == null) { Remoteable r = ReflectionUtils.getAnnotation(Remoteable.class, interfaceClass); String path = r == null ? "" : trimSlashes(r.path()); if (path.indexOf("://") == -1) { if (path.isEmpty()) path = interfaceClass.getName(); if (rootUrl == null) throw new RemoteableMetadataException(interfaceClass, "Root URI has not been specified. Cannot construct absolute path to remoteable proxy."); path = trimSlashes(rootUrl) + '/' + path; } restUrl = path; } final String restUrl2 = restUrl.toString(); try { return (T) Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class[] { interfaceClass }, new InvocationHandler() { final RemoteableMeta rm = new RemoteableMeta(interfaceClass, restUrl2); @Override /* InvocationHandler */ public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { RemoteableMethodMeta rmm = rm.getMethodMeta(method); if (rmm == null) throw new RuntimeException("Method is not exposed as a remoteable method."); try { String url = rmm.getUrl(); String httpMethod = rmm.getHttpMethod(); RestCall rc = (httpMethod.equals("POST") ? doPost(url) : doGet(url)); rc.serializer(serializer).parser(parser); for (RemoteMethodArg a : rmm.getPathArgs()) rc.path(a.name, args[a.index], a.serializer); for (RemoteMethodArg a : rmm.getQueryArgs()) rc.query(a.name, args[a.index], a.skipIfNE, a.serializer); for (RemoteMethodArg a : rmm.getFormDataArgs()) rc.formData(a.name, args[a.index], a.skipIfNE, a.serializer); for (RemoteMethodArg a : rmm.getHeaderArgs()) rc.header(a.name, args[a.index], a.skipIfNE, a.serializer); if (rmm.getBodyArg() != null) rc.input(args[rmm.getBodyArg()]); if (rmm.getRequestBeanArgs().length > 0) { BeanSession bs = getBeanContext().createSession(); for (Integer i : rmm.getRequestBeanArgs()) { BeanMap<?> bm = bs.toBeanMap(args[i]); for (BeanPropertyValue bpv : bm.getValues(true)) { BeanPropertyMeta pMeta = bpv.getMeta(); Object val = bpv.getValue(); Path p = pMeta.getAnnotation(Path.class); if (p != null) rc.path(getName(p.value(), pMeta), val, getPartSerializer(p.serializer())); Query q1 = pMeta.getAnnotation(Query.class); if (q1 != null) rc.query(getName(q1.value(), pMeta), val, false, getPartSerializer(q1.serializer())); QueryIfNE q2 = pMeta.getAnnotation(QueryIfNE.class); if (q2 != null) rc.query(getName(q2.value(), pMeta), val, true, getPartSerializer(q2.serializer())); FormData f1 = pMeta.getAnnotation(FormData.class); if (f1 != null) rc.formData(getName(f1.value(), pMeta), val, false, getPartSerializer(f1.serializer())); FormDataIfNE f2 = pMeta.getAnnotation(FormDataIfNE.class); if (f2 != null) rc.formData(getName(f2.value(), pMeta), val, true, getPartSerializer(f2.serializer())); org.apache.juneau.remoteable.Header h1 = pMeta .getAnnotation(org.apache.juneau.remoteable.Header.class); if (h1 != null) rc.header(getName(h1.value(), pMeta), val, false, getPartSerializer(h1.serializer())); HeaderIfNE h2 = pMeta.getAnnotation(HeaderIfNE.class); if (h2 != null) rc.header(getName(h2.value(), pMeta), val, true, getPartSerializer(h2.serializer())); } } } if (rmm.getOtherArgs().length > 0) { Object[] otherArgs = new Object[rmm.getOtherArgs().length]; int i = 0; for (Integer otherArg : rmm.getOtherArgs()) otherArgs[i++] = args[otherArg]; rc.input(otherArgs); } return rc.getResponse(method.getGenericReturnType()); } catch (RestCallException e) { // Try to throw original exception if possible. e.throwServerException(interfaceClass.getClassLoader()); throw new RuntimeException(e); } catch (Exception e) { throw new RuntimeException(e); } } }); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:org.apache.olingo.ext.proxy.utils.CoreUtils.java
public static Object getObjectFromODataValue(final ClientValue value, final Class<?> ref, final AbstractService<?> service) throws InstantiationException, IllegalAccessException { final Object res; if (value == null) { res = null;/*from www . j a v a 2 s.c om*/ } else if (value.isComplex()) { // complex types supports inheritance in V4, best to re-read actual type Class<?> internalRef = getComplexTypeRef(service, value); res = Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class<?>[] { internalRef }, ComplexInvocationHandler.getInstance(value.asComplex(), internalRef, service)); } else if (value.isCollection()) { final ArrayList<Object> collection = new ArrayList<Object>(); final Iterator<ClientValue> collPropItor = value.asCollection().iterator(); while (collPropItor.hasNext()) { final ClientValue itemValue = collPropItor.next(); if (itemValue.isPrimitive()) { collection.add(CoreUtils.primitiveValueToObject(itemValue.asPrimitive(), ref)); } else if (itemValue.isComplex()) { Class<?> internalRef = getComplexTypeRef(service, value); final Object collItem = Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class<?>[] { internalRef }, ComplexInvocationHandler.getInstance(itemValue.asComplex(), internalRef, service)); collection.add(collItem); } } res = collection; } else if (value instanceof ClientEnumValue) { res = enumValueToObject((ClientEnumValue) value, ref == null ? getEnumTypeRef(service, value) : ref); } else { res = primitiveValueToObject(value.asPrimitive(), ref); } return res; }
From source file:com.taobao.adfs.distributed.rpc.RPC.java
/** * Construct a client-side proxy object that implements the named protocol, talking to a server at the named address. *//*from w w w . ja v a 2s .co m*/ public static VersionedProtocol getProxy(Class<?> protocol, long clientVersion, InetSocketAddress addr, Configuration conf, SocketFactory factory) throws IOException { VersionedProtocol proxy = (VersionedProtocol) Proxy.newProxyInstance(protocol.getClassLoader(), new Class[] { protocol }, new Invoker(addr, conf, factory)); long serverVersion = proxy.getProtocolVersion(protocol.getName(), clientVersion); if (serverVersion == clientVersion) { return proxy; } else { throw new VersionMismatch(protocol.getName(), clientVersion, serverVersion); } }
From source file:org.apache.nifi.authorization.AuthorizerFactory.java
/** * Decorates the base authorizer to ensure the nar context classloader is used when invoking the underlying methods. * * @param baseAuthorizer base authorizer * @return authorizer//ww w. java 2 s . c o m */ public static Authorizer withNarLoader(final Authorizer baseAuthorizer, final ClassLoader classLoader) { final AuthorizerInvocationHandler invocationHandler = new AuthorizerInvocationHandler(baseAuthorizer, classLoader); // extract all interfaces... baseAuthorizer is non null so getAllInterfaces is non null final List<Class<?>> interfaceList = ClassUtils.getAllInterfaces(baseAuthorizer.getClass()); final Class<?>[] interfaces = interfaceList.toArray(new Class<?>[interfaceList.size()]); return (Authorizer) Proxy.newProxyInstance(classLoader, interfaces, invocationHandler); }