List of usage examples for java.lang.reflect InvocationHandler InvocationHandler
InvocationHandler
From source file:org.apache.brooklyn.rest.client.BrooklynApi.java
@SuppressWarnings("unchecked") private <T> T proxy(Class<T> clazz) { final T result0 = ProxyFactory.create(clazz, target, clientExecutor); return (T) Proxy.newProxyInstance(clazz.getClassLoader(), new Class<?>[] { clazz }, new InvocationHandler() { @Override/* www . j av a 2 s. c o m*/ public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { try { Object result1 = method.invoke(result0, args); Class<?> type = String.class; if (result1 instanceof Response) { Response resp = (Response) result1; if (isStatusCodeHealthy(resp.getStatus()) && method.isAnnotationPresent(ApiOperation.class)) { type = getClassFromMethodAnnotationOrDefault(method, type); } // wrap the original response so it self-closes result1 = BuiltResponsePreservingError.copyResponseAndClose(resp, type); } return result1; } catch (Throwable e) { if (e instanceof InvocationTargetException) { // throw the original exception e = ((InvocationTargetException) e).getTargetException(); } throw Exceptions.propagate(e); } } private boolean isStatusCodeHealthy(int code) { return (code >= 200 && code <= 299); } private Class<?> getClassFromMethodAnnotationOrDefault(Method method, Class<?> def) { Class<?> type; try { type = method.getAnnotation(ApiOperation.class).response(); } catch (Exception e) { type = def; LOG.debug("Unable to get class from annotation: {}. Defaulting to {}", e.getMessage(), def.getName()); Exceptions.propagateIfFatal(e); } return type; } }); }
From source file:com.easyjf.web.core.FrameworkEngine.java
/** * IWebAction?/*from www. ja v a2s .c om*/ * @param methodName ?? * @param bean ?Bean * @return */ public static IWebAction createProxyAction(final Module module, final Object bean) { String methodName = module.getMethod(); int argNum = 0; Method method = null; try { method = bean.getClass().getMethod(methodName); } catch (NoSuchMethodException nme) { try { method = bean.getClass().getMethod(methodName, WebForm.class); argNum = 1; } catch (NoSuchMethodException e) { try { method = bean.getClass().getMethod(methodName, WebForm.class, Module.class); argNum = 2; } catch (NoSuchMethodException e2) { e.printStackTrace(); } } } final Method beanMethod = method; final int num = argNum; if (method != null) { return (IWebAction) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[] { IWebAction.class }, new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (method.getName().equals("execute")) { Object[] arg; if (num == 0) arg = new Object[] {}; else if (num == 1) arg = new Object[] { args[0] }; else arg = args; Object result = beanMethod.invoke(bean, arg); if (result != null) { if (result instanceof Page) return result; else return module.findPage(result.toString()); } return null; } return method.invoke(bean, args); } }); } return null; }
From source file:org.eclipse.wb.internal.rcp.model.rcp.ActionBarAdvisorInfo.java
/** * Prepares {@link IActionBarConfigurer} implementation in {@link #m_IActionBarConfigurer}. *//* www. java 2 s. com*/ private void prepare_IActionBarConfigurer() throws ClassNotFoundException { ClassLoader editorLoader = JavaInfoUtils.getClassLoader(this); Class<?> class_IActionBarConfigurer = editorLoader .loadClass("org.eclipse.ui.application.IActionBarConfigurer"); Class<?> class_IWorkbenchWindowConfigurer = editorLoader .loadClass("org.eclipse.ui.application.IWorkbenchWindowConfigurer"); m_IActionBarConfigurer = Proxy.newProxyInstance(editorLoader, new Class<?>[] { class_IActionBarConfigurer }, new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { String methodSignature = ReflectionUtils.getMethodSignature(method); if (methodSignature.equals("getWindowConfigurer()")) { return m_IWorkbenchWindowConfigurer; } if (methodSignature.equals("getCoolBarManager()")) { return m_coolBarManager; } if (methodSignature.equals("getMenuManager()")) { return m_menuManager; } throw new NotImplementedException(methodSignature); } }); m_IWorkbenchWindowConfigurer = Proxy.newProxyInstance(editorLoader, new Class<?>[] { class_IWorkbenchWindowConfigurer }, new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { String methodSignature = ReflectionUtils.getMethodSignature(method); if (methodSignature.equals("getWindow()")) { return m_IWorkbenchWindow; } throw new NotImplementedException(methodSignature); } }); m_IWorkbenchWindow = DesignerPlugin.getActiveWorkbenchWindow(); }
From source file:com.streamsets.pipeline.stage.processor.fieldhasher.TestFieldHasherProcessor.java
private Set<String> registerCallbackForValidFields() { final Set<String> validFieldsFromTheProcessor = new HashSet<String>(); PowerMockito.replace(MemberMatcher.method(FieldHasherProcessor.class, "validateAndExtractFieldsToHash")) .with(new InvocationHandler() { @Override//from ww w. ja v a 2s. c o m public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Object returnVal = method.invoke(proxy, args); validFieldsFromTheProcessor.addAll((HashSet<String>) returnVal); return returnVal; } }); return validFieldsFromTheProcessor; }
From source file:org.kchine.r.server.http.RHttpProxy.java
public static Object getDynamicProxy(final String url, final String sessionId, final String servantName, Class<?>[] c, final HttpClient httpClient) { Object proxy = Proxy.newProxyInstance(RHttpProxy.class.getClassLoader(), c, new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { return RHttpProxy.invoke(url, sessionId, servantName, method.getName(), method.getParameterTypes(), args, httpClient);/* w w w .j a v a 2 s . co m*/ } }); return proxy; }
From source file:com.zavakid.mushroom.impl.MetricsSystemImpl.java
@Override public synchronized void register(final Callback callback) { callbacks.add((Callback) Proxy.newProxyInstance(callback.getClass().getClassLoader(), new Class<?>[] { Callback.class }, new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { try { return method.invoke(callback, args); } catch (Exception e) { LOG.warn("Caught exception in callback " + method.getName(), e); }// w w w . jav a2s . c o m return null; } })); }
From source file:org.nebularis.defproxy.AnnotationDrivenProxyFactoryTestCase.java
private <T> T wrap(final Object delegateObject, final Class<T> clazz) { InvocationHandler handler = new InvocationHandler() { private final Object delegate = delegateObject; @Override/* w w w.j a v a 2 s . c om*/ public Object invoke(Object o, Method method, Object[] objects) throws Throwable { // handlerConfiguration.getMethodInvoker(method).handleInvocation(delegate, objects); return ((MyDelegate) delegate).getName(); } }; final Class proxyClass = Proxy.getProxyClass(clazz.getClassLoader(), new Class[] { clazz }); final Object obj = createProxyInstance(handler, proxyClass); final T casted = (T) obj; return casted; }
From source file:me.piebridge.android.preference.PreferenceFragment.java
@Override public void onStart() { super.onStart(); // FIXME: mPreferenceManager.setOnPreferenceTreeClickListener(this); try {/*from ww w. jav a 2 s .co m*/ Class<?> clazz = Class.forName("android.preference.PreferenceManager$OnPreferenceTreeClickListener"); Object proxy = Proxy.newProxyInstance(clazz.getClassLoader(), new Class[] { clazz }, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (method.getName().equals("onPreferenceTreeClick")) { return onPreferenceTreeClick((PreferenceScreen) args[0], (Preference) args[1]); } return null; } }); callVoidMethod(mPreferenceManager, "setOnPreferenceTreeClickListener", new Class[] { clazz }, new Object[] { proxy }); } catch (ClassNotFoundException e) { e.printStackTrace(); } }
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// w w w . j a va 2 s . 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:org.apache.nifi.controller.service.StandardControllerServiceProvider.java
private ControllerServiceNode createGhostControllerService(final String type, final String id) { final InvocationHandler invocationHandler = new InvocationHandler() { @Override/*from w ww .j a va 2 s . com*/ public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable { final String methodName = method.getName(); if ("validate".equals(methodName)) { final ValidationResult result = new ValidationResult.Builder().input("Any Property") .subject("Missing Controller Service").valid(false) .explanation( "Controller Service could not be created because the Controller Service Type (" + type + ") could not be found") .build(); return Collections.singleton(result); } else if ("getPropertyDescriptor".equals(methodName)) { final String propertyName = (String) args[0]; return new PropertyDescriptor.Builder().name(propertyName).description(propertyName) .sensitive(true).required(true).build(); } else if ("getPropertyDescriptors".equals(methodName)) { return Collections.emptyList(); } else if ("onPropertyModified".equals(methodName)) { return null; } else if ("getIdentifier".equals(methodName)) { return id; } else if ("toString".equals(methodName)) { return "GhostControllerService[id=" + id + ", type=" + type + "]"; } else if ("hashCode".equals(methodName)) { return 91 * type.hashCode() + 41 * id.hashCode(); } else if ("equals".equals(methodName)) { return proxy == args[0]; } else { throw new IllegalStateException( "Controller Service could not be created because the Controller Service Type (" + type + ") could not be found"); } } }; final ControllerService proxiedService = (ControllerService) Proxy.newProxyInstance( getClass().getClassLoader(), new Class[] { ControllerService.class }, invocationHandler); final String simpleClassName = type.contains(".") ? StringUtils.substringAfterLast(type, ".") : type; final String componentType = "(Missing) " + simpleClassName; final ComponentLog logger = new SimpleProcessLogger(id, proxiedService); final ControllerServiceNode serviceNode = new StandardControllerServiceNode(proxiedService, proxiedService, id, new StandardValidationContextFactory(this, variableRegistry), this, componentType, type, variableRegistry, logger); return serviceNode; }