/** {@inheritDoc} */ @Override public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable { unwrapArgs(method.getParameterTypes(), args); if (!mixinHandlers.isEmpty()) { MethodSignature methodSignature = MethodSignature.forMethod(method); if (mixinHandlers.containsKey(methodSignature)) { return mixinHandlers.get(methodSignature).invoke(proxy, method, args); } } final InvocationHandler invocationHandler = handlers.get(MethodSignature.forMethod(method)); if (invocationHandler != null) { try { return invocationHandler.invoke(proxy, method, args); } catch (XPathExpressionException e) { throw new XBPathException(e, method, "??"); } } throw new IllegalArgumentException( "I don't known how to invoke method " + method + ". Did you forget to add a XB*-annotation or to register a mixin?"); }
/** * Marks a borrowed connection as no longer usable. * * @param connection The connection (proxy) to be marked. */ public static void renderUnuseable(Connection connection) { if (connection != null && Proxy.isProxyClass(connection.getClass())) { InvocationHandler handler = Proxy.getInvocationHandler(connection); if (BorrowedConnectionProxy.class.isAssignableFrom(handler.getClass())) { ((BorrowedConnectionProxy) handler).useable = false; } } }
public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) { InvocationHandler invocationHandler = Proxy.getInvocationHandler(source); addInterfacesToXml(source, writer); writer.startNode("handler"); writer.addAttribute("class", mapper.serializedClass(invocationHandler.getClass())); context.convertAnother(invocationHandler); writer.endNode(); }
private static String getProxyUri(Object proxy) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { InvocationHandler handler = Proxy.getInvocationHandler(proxy); Field f = handler.getClass().getDeclaredField("url"); f.setAccessible(true); String url = (String) f.get(handler); return url; }
/** Given a Hibernate Session, retrieve the "real" session if it's a proxy. */ public static Session getRealSession(Session session) { Session realSession = session; if (Proxy.isProxyClass(session.getClass())) { InvocationHandler handler = Proxy.getInvocationHandler(session); try { Field fld = handler.getClass().getDeclaredField("realSession"); fld.setAccessible(true); realSession = (Session) fld.get(handler); } catch (Exception ex) { throw new RuntimeException( "Error while getting the real Hibernate session out of proxy session", ex); } } return realSession; }
public static Object getDepackageObject(Object object) { if (object == null) { return null; } if (!(object instanceof Proxy)) { return object; } InvocationHandler h = Proxy.getInvocationHandler((Proxy) object); ProxyDepackage depackage; synchronized (map) { depackage = map.get(h.getClass().getName()); } if (depackage == null) { throw new RuntimeException("Cannot proxy depackager for `" + h.getClass().getName() + "`."); } return depackage.depackage((Proxy) object); }
@SuppressWarnings({"ThrowableInstanceNeverThrown"}) @Test(expected = IllegalStateException.class) public void shouldRethrowAllOtherExceptions() throws Throwable { EasyMock.expect(mockFilterChain.filter(mockMethodParam)); EasyMock.expectLastCall().andThrow(new IllegalStateException()); mockControl.replay(); handler.invoke(null, method, NO_PARAM); }
protected boolean getBooleanParam( final InvocationHandler invocationHandler, final Method method, final boolean defaultValue) throws Throwable { Boolean value = (Boolean) invocationHandler.invoke(configuration, method, null); if (value == null) { value = defaultValue; } logger.debug("Boolean param: {}: {}", method.getName(), value); return value; }
protected String getStringParam( final InvocationHandler invocationHandler, final Method method, final String defaultValue) throws Throwable { String value = (String) invocationHandler.invoke(configuration, method, null); if (value == null) { value = defaultValue; } logger.debug("String param: {}: {}", method.getName(), value); return value; }
/** {@inheritDoc} */ @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { try { return delegate.invoke(proxy, method, args); } catch (final InvocationTargetException e) { if (e.getTargetException() != null) { throw e.getTargetException(); } throw e; } }
public Object intercept( Object object, java.lang.reflect.Method method, Object[] arguments, MethodProxy proxy) throws Throwable { Object res = null; { res = invocationHandler.invoke(object, method, arguments); } return res; }
@Override public Object read(final Kryo kryo, final Input input, final Class<Object> type) { final InvocationHandler invocationHandler = (InvocationHandler) kryo.readClassAndObject(input); final Class<?>[] interfaces = kryo.readObject(input, Class[].class); final ClassLoader classLoader = kryo.getClass().getClassLoader(); // TODO: can we do this? try { return Proxy.newProxyInstance(classLoader, interfaces, invocationHandler); } catch (final RuntimeException e) { System.err.println( getClass().getName() + ".read:\n" + "Could not create proxy using classLoader " + classLoader + "," + " have invocationhandler.classloader: " + invocationHandler.getClass().getClassLoader() + " have contextclassloader: " + Thread.currentThread().getContextClassLoader()); throw e; } }
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { // We conveniently mock abstract methods be default if (Modifier.isAbstract(method.getModifiers())) { return handler.invoke(obj, method, args); } // Here I need to check if the fillInStackTrace was called by EasyMock inner code // If it's the case, just ignore the call. We ignore it for two reasons // 1- In Java 7, the fillInStackTrace won't work because, since no constructor was called, the // stackTrace attribute is null // 2- There might be some unexpected side effect in the original fillInStackTrace. So it seems // more logical to ignore the call if (obj instanceof Throwable && method.getName().equals("fillInStackTrace")) { if (isCallerMockInvocationHandlerInvoke(new Throwable())) { return obj; } } // Bridges should delegate to their bridged method. It should be done before // checking for mocked methods because only unbridged method are mocked // It also make sure the method passed to the handler is not the bridge. Normally it // shouldn't be necessary because bridges are never mocked so are never in the mockedMethods // map. So the normal case is that is will call invokeSuper which will call the interceptor // for // the bridged method. The problem is that it doesn't happen. It looks like a cglib bug. For // package scoped bridges (see GenericTest), the interceptor is not called for the bridged // method. Not normal from my point of view. if (method.isBridge()) { method = BridgeMethodResolver.findBridgedMethod(method); } if (mockedMethods != null && !mockedMethods.contains(method)) { return proxy.invokeSuper(obj, args); } return handler.invoke(obj, method, args); }
private static void checkStub(Remote stub, Class<? extends Remote> stubClass) { // Check remote stub is from the expected class. // if (stub.getClass() != stubClass) { if (!Proxy.isProxyClass(stub.getClass())) { throw new SecurityException("Expecting a " + stubClass.getName() + " stub!"); } else { InvocationHandler handler = Proxy.getInvocationHandler(stub); if (handler.getClass() != RemoteObjectInvocationHandler.class) { throw new SecurityException( "Expecting a dynamic proxy instance with a " + RemoteObjectInvocationHandler.class.getName() + " invocation handler!"); } else { stub = (Remote) handler; } } } // Check RemoteRef in stub is from the expected class // "sun.rmi.server.UnicastRef2". // RemoteRef ref = ((RemoteObject) stub).getRef(); if (ref.getClass() != UnicastRef2.class) { throw new SecurityException( "Expecting a " + UnicastRef2.class.getName() + " remote reference in stub!"); } // Check RMIClientSocketFactory in stub is from the expected class // "javax.rmi.ssl.SslRMIClientSocketFactory". // LiveRef liveRef = ((UnicastRef2) ref).getLiveRef(); RMIClientSocketFactory csf = liveRef.getClientSocketFactory(); if (csf == null || csf.getClass() != SslRMIClientSocketFactory.class) { throw new SecurityException( "Expecting a " + SslRMIClientSocketFactory.class.getName() + " RMI client socket factory in stub!"); } }
@SuppressWarnings({"ThrowableInstanceNeverThrown"}) @Test public void shouldThrowAnImplementationNotFoundExceptionIfAClassCantBeLocated() throws Throwable { EasyMock.expect(mockFilterChain.filter(mockMethodParam)); EasyMock.expectLastCall().andThrow(new MatchNotFoundException()); mockControl.replay(); try { handler.invoke(null, method, NO_PARAM); fail(); } catch (ImplementationNotFoundException e) { mockControl.verify(); assertThat(e.getMessage(), equalTo("Could not find implementation for class [B")); } }
/** * Build the action context from the Play {@link Context} and the {@link RequiresAuthentication} * annotation. * * @param ctx the Play context. * @param configuration the configuration. * @return */ public static ActionContext build(Context ctx, Object configuration) { JavaWebContext context = new JavaWebContext(ctx.request(), ctx.response(), ctx.session()); String clientName = null; String targetUrl = ""; Boolean isAjax = false; Boolean stateless = false; String requireAnyRole = ""; String requireAllRoles = ""; if (configuration != null) { try { final InvocationHandler invocationHandler = Proxy.getInvocationHandler(configuration); clientName = (String) invocationHandler.invoke(configuration, clientNameMethod, null); targetUrl = (String) invocationHandler.invoke(configuration, targetUrlMethod, null); logger.debug("targetUrl : {}", targetUrl); isAjax = (Boolean) invocationHandler.invoke(configuration, isAjaxMethod, null); logger.debug("isAjax : {}", isAjax); stateless = (Boolean) invocationHandler.invoke(configuration, statelessMethod, null); logger.debug("stateless : {}", stateless); requireAnyRole = (String) invocationHandler.invoke(configuration, requireAnyRoleMethod, null); logger.debug("requireAnyRole : {}", requireAnyRole); requireAllRoles = (String) invocationHandler.invoke(configuration, requireAllRolesMethod, null); logger.debug("requireAllRoles : {}", requireAllRoles); } catch (Throwable e) { logger.error("Error during configuration retrieval", e); throw new TechnicalException(e); } } clientName = (clientName != null) ? clientName : context.getRequestParameter(Config.getClients().getClientNameParameter()); logger.debug("clientName : {}", clientName); String sessionId = (stateless) ? null : StorageHelper.getOrCreationSessionId(ctx.session()); return new ActionContext( ctx, ctx.request(), sessionId, context, clientName, targetUrl, isAjax, stateless, requireAnyRole, requireAllRoles); }
@Override public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable { return DEFAULT_METHOD_INVOCATION_HANDLER.invoke(proxy, defaultMethod, args); }
/** * Convenience method to generate a single-interface proxy using the handler's classloader * * @param <T> The type of object to proxy * @param type The type of object to proxy * @param handler The handler that intercepts/overrides method calls. * @return proxied object */ public <T> T newProxyInstance(Class<T> type, InvocationHandler handler) { return type.cast( Proxy.newProxyInstance( handler.getClass().getClassLoader(), new Class<?>[] {type}, handler)); }