private static Object getDefaultValue(Class<?> returnType) { Object defaultValue = ArbitraryInstances.get(returnType); if (defaultValue != null) { return defaultValue; } if ("java.util.function.Predicate".equals(returnType.getCanonicalName()) || ("java.util.function.Consumer".equals(returnType.getCanonicalName()))) { // Generally, methods that accept java.util.function.* instances // don't like to get null values. We generate them dynamically // using Proxy so that we can have Java 7 compliant code. return Reflection.newProxy(returnType, new AbstractInvocationHandler() { @Override public Object handleInvocation(Object proxy, Method method, Object[] args) { // Crude, but acceptable until we can use Java 8. Other // methods have default implementations, and it is hard to // distinguish. if ("test".equals(method.getName()) || "accept".equals(method.getName())) { return getDefaultValue(method.getReturnType()); } throw new IllegalStateException("Unexpected " + method + " invoked on " + proxy); } }); } else { return null; } }
@Override public AutoCloseable createInstance() { // The service is provided via blueprint so wait for and return it here for backwards compatibility. final WaitingServiceTracker<Timer> tracker = WaitingServiceTracker.create( Timer.class, bundleContext, "(type=global-timer)"); final Timer timer = tracker.waitForService(WaitingServiceTracker.FIVE_MINUTES); return Reflection.newProxy(AutoCloseableTimerInterface.class, new AbstractInvocationHandler() { @Override protected Object handleInvocation(final Object proxy, final Method method, final Object[] args) throws Throwable { if (method.getName().equals("close")) { tracker.close(); return null; } else { return method.invoke(timer, args); } } }); }
@Override public AutoCloseable createInstance() { // The service is provided via blueprint so wait for and return it here for backwards compatibility. String typeFilter = String.format("(type=%s)", getIdentifier().getInstanceName()); final WaitingServiceTracker<EventLoopGroup> tracker = WaitingServiceTracker.create( EventLoopGroup.class, bundleContext, typeFilter); final EventLoopGroup group = tracker.waitForService(WaitingServiceTracker.FIVE_MINUTES); return Reflection.newProxy(AutoCloseableEventLoopGroupInterface.class, new AbstractInvocationHandler() { @Override protected Object handleInvocation(final Object proxy, final Method method, final Object[] args) throws Throwable { if (method.getName().equals("close")) { tracker.close(); return null; } else { return method.invoke(group, args); } } }); }
@Override public AutoCloseable createInstance() { final WaitingServiceTracker<EntityOwnershipService> tracker = WaitingServiceTracker.create( EntityOwnershipService.class, bundleContext); final EntityOwnershipService service = tracker.waitForService(WaitingServiceTracker.FIVE_MINUTES); return Reflection.newProxy(AutoCloseableEntityOwnershipService.class, new AbstractInvocationHandler() { @Override protected Object handleInvocation(Object proxy, Method method, Object[] args) throws Throwable { if (method.getName().equals("close")) { tracker.close(); return null; } else { try { return method.invoke(service, args); } catch (InvocationTargetException e) { // https://bugs.opendaylight.org/show_bug.cgi?id=6564 // http://stackoverflow.com/a/10719613/421602 // https://amitstechblog.wordpress.com/2011/07/24/java-proxies-and-undeclaredthrowableexception/ throw e.getCause(); } } } }); }
@Override public AutoCloseable createInstance() { final WaitingServiceTracker<ClusterSingletonServiceProvider> tracker = WaitingServiceTracker .create(ClusterSingletonServiceProvider.class, bundleContext); final ClusterSingletonServiceProvider service = tracker.waitForService(WaitingServiceTracker.FIVE_MINUTES); // Create a proxy to override close to close the ServiceTracker. The actual DOMClusterSingletonServiceProvider // instance will be closed via blueprint. return Reflection.newProxy(AutoCloseableDOMClusterSingletonServiceProvider.class, new AbstractInvocationHandler() { @Override protected Object handleInvocation(final Object proxy, final Method method, final Object[] args) throws Throwable { if (method.getName().equals("close")) { tracker.close(); return null; } else { return method.invoke(service, args); } } }); }
public static <S> PartitionContextValidator<S> newPartitionContextTest(final Class<S> ifc, final Class<? extends S> impl) { final PartitionContextSupplier supplier = new AnnotationPartitionContextSupplier(ifc, impl); return new PartitionContextValidator<S>() { @Override public S expect(final PartitionContext expected) { return Reflection.newProxy(ifc, new AbstractInvocationHandler() { @Override protected Object handleInvocation(Object proxy, Method method, Object[] args) throws Throwable { PartitionContext actual = supplier.forCall(method, args); assertEquals(actual, expected, "Expected=" + expected.asMap() + ", Actual=" + actual.asMap()); return Defaults.defaultValue(method.getReturnType()); } }); } }; }
private DataStore verifyThrottled(final DataStore dataStore) { return (DataStore) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[] { DataStore.class }, new AbstractInvocationHandler() { @Override protected Object handleInvocation(Object proxy, Method method, Object[] args) throws Throwable { try { method.invoke(dataStore, args); fail(String.format("Throttled request did not generate a 503 error: %s(%s)", method.getName(), Joiner.on(",").join(args))); } catch (InvocationTargetException e) { assertTrue(e.getCause() instanceof EmoClientException); EmoClientException ce = (EmoClientException) e.getCause(); assertEquals(ce.getResponse().getStatus(), HttpStatus.SERVICE_UNAVAILABLE_503); } // This should be unreachable; the caller doesn't care what the result is if (method.getReturnType().isPrimitive()) { return Primitives.defaultValueForPrimitiveOrWrapper(method.getReturnType()); } return null; } }); }
/** * Creates a proxy which delegates all DataStore operations to the provided instance and delegates the Closeable's * close() method to the provided Runnable if necessary. */ private CloseableDataStore asCloseableDataStore(final DataStore dataStore, final Optional<Runnable> onClose) { return (CloseableDataStore) Proxy.newProxyInstance( DataStore.class.getClassLoader(), new Class[] { CloseableDataStore.class }, new AbstractInvocationHandler() { @Override protected Object handleInvocation(Object proxy, Method method, Object[] args) throws Throwable { if ("close".equals(method.getName())) { if (onClose.isPresent()) { onClose.get().run(); } return null; } else { return method.invoke(dataStore, args); } } }); }
/** * Create new composite listener for a collection of delegates. */ @SafeVarargs public static <T extends ParseTreeListener> T create(Class<T> type, T... delegates) { ImmutableList<T> listeners = ImmutableList.copyOf(delegates); return Reflection.newProxy(type, new AbstractInvocationHandler() { @Override @ParametersAreNonnullByDefault protected Object handleInvocation(Object proxy, Method method, Object[] args) throws Throwable { for (T listener : listeners) { method.invoke(listener, args); } return null; } @Override public String toString() { return MoreObjects.toStringHelper("CompositeParseTreeListener") .add("listeners", listeners) .toString(); } }); }
/** Makes a fresh type variable that's only equal to itself. */ @SuppressWarnings("unchecked") // Delegates to the <T> of class Var except getName(). static TypeVariable<Class<?>> freshTypeVariable(final String name) { // Use dynamic proxy so we only changes the behavior of getName() and equals/hashCode // Everything else delegates to a JDK native type variable. return Reflection.newProxy(TypeVariable.class, new AbstractInvocationHandler() { @Override protected Object handleInvocation(Object proxy, Method method, Object[] args) throws Throwable { if (method.getName().equals("getName")) { return name; } try { return method.invoke(PROTOTYPE, args); } catch (InvocationTargetException e) { throw e.getCause(); } } @Override public String toString() { return name; } }); }
public TestVagrantRuntime(String user, VagrantResource.Ensure after) { try { ServiceManager serviceManager = (ServiceManager) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{ServiceManager.class}, new AbstractInvocationHandler() { @Override protected Object handleInvocation(Object o, Method method, Object[] objects) throws Throwable { SshHost host = (SshHost) objects[1]; set(host, "hostProvider", new LinuxMetadataProvider()); return null; } }); Resource resource = Mockito.mock(Resource.class); vagrantResource = new VagrantResource("ubuntu-precise64", "_vagrant", VagrantResource.Ensure.UP, after, LocalHost.createStandalone(), serviceManager, Arrays.asList(new SharedFolder(true, true, "test", "_vagrant/test", "/test"))); set(vagrantResource, "resource", resource); vagrantResource.exec(); sshHost = vagrantResource.getSshHost(); set(sshHost, "hostProvider", new LinuxMetadataProvider()); sshHost.start(); if (user != null) { // TODO } } catch (KMRuntimeException e) { throw new RuntimeException(e.getMessage(), e); } }
private static AutoCloseableEventExecutor createCloseableProxy( final CloseableEventExecutorMixin closeableEventExecutorMixin) { return Reflection.newProxy(AutoCloseableEventExecutor.class, new AbstractInvocationHandler() { @Override protected Object handleInvocation(final Object proxy, final Method method, final Object[] args) throws Throwable { if (method.getName().equals("close")) { closeableEventExecutorMixin.close(); return null; } else { return method.invoke(closeableEventExecutorMixin.eventExecutor, args); } } }); }
private S createDelegate(ServiceEndPoint endPoint) { final S delegateService = _delegate.create(endPoint); S proxiedService = Reflection.newProxy(_serviceClass, new AbstractInvocationHandler() { @Override protected Object handleInvocation(Object proxy, Method method, Object[] args) throws Throwable { try { return method.invoke(delegateService, args); } catch (InvocationTargetException e) { // If the target exception is a declared exception then rethrow as-is Throwable targetException = e.getTargetException(); for (Class<?> declaredException : method.getExceptionTypes()) { // noinspection unchecked Throwables.propagateIfInstanceOf(targetException, (Class<? extends Throwable>) declaredException); } // If the exception was due to connection issues and not necessarily the target let the caller know. // It's possible the connection timed out due to a problem on the target, but from our perspective // there's no definitive way of knowing. if (targetException instanceof ClientHandlerException) { _errorMeter.mark(); throw new PartitionForwardingException("Failed to handle request at endpoint", targetException.getCause()); } throw Throwables.propagate(targetException); } } }); _proxiedToDelegateServices.put(proxiedService, delegateService); return proxiedService; }
/** * Creates a dynamic proxy implementing the given interface. * All of the proxy's one-arg methods will return their argument. * All other methods return a List containing their arguments. */ protected <T> T newEchoProxyInstance(Class<T> clazz) { return clazz.cast(newProxyInstance(getClass().getClassLoader(), new Class[]{clazz}, new AbstractInvocationHandler() { @Override @ParametersAreNonnullByDefault protected Object handleInvocation(Object proxy, Method method, Object[] args) throws Throwable { return args.length == 0 ? null : args.length == 1 ? args[0] : Arrays.asList(args); } })); }
@Override public <T extends Localizable> T getLocalizable(Class<T> clazz) { return Reflection.newProxy(clazz, new AbstractInvocationHandler() { @Override protected String handleInvocation(Object proxy, Method method, Object[] args) throws Throwable { return getMessage(method.getName(), method.getName(), args); } }); }
private static void invocation() { new AbstractInvocationHandler() { @Override protected Object handleInvocation(Object o, Method method, Object[] params) { return immediateFuture(null); } }; }
private static Object getDefaultValue(Class<?> returnType) { Object defaultValue = ArbitraryInstances.get(returnType); if (defaultValue != null) { return defaultValue; } if ("java.util.function.Predicate".equals(returnType.getCanonicalName()) || ("java.util.function.Consumer".equals(returnType.getCanonicalName()))) { // Generally, methods that accept java.util.function.* instances // don't like to get null values. We generate them dynamically // using Proxy so that we can have Java 7 compliant code. return Reflection.newProxy( returnType, new AbstractInvocationHandler() { @Override public Object handleInvocation(Object proxy, Method method, Object[] args) { // Crude, but acceptable until we can use Java 8. Other // methods have default implementations, and it is hard to // distinguish. if ("test".equals(method.getName()) || "accept".equals(method.getName())) { return getDefaultValue(method.getReturnType()); } throw new IllegalStateException("Unexpected " + method + " invoked on " + proxy); } }); } else { return null; } }
public static <T> T newProxy(Object target, Class<T> targetInterface) { return Reflection.newProxy(targetInterface, new AbstractInvocationHandler() { @Override protected Object handleInvocation(Object proxy, Method method, Object[] args) throws Throwable { return method.invoke(target, args); } }); }
@Test public void testOnTimeout() { final BasicElements<?> basicElements = mock(BasicElements.class); final Configuration configuration = new DefaultConfiguration(); MixinClass<DefaultWebElements> webElemsClass = MixinClasses.builder(DefaultWebElements.class).addInterfaces(Mixin.class).build(); DefaultWebElements loading = webElemsClass.newInstance(new AbstractMixinInitializer() { @Override protected void initialize() { implement(AsIs.class, Mixin.class).with(new AsIsImpl()); implement(HasConfiguration.class).with(new HasConfiguration.Impl(configuration)); implement(BasicElements.class).with(basicElements); implement(DefaultWebElements.class).with(new AbstractInvocationHandler() { @Override protected Object handleInvocation(Object arg0, Method arg1, Object[] arg2) throws Throwable { return null; } }); } }); Interaction interaction = mock(Interaction.class); InteractionListener retryOnTimeout = WebInteractionListeners .onTimeout() .when(loading) .waitForUnexistence(loading) .withWaitingPreset("very-slow") .thenRetry(); when(basicElements.size()).then(new Answer<Integer>() { int next = 1; @Override public Integer answer(InvocationOnMock invocation) throws Throwable { return next--; } }); AfterFailInteractionEvent event = new AfterFailInteractionEvent(loading, interaction, new TimeoutException()); retryOnTimeout.onEvent(event); verify(basicElements, times(2)).size(); Assert.assertThat(event.isRetry(), is(true)); }