Java 类com.google.common.reflect.AbstractInvocationHandler 实例源码

项目:guava-mock    文件:ForwardingMapTest.java   
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;
  }
}
项目:googles-monorepo-demo    文件:ForwardingMapTest.java   
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;
  }
}
项目:hashsdn-controller    文件:HashedWheelTimerModule.java   
@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);
            }
        }
    });
}
项目:hashsdn-controller    文件:NettyThreadgroupModule.java   
@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);
            }
        }
    });
}
项目:hashsdn-controller    文件:LegacyEntityOwnershipServiceProviderModule.java   
@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();
                }
            }
        }
    });
}
项目:hashsdn-controller    文件:ClusterSingletonServiceProviderModule.java   
@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);
                    }
                }
            });
}
项目:emodb    文件:OstrichAccessors.java   
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());
                }
            });
        }
    };
}
项目:emodb    文件:AdHocThrottleTest.java   
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;
                }
            });
}
项目:emodb    文件:HadoopDataStoreManager.java   
/**
 * 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);
                    }
                }
            });
}
项目:protostuff-compiler    文件:CompositeParseTreeListener.java   
/**
 * 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();
        }
    });

}
项目:jparsec-g    文件:Types.java   
/** 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; }
  });
}
项目:kloudmake    文件:TestVagrantRuntime.java   
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);
    }
}
项目:hashsdn-controller    文件:AutoCloseableEventExecutor.java   
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);
            }
        }
    });
}
项目:emodb    文件:PartitionAwareServiceFactory.java   
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;
}
项目:therapi-json-rpc    文件:AbstractMethodRegistryTest.java   
/**
 * 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);
        }
    }));
}
项目:guja    文件:AbstractLocalization.java   
@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);
    }
  });
}
项目:error-prone    文件:FutureReturnValueIgnoredNegativeCases.java   
private static void invocation() {
  new AbstractInvocationHandler() {
    @Override
    protected Object handleInvocation(Object o, Method method, Object[] params) {
      return immediateFuture(null);
    }
  };
}
项目:guava    文件:ForwardingMapTest.java   
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;
  }
}
项目:guava    文件:ForwardingMapTest.java   
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;
  }
}
项目:winter-data-jpa    文件:ProxyFactory.java   
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);
        }
    });
}
项目:minium    文件:RetryInteractionListenerTest.java   
@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));
}