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.atlas.TestUtils.java
/** * Adds a proxy wrapper around the specified MetadataService that automatically * resets the request context before every call. * * @param delegate//from w ww . j a v a2 s . c o m * @return */ public static MetadataService addSessionCleanupWrapper(final MetadataService delegate) { return (MetadataService) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[] { MetadataService.class }, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { try { resetRequestContext(); Object result = method.invoke(delegate, args); return result; } catch (InvocationTargetException e) { e.getCause().printStackTrace(); throw e.getCause(); } catch (Throwable t) { t.printStackTrace(); throw t; } } }); }
From source file:org.apache.axis2.jaxws.spi.ServiceDelegate.java
public <T> T getPort(org.apache.axis2.addressing.EndpointReference axis2EPR, String addressingNamespace, Class<T> sei, WebServiceFeature... features) { verifyServiceDescriptionActive();// ww w .j ava2 s. c o m DescriptionBuilderComposite sparseComposite = getPortMetadata(); resetPortMetadata(); EndpointDescription endpointDesc = null; if (sparseComposite != null) { endpointDesc = DescriptionFactory.updateEndpoint(serviceDescription, sei, axis2EPR, addressingNamespace, DescriptionFactory.UpdateType.GET_PORT, sparseComposite, this); } else { endpointDesc = DescriptionFactory.updateEndpoint(serviceDescription, sei, axis2EPR, addressingNamespace, DescriptionFactory.UpdateType.GET_PORT, null, this); } if (endpointDesc == null) { throw ExceptionFactory .makeWebServiceException(Messages.getMessage("serviceDelegateNoPort", axis2EPR.toString())); } String[] interfacesNames = new String[] { sei.getName(), org.apache.axis2.jaxws.spi.BindingProvider.class.getName() }; // As required by java.lang.reflect.Proxy, ensure that the interfaces // for the proxy are loadable by the same class loader. Class[] interfaces = null; // First, let's try loading the interfaces with the SEI classLoader ClassLoader classLoader = getClassLoader(sei); try { interfaces = loadClasses(classLoader, interfacesNames); } catch (ClassNotFoundException e1) { // Let's try with context classLoader now classLoader = getContextClassLoader(); try { interfaces = loadClasses(classLoader, interfacesNames); } catch (ClassNotFoundException e2) { throw ExceptionFactory .makeWebServiceException(Messages.getMessage("serviceDelegateProxyError", e2.getMessage())); } } JAXWSProxyHandler proxyHandler = new JAXWSProxyHandler(this, interfaces[0], endpointDesc, axis2EPR, addressingNamespace, features); Object proxyClass = Proxy.newProxyInstance(classLoader, interfaces, proxyHandler); return sei.cast(proxyClass); }
From source file:org.apache.atlas.TestUtils.java
/** * Adds a proxy wrapper around the specified MetadataRepository that automatically * resets the request context before every call and either commits or rolls * back the graph transaction after every call. * * @param delegate/*from w ww .java 2 s . c o m*/ * @return */ public static MetadataRepository addTransactionWrapper(final MetadataRepository delegate) { return (MetadataRepository) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[] { MetadataRepository.class }, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { boolean useTransaction = GraphBackedMetadataRepository.class .getMethod(method.getName(), method.getParameterTypes()) .isAnnotationPresent(GraphTransaction.class); try { resetRequestContext(); Object result = method.invoke(delegate, args); if (useTransaction) { System.out.println("Committing changes"); getGraph().commit(); System.out.println("Commit succeeded."); } return result; } catch (InvocationTargetException e) { e.getCause().printStackTrace(); if (useTransaction) { System.out.println("Rolling back changes due to exception."); getGraph().rollback(); } throw e.getCause(); } catch (Throwable t) { t.printStackTrace(); if (useTransaction) { System.out.println("Rolling back changes due to exception."); getGraph().rollback(); } throw t; } } }); }
From source file:com.ikanow.aleph2.data_model.utils.CrudServiceUtils.java
/** CRUD service proxy that optionally adds an extra term and allows the user to modify the results after they've run (eg to apply security service settings) * @author Alex/* w ww . j a va 2 s . co m*/ */ @SuppressWarnings("unchecked") public static <T> ICrudService<T> intercept(final Class<T> clazz, final ICrudService<T> delegate, final Optional<QueryComponent<T>> extra_query, final Optional<Function<QueryComponent<T>, QueryComponent<T>>> query_transform, final Map<String, BiFunction<Object, Object[], Object>> interceptors, final Optional<BiFunction<Object, Object[], Object>> default_interceptor) { InvocationHandler handler = new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { final Method m = delegate.getClass().getMethod(method.getName(), method.getParameterTypes()); // First off, apply the extra term to any relevant args: final Object[] args_with_extra_query_pretransform = query_transform.map(q -> { return (null != args) ? Arrays.stream(args) .map(o -> (null != o) && QueryComponent.class.isAssignableFrom(o.getClass()) ? q.apply((QueryComponent<T>) o) : o) .collect(Collectors.toList()).toArray() : args; }).orElse(args); final Object[] args_with_extra_query = extra_query.map(q -> { return (null != args_with_extra_query_pretransform) ? Arrays.stream(args_with_extra_query_pretransform) .map(o -> (null != o) && QueryComponent.class.isAssignableFrom(o.getClass()) ? CrudUtils.allOf((QueryComponent<T>) o, q) : o) .collect(Collectors.toList()).toArray() : args_with_extra_query_pretransform; }).orElse(args_with_extra_query_pretransform); // Special cases for: readOnlyVersion, getFilterdRepo / countObjects / getRawService / *byId final Object o = Lambdas.get(() -> { final SingleQueryComponent<T> base_query = JsonNode.class.equals(clazz) ? (SingleQueryComponent<T>) CrudUtils.allOf() : CrudUtils.allOf(clazz); try { if (extra_query.isPresent() && m.getName().equals("countObjects")) { // special case....change method and apply spec return delegate.countObjectsBySpec(extra_query.get()); } else if (extra_query.isPresent() && m.getName().equals("getObjectById")) { // convert from id to spec and append extra_query if (1 == args.length) { return delegate.getObjectBySpec(CrudUtils.allOf(extra_query.get(), base_query.when(JsonUtils._ID, args[0]))); } else { return delegate.getObjectBySpec( CrudUtils.allOf(extra_query.get(), base_query.when(JsonUtils._ID, args[0])), (List<String>) args[1], (Boolean) args[2]); } } else if (extra_query.isPresent() && m.getName().equals("deleteDatastore")) { CompletableFuture<Long> l = delegate.deleteObjectsBySpec(extra_query.get()); return l.thenApply(ll -> ll > 0); } else if (extra_query.isPresent() && m.getName().equals("deleteObjectById")) { // convert from id to spec and append extra_query return delegate.deleteObjectBySpec( CrudUtils.allOf(extra_query.get(), base_query.when(JsonUtils._ID, args[0]))); } else if (extra_query.isPresent() && m.getName().equals("updateObjectById")) { // convert from id to spec and append extra_query return delegate.updateObjectBySpec( CrudUtils.allOf(extra_query.get(), base_query.when(JsonUtils._ID, args[0])), Optional.empty(), (UpdateComponent<T>) args[1]); } else if (m.getName().equals("getRawService")) { // special case....convert the default query to JSON, if present Object o_internal = m.invoke(delegate, args_with_extra_query); Optional<QueryComponent<JsonNode>> json_extra_query = extra_query .map(qc -> qc.toJson()); return intercept(JsonNode.class, (ICrudService<JsonNode>) o_internal, json_extra_query, Optional.empty(), interceptors, default_interceptor); } else { // wrap any CrudService types Object o_internal = m.invoke(delegate, args_with_extra_query); return (null != o_internal) && ICrudService.class.isAssignableFrom(o_internal.getClass()) ? intercept(clazz, (ICrudService<T>) o_internal, extra_query, Optional.empty(), interceptors, default_interceptor) : o_internal; } } catch (IllegalAccessException ee) { throw new RuntimeException(ee); } catch (InvocationTargetException e) { throw new RuntimeException(e.getCause().getMessage(), e); } }); return interceptors .getOrDefault(m.getName(), default_interceptor.orElse(CrudServiceUtils::identityInterceptor)) .apply(o, args_with_extra_query); } }; return ICrudService.IReadOnlyCrudService.class.isAssignableFrom(delegate.getClass()) ? (ICrudService<T>) Proxy.newProxyInstance(ICrudService.IReadOnlyCrudService.class.getClassLoader(), new Class[] { ICrudService.IReadOnlyCrudService.class }, handler) : (ICrudService<T>) Proxy.newProxyInstance(ICrudService.class.getClassLoader(), new Class[] { ICrudService.class }, handler); }
From source file:org.apache.tinkerpop.gremlin.groovy.jsr223.GremlinGroovyScriptEngine.java
@SuppressWarnings("unchecked") private <T> T makeInterface(final Object obj, final Class<T> clazz) { if (null == clazz || !clazz.isInterface()) throw new IllegalArgumentException("interface Class expected"); return (T) Proxy.newProxyInstance(clazz.getClassLoader(), new Class[] { clazz }, (proxy, m, args) -> invokeImpl(obj, m.getName(), args)); }
From source file:com.emc.storageos.coordinator.client.service.impl.CoordinatorClientImpl.java
@Override public <T> T locateService(Class<T> clazz, String name, String version, String tag, String endpointKey) throws CoordinatorException { String key = String.format("%1$s:%2$s:%3$s:%4$s", name, version, tag, endpointKey); Object proxy = _proxyCache.get(key); if (proxy == null) { List<Service> services = locateAllServices(name, version, tag, endpointKey); if (services == null || services.isEmpty()) { throw CoordinatorException.retryables.unableToLocateService(name, version, tag, endpointKey); }/*from ww w. ja v a2 s . c om*/ Service service = services.get(0); URI endpoint = service.getEndpoint(endpointKey); if (endpoint == null) { throw CoordinatorException.retryables.unableToLocateServiceNoEndpoint(name, version, tag, endpointKey); } // check local host IPv6/IPv4 endpoint = getInetAddessLookupMap().expandURI(endpoint); if (endpoint.getScheme().equals("rmi")) { RmiInvocationHandler handler = new RmiInvocationHandler(); handler.setName(name); handler.setVersion(version); handler.setTag(tag); handler.setEndpointKey(endpointKey); handler.setEndpointInterface(clazz); handler.setCoordinator(this); proxy = Proxy.newProxyInstance(clazz.getClassLoader(), new Class[] { clazz }, handler); _proxyCache.putIfAbsent(key, proxy); } else { throw CoordinatorException.retryables.unsupportedEndPointSchema(endpoint.getScheme()); } } return clazz.cast(proxy); }
From source file:org.kuali.kfs.module.tem.document.web.struts.TravelActionBase.java
/** * * @param form//from w w w . j av a 2 s .com * @return * @throws Exception */ @SuppressWarnings("rawtypes") public <T> T newMvcDelegate(final ActionForm form) throws Exception { T retval = (T) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[] { getMvcWrapperInterface() }, new TravelMvcWrapperInvocationHandler(form)); return retval; }
From source file:com.openddal.test.BaseTestCase.java
/** * Verify the next method call on the object will throw an exception. * * @param <T> the class of the object * @param verifier the result verifier to call * @param obj the object to wrap/* ww w.j ava 2s . co m*/ * @return a proxy for the object */ @SuppressWarnings("unchecked") protected <T> T assertThrows(final ResultVerifier verifier, final T obj) { Class<?> c = obj.getClass(); InvocationHandler ih = new InvocationHandler() { private Exception called = new Exception("No method called"); @Override protected void finalize() { if (called != null) { called.printStackTrace(System.err); } } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Exception { try { called = null; Object ret = method.invoke(obj, args); verifier.verify(ret, null, method, args); return ret; } catch (InvocationTargetException e) { verifier.verify(null, e.getTargetException(), method, args); Class<?> retClass = method.getReturnType(); if (!retClass.isPrimitive()) { return null; } if (retClass == boolean.class) { return false; } else if (retClass == byte.class) { return (byte) 0; } else if (retClass == char.class) { return (char) 0; } else if (retClass == short.class) { return (short) 0; } else if (retClass == int.class) { return 0; } else if (retClass == long.class) { return 0L; } else if (retClass == float.class) { return 0F; } else if (retClass == double.class) { return 0D; } return null; } } }; if (!ProxyCodeGenerator.isGenerated(c)) { Class<?>[] interfaces = c.getInterfaces(); if (Modifier.isFinal(c.getModifiers()) || (interfaces.length > 0 && getClass() != c)) { // interface class proxies if (interfaces.length == 0) { throw new RuntimeException("Can not create a proxy for the class " + c.getSimpleName() + " because it doesn't implement any interfaces and is final"); } return (T) Proxy.newProxyInstance(c.getClassLoader(), interfaces, ih); } } try { Class<?> pc = ProxyCodeGenerator.getClassProxy(c); Constructor<?> cons = pc.getConstructor(InvocationHandler.class); return (T) cons.newInstance(ih); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:org.broadleafcommerce.core.catalog.domain.SkuImpl.java
@Override @Deprecated//from w ww .j a va 2 s. c o m public List<ProductOptionValue> getProductOptionValues() { //Changing this API to Set is ill-advised (especially in a patch release). The tendrils are widespread. Instead //we just migrate the call from the List to the internal Set representation. This is in response //to https://github.com/BroadleafCommerce/BroadleafCommerce/issues/917. return (List<ProductOptionValue>) Proxy.newProxyInstance(getClass().getClassLoader(), new Class<?>[] { List.class }, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { return MethodUtils.invokeMethod(getProductOptionValuesCollection(), method.getName(), args, method.getParameterTypes()); } }); }
From source file:com.github.spyhunter99.pdf.plugin.PdfMojo.java
/** * Generate the given Maven report only if it is not an external report and the report could be generated. * * @param mojoDescriptor not null, to catch linkage error * @param report could be null//from ww w . j av a2 s. co m * @param locale not null * @throws IOException if any * @throws MojoExecutionException if any * @see #isValidGeneratedReport(MojoDescriptor, File, String) * @since 1.1 */ private void generateMavenReport(MavenReport report, Artifact pluginArtifact, Locale locale) throws IOException, MojoExecutionException { if (report == null) { return; } String localReportName = report.getName(locale); if (!report.canGenerateReport()) { getLog().info("Skipped \"" + localReportName + "\" report."); getLog().debug("canGenerateReport() was false."); return; } if (report.isExternalReport()) { getLog().info("Skipped external \"" + localReportName + "\" report."); getLog().debug("isExternalReport() was false."); return; } for (final MavenReport generatedReport : getGeneratedMavenReports(locale)) { if (report.getName(locale).equals(generatedReport.getName(locale))) { if (getLog().isDebugEnabled()) { getLog().debug(report.getName(locale) + " was already generated."); } return; } } File outDir = new File(getGeneratedSiteDirectoryTmp(), "xdoc"); if (!locale.getLanguage().equals(defaultLocale.getLanguage())) { outDir = new File(new File(getGeneratedSiteDirectoryTmp(), locale.getLanguage()), "xdoc"); } outDir.mkdirs(); File generatedReport = new File(outDir, report.getOutputName() + ".xml"); String excludes = getDefaultExcludesWithLocales(getAvailableLocales(), getDefaultLocale()); List<String> files = FileUtils.getFileNames(siteDirectory, "*/" + report.getOutputName() + ".*", excludes, false); if (!locale.getLanguage().equals(defaultLocale.getLanguage())) { files = FileUtils.getFileNames(new File(siteDirectory, locale.getLanguage()), "*/" + report.getOutputName() + ".*", excludes, false); } if (files.size() != 0) { String displayLanguage = locale.getDisplayLanguage(Locale.ENGLISH); if (getLog().isInfoEnabled()) { getLog().info("Skipped \"" + report.getName(locale) + "\" report, file \"" + report.getOutputName() + "\" already exists for the " + displayLanguage + " version."); } return; } if (getLog().isInfoEnabled()) { getLog().info("Generating \"" + localReportName + "\" report."); } StringWriter sw = new StringWriter(); PdfSink sink = null; try { sink = new PdfSink(sw); org.codehaus.doxia.sink.Sink proxy = (org.codehaus.doxia.sink.Sink) Proxy.newProxyInstance( org.codehaus.doxia.sink.Sink.class.getClassLoader(), new Class[] { org.codehaus.doxia.sink.Sink.class }, new SinkDelegate(sink)); report.generate(proxy, locale); } catch (MavenReportException e) { throw new MojoExecutionException("MavenReportException: " + e.getMessage(), e); } finally { if (sink != null) { sink.close(); } } writeGeneratedReport(sw.toString(), generatedReport); if (isValidGeneratedReport(pluginArtifact, generatedReport, localReportName)) { getGeneratedMavenReports(locale).add(report); } }