Java Code Examples for com.google.common.reflect.AbstractInvocationHandler

The following examples show how to use com.google.common.reflect.AbstractInvocationHandler. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: emodb   Source File: S3RateLimiter.java    License: Apache License 2.0 6 votes vote down vote up
public AmazonS3 rateLimit(final AmazonS3 delegate) {
    return Reflection.newProxy(AmazonS3.class, new AbstractInvocationHandler() {

        @Override
        protected Object handleInvocation(Object proxy, Method method, Object[] args) throws Throwable {
            int attempts = 0;
            _l.maybeIncreaseRateLimit();

            while (true) {
                try {
                    _l.beforeS3Method();
                    return method.invoke(delegate, args);
                } catch (InvocationTargetException ite) {
                    Throwable t = ite.getTargetException();
                    attempts += 1;

                    if (attempts == maxAttempts || !_l.checkException(t, method)) {
                        LOGGER.warn("S3 exception being raised to caller after {} attempts", attempts, t);
                        throw _l.asDeclaredThrowable(t, method);
                    }
                }
            }
        }
    });
}
 
Example 2
Source Project: emodb   Source File: OstrichAccessors.java    License: Apache License 2.0 6 votes vote down vote up
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());
                }
            });
        }
    };
}
 
Example 3
Source Project: emodb   Source File: AdHocThrottleTest.java    License: Apache License 2.0 6 votes vote down vote up
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;
                }
            });
}
 
Example 4
Source Project: emodb   Source File: HadoopDataStoreManager.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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);
                    }
                }
            });
}
 
Example 5
Source Project: emodb   Source File: StashReader.java    License: Apache License 2.0 6 votes vote down vote up
protected static AmazonS3 getS3Client(URI stashRoot, final AWSCredentialsProvider credentialsProvider,
                                      final @Nullable ClientConfiguration s3Config) {
    final String bucket = stashRoot.getHost();

    // If the bucket is a well-known Stash bucket then the region for the bucket is known in advance.
    // Otherwise return a proxy which lazily looks up the bucket on the first call.

    return StashUtil.getRegionForBucket(bucket)
            .map(region -> createS3ClientForRegion(region, credentialsProvider, s3Config))
            .orElseGet(() -> Reflection.newProxy(AmazonS3.class, new AbstractInvocationHandler() {
                private AmazonS3 _resolvedClient = null;

                @Override
                protected Object handleInvocation(Object proxy, Method method, Object[] args) throws Throwable {
                    return method.invoke(resolvedClient(), args);
                }

                private AmazonS3 resolvedClient() {
                    if (_resolvedClient == null) {
                        String endPoint = determineEndpointForBucket(bucket, credentialsProvider, s3Config, stashRoot.getPath());
                        _resolvedClient = createS3ClientForEndpoint(endPoint, credentialsProvider, s3Config);
                    }
                    return _resolvedClient;
                }
            }));
}
 
Example 6
/**
 * 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();
        }
    });

}
 
Example 7
Source Project: emodb   Source File: PartitionAwareServiceFactory.java    License: Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 8
Source Project: qpid-broker-j   Source File: ForeignMessageTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void testSendForeignMessage() throws Exception
{
    final Destination replyTo = createQueue(getTestName() + "_replyTo");
    final Queue queue = createQueue(getTestName());
    final Connection connection = getConnection();
    try
    {
        final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        final String jmsType = "TestJmsType";
        final String correlationId = "testCorrelationId";
        final ObjectMessage message = session.createObjectMessage();
        final ObjectMessage foreignMessage =
                Reflection.newProxy(ObjectMessage.class, new AbstractInvocationHandler()
                {
                    @Override
                    protected Object handleInvocation(final Object proxy, final Method method, final Object[] args)
                            throws Throwable
                    {
                        return method.invoke(message, args);
                    }
                });

        foreignMessage.setJMSCorrelationID(correlationId);
        foreignMessage.setJMSType(jmsType);
        foreignMessage.setJMSReplyTo(replyTo);
        Serializable payload = UUID.randomUUID();
        foreignMessage.setObject(payload);

        final MessageConsumer consumer = session.createConsumer(queue);
        final MessageProducer producer = session.createProducer(queue);
        producer.send(foreignMessage);

        connection.start();

        Message receivedMessage = consumer.receive(getReceiveTimeout());
        assertTrue("ObjectMessage was not received ", receivedMessage instanceof ObjectMessage);
        assertEquals("JMSCorrelationID mismatch",
                     foreignMessage.getJMSCorrelationID(),
                     receivedMessage.getJMSCorrelationID());
        assertEquals("JMSType mismatch", foreignMessage.getJMSType(), receivedMessage.getJMSType());
        assertEquals("JMSReply To mismatch", foreignMessage.getJMSReplyTo(), receivedMessage.getJMSReplyTo());
        assertEquals("JMSMessageID mismatch", foreignMessage.getJMSMessageID(), receivedMessage.getJMSMessageID());
        assertEquals("JMS Default priority should be default",
                     Message.DEFAULT_PRIORITY,
                     receivedMessage.getJMSPriority());
        assertEquals("Message payload not as expected", payload, ((ObjectMessage) receivedMessage).getObject());
    }
    finally
    {
        connection.close();
    }
}