List of usage examples for java.lang.reflect InvocationHandler InvocationHandler
InvocationHandler
From source file:grails.plugin.springsecurity.web.access.GrailsWebInvocationPrivilegeEvaluator.java
static HttpServletRequest createInstance(final String contextPath, final String httpMethod, final String requestURI) { final Map<String, Object> attributes = new HashMap<String, Object>(); return (HttpServletRequest) Proxy.newProxyInstance(HttpServletRequest.class.getClassLoader(), new Class[] { HttpServletRequest.class }, new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) { String methodName = method.getName(); if ("getContextPath".equals(methodName)) return contextPath; if ("getMethod".equals(methodName)) return httpMethod; if ("getRequestURI".equals(methodName)) return requestURI; if ("setAttribute".equals(methodName)) { attributes.put((String) args[0], args[1]); return null; }/* w w w . j a v a 2 s . c om*/ if ("getAttribute".equals(methodName)) { return attributes.get(args[0]); } if ("getProtocol".equals(methodName) || "getScheme".equals(methodName)) return "http"; if ("getServerName".equals(methodName)) return "localhost"; if ("getServerPort".equals(methodName)) return 8080; if (methodName.startsWith("is")) return false; if ("getParameterMap".equals(methodName)) return Collections.emptyMap(); if ("getAttributeNames".equals(methodName) || "getHeaderNames".equals(methodName) || "getHeaders".equals(methodName) || "getLocales".equals(methodName) || "getParameterNames".equals(methodName)) { return Collections.enumeration(Collections.emptySet()); } return null; } }); }
From source file:org.broadleafcommerce.common.util.BLCCollectionUtils.java
/** * Create a collection proxy that will perform some piece of work whenever modification methods are called on the * proxy. This includes the add, allAll, remove, removeAll, clear methods. Additionally, calling remove on an iterator * created from this collection is also covered. * * @param work the work to perform on collection modification * @param original the original collection to make change aware * @param <T> the collection type (e.g. List, Set, etc...) * @return the proxied collection//from ww w . java2s .c om */ public static <T extends Collection> T createChangeAwareCollection(final WorkOnChange work, final Collection original) { T proxy = (T) Proxy.newProxyInstance(BLCCollectionUtils.class.getClassLoader(), ClassUtils.getAllInterfacesForClass(original.getClass()), new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (method.getName().startsWith("add") || method.getName().startsWith("remove") || method.getName().startsWith("clear")) { work.doWork(original); } if (method.getName().equals("iterator")) { final Iterator itr = (Iterator) method.invoke(original, args); Iterator proxyItr = (Iterator) Proxy.newProxyInstance(getClass().getClassLoader(), ClassUtils.getAllInterfacesForClass(itr.getClass()), new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (method.getName().equals("remove")) { work.doWork(original); } return method.invoke(itr, args); } }); return proxyItr; } return method.invoke(original, args); } }); return proxy; }
From source file:org.hyperic.hq.agent.client.AbstractCommandsClient.java
/** * Retrieve a synchronous proxy to a remote service. * //from ww w . jav a2 s. co m * @param serviceInterface The service interface. It is expected that all * service interface operations throw an * {@link AgentRemoteException}. * @return The synchronous proxy. * @throws AgentConnectionException if there is an error creating the proxy. * @throws IllegalArgumentException if any of the service interface operations * do not throw an {@link AgentRemoteException}. */ protected final Object getSynchronousProxy(Class serviceInterface) throws AgentConnectionException { TransportUtils.assertOperationsThrowException(serviceInterface, AgentRemoteException.class); Object proxy; try { proxy = _factory.createSyncService(_agent, serviceInterface); } catch (Exception e) { _log.error("Error creating proxy to remote service.", e); throw new AgentConnectionException("Error creating proxy to remote service.", e); } if (_agent.isUnidirectional()) { // For unidirectional agents, if a synchronous request blocks for // more than the specified timeout (see ResponseHandler#RESPONSE_WAIT_TIME) // waiting for the response, then a TimeoutException is thrown. This // exception will be wrapped in an HQ-specific checked exception // (AgentRemoteException). final InvocationHandler handler = Proxy.getInvocationHandler(proxy); InvocationHandler timeoutExceptionHandler = new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { try { return handler.invoke(proxy, method, args); } catch (TimeoutException e) { throw new AgentRemoteException("Timeout occurred waiting on agent response.", e); } } }; proxy = Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[] { serviceInterface }, timeoutExceptionHandler); } return proxy; }
From source file:org.dimitrovchi.conf.service.ServiceParameterUtils.java
public static <P> P parameters(final String prefix, final Environment environment) { final AnnotationParameters aParameters = annotationParameters(); return (P) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), aParameters.annotations.toArray(new Class[aParameters.annotations.size()]), new InvocationHandler() { @Override//from w w w . j av a 2s. c o m public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if ("toString".equals(method.getName())) { return reflectToString(prefix, proxy); } return environment.getProperty(prefix + "." + method.getName(), (Class) method.getReturnType(), method.getDefaultValue()); } }); }
From source file:org.eclipse.wb.internal.rcp.model.rcp.ViewPartLikeInfo.java
/** * Prepares {@link IActionBars} instance, with {@link ToolBarManager} and {@link MenuManager}. *///from w w w. ja v a 2 s. com private void prepareActionBars() throws Exception { ClassLoader editorLoader = JavaInfoUtils.getClassLoader(this); Class<?> toolBarManagerClass = editorLoader.loadClass("org.eclipse.jface.action.ToolBarManager"); Class<?> menuManagerClass = editorLoader.loadClass("org.eclipse.jface.action.MenuManager"); Class<?> actionBarsClass = editorLoader.loadClass("org.eclipse.ui.IActionBars"); // create managers m_toolBarManager = toolBarManagerClass.newInstance(); m_menuManager = menuManagerClass.newInstance(); // create IActionBars m_actionBars = Proxy.newProxyInstance(editorLoader, new Class<?>[] { actionBarsClass }, new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (ReflectionUtils.getMethodSignature(method).equals("getToolBarManager()")) { return m_toolBarManager; } if (ReflectionUtils.getMethodSignature(method).equals("getMenuManager()")) { return m_menuManager; } throw new NotImplementedException(); } }); }
From source file:org.bsc.maven.plugin.confluence.PegdownTest.java
@Test public void parseTest() throws IOException { InvocationHandler handler = new InvocationHandler() { int indent = 0; protected void visitChildren(Object proxy, Node node) { for (Node child : node.getChildren()) { child.accept((Visitor) proxy); }/* www .j a v a2s. c o m*/ } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { for (int i = 0; i < indent; ++i) System.out.print('\t'); final Object n = args[0]; System.out.printf("[%s]", n); IfContext.iF(n, StrongEmphSuperNode.class, sesn).elseIf(n, ExpLinkNode.class, eln) .elseIf(n, AnchorLinkNode.class, aln).elseIf(n, VerbatimNode.class, vln) .elseIf(n, RefLinkNode.class, rln) ; System.out.println(); if (n instanceof Node) { ++indent; visitChildren(proxy, (Node) args[0]); --indent; } return null; } }; final ClassLoader cl = PegdownTest.class.getClassLoader(); final Visitor proxy = (Visitor) Proxy.newProxyInstance(cl, new Class[] { Visitor.class }, handler); final PegDownProcessor p = new PegDownProcessor(ToConfluenceSerializer.extensions()); final RootNode root = p.parseMarkdown(loadResource(FILES[1])); root.accept(proxy); }
From source file:org.pentaho.platform.web.servlet.JAXRSPluginServlet.java
@Override public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { logger.debug("servicing request for resource " + request.getPathInfo()); //$NON-NLS-1$ // Jersey's Servlet only responds to 'application.wadl', Plugin requests always have 'plugin/PLUGIN_NAME/api' as a // predicate i.e. /plugin/data-access/api/application.wadl. ////from w ww . j a v a 2 s.c om // If the request ends with application.wadl, dispatch a Proxied request that rewrites the url to plain // 'application.wadl'. This is using a JDK Dynamic Proxy which increases overhead, but these requests should be // seldom and don't need to be that performant. if (WADL_PATTERN.matcher(request.getPathInfo()).find()) { final HttpServletRequest originalRequest = request; final String appWadlUrl = request.getPathInfo() .substring(request.getPathInfo().indexOf(APPLICATION_WADL), request.getPathInfo().length()); request = (HttpServletRequest) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[] { HttpServletRequest.class }, new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (method.getName().equals("getPathInfo")) { return appWadlUrl; } else if (method.getName().equals("getRequestURL")) { String url = originalRequest.getRequestURL().toString(); return new StringBuffer(url.substring(0, url.indexOf(originalRequest.getPathInfo())) + "/" + appWadlUrl); } else if (method.getName().equals("getRequestURI")) { String uri = originalRequest.getRequestURI(); return uri.substring(0, uri.indexOf(originalRequest.getPathInfo())) + "/" + appWadlUrl; } // We don't care about the Method, delegate out to real Request object. return method.invoke(originalRequest, args); } }); if (originalRequest.getRequestURL() != null) { requestThread.set(originalRequest.getRequestURL().toString()); } else if (originalRequest.getRequestURI() != null) { requestThread.set(originalRequest.getRequestURI().toString()); } } super.service(request, response); }
From source file:com.futureplatforms.kirin.internal.attic.ProxyGenerator.java
public <T> T javascriptProxyForResponse(final JSONObject obj, Class<T> baseInterface, Class<?>... otherClasses) { Class<?>[] allClasses;/*from ww w . j a v a2 s .c om*/ if (otherClasses.length == 0) { allClasses = new Class[] { baseInterface }; } else { allClasses = new Class[otherClasses.length + 1]; allClasses[0] = baseInterface; System.arraycopy(otherClasses, 0, allClasses, 1, otherClasses.length); } InvocationHandler h = new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { String methodName = method.getName(); Class<?> returnType = method.getReturnType(); if (void.class.equals(returnType) && args.length == 1) { String propertyName = findSetter(methodName); if (propertyName != null) { handleSetter(obj, propertyName, args[0]); } } String propertyName = findGetter(methodName); if (propertyName != null) { return handleGetter(obj, returnType, propertyName); } if ("toString".equals(methodName) && String.class.equals(returnType)) { return obj.toString(); } return null; } }; Object proxy = Proxy.newProxyInstance(baseInterface.getClassLoader(), allClasses, h); return baseInterface.cast(proxy); }
From source file:com.github.steveash.typedconfig.resolver.ProxyValueResolver.java
@SuppressWarnings("unchecked") private <T> T makeProxyForResolvers(final Class<?> interfaze, final ImmutableMap<Method, ValueResolver> propertyResolvers) throws NoSuchMethodException { final ImmutableMap<Method, ValueResolver> allResolvers = addInternalResolvers(interfaze, propertyResolvers); final Method equalsMethod = Object.class.getDeclaredMethod("equals", Object.class); InvocationHandler handler = new InvocationHandler() { @Override//www . j a v a2 s. com public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable { ValueResolver valueResolver = allResolvers.get(method); if (valueResolver != null) return valueResolver.resolve(); if (equalsMethod.equals(method)) return proxyEquals(interfaze, propertyResolvers, args[0]); throw new IllegalStateException("no method is known for " + method); } }; return (T) Proxy.newProxyInstance(getClass().getClassLoader(), new Class<?>[] { interfaze, ProxiedConfiguration.class }, handler); }
From source file:com.nearinfinity.blur.thrift.AsyncClientPool.java
/** * Gets a client instance that implements the AsyncIface interface that * connects to the given connection string. * /*from ww w. j av a2 s . c o m*/ * @param <T> * @param asyncIfaceClass * the AsyncIface interface to pool. * @param connectionStr * the connection string. * @return the client instance. */ @SuppressWarnings("unchecked") public <T> T getClient(final Class<T> asyncIfaceClass, final String connectionStr) { List<Connection> connections = BlurClientManager.getConnections(connectionStr); Collections.shuffle(connections, random); //randomness ftw final Connection connection = connections.get(0); return (T) Proxy.newProxyInstance(asyncIfaceClass.getClassLoader(), new Class[] { asyncIfaceClass }, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { return execute(new AsyncCall(asyncIfaceClass, method, args, connection)); } }); }