Example usage for java.lang.reflect Proxy getInvocationHandler

List of usage examples for java.lang.reflect Proxy getInvocationHandler

Introduction

In this page you can find the example usage for java.lang.reflect Proxy getInvocationHandler.

Prototype

@CallerSensitive
public static InvocationHandler getInvocationHandler(Object proxy) throws IllegalArgumentException 

Source Link

Document

Returns the invocation handler for the specified proxy instance.

Usage

From source file:io.syndesis.runtime.Recordings.java

static public CountDownLatch resetRecorderLatch(Object object, int count) {
    RecordingInvocationHandler ih = null;
    if (object instanceof RecordingProxy) {
        ih = ((RecordingProxy) object).getInvocationHandler$$$();
    } else {/*  ww  w.  j  a v  a 2  s  .co m*/
        ih = (RecordingInvocationHandler) Proxy.getInvocationHandler(object);
    }
    CountDownLatch latch = new CountDownLatch(count);
    ih.latch = latch;
    return latch;
}

From source file:org.apache.hadoop.hbase.client.coprocessor.Batch.java

/**
 * Creates a new {@link Batch.Call} instance that invokes a method
 * with the given parameters and returns the result.
 *
 * @param method the method reference to invoke
 * @param args zero or more arguments to be passed to the method
 * @param <T> the class type of the protocol implementation being invoked
 * @param <R> the return type for the method call
 * @return a {@code Callable} instance that will invoke the given method and
 * return the results/*from  w w  w .  j  av  a  2 s . com*/
 * @see org.apache.hadoop.hbase.client.HTable#coprocessorExec(Class, byte[], byte[], org.apache.hadoop.hbase.client.coprocessor.Batch.Call, org.apache.hadoop.hbase.client.coprocessor.Batch.Callback)
 */
public static <T extends CoprocessorProtocol, R> Call<T, R> forMethod(final Method method,
        final Object... args) {
    return new Call<T, R>() {
        public R call(T instance) throws IOException {
            try {
                if (Proxy.isProxyClass(instance.getClass())) {
                    InvocationHandler invoker = Proxy.getInvocationHandler(instance);
                    return (R) invoker.invoke(instance, method, args);
                } else {
                    LOG.warn("Non proxied invocation of method '" + method.getName() + "'!");
                    return (R) method.invoke(instance, args);
                }
            } catch (IllegalAccessException iae) {
                throw new IOException("Unable to invoke method '" + method.getName() + "'", iae);
            } catch (InvocationTargetException ite) {
                throw new IOException(ite.toString(), ite);
            } catch (Throwable t) {
                throw new IOException(t.toString(), t);
            }
        }
    };
}

From source file:no.sesat.search.datamodel.BeanDataNodeInvocationHandler.java

/**
 * Creates a new instance of ProxyBeanDataObject
 *//* www .j  av  a2 s.  co m*/
protected BeanDataNodeInvocationHandler(final Class<T> cls, final DataModel datamodel,
        final BeanContext context, final PropertyInitialisor properties) throws IntrospectionException {

    super(cls, context, properties.properties);

    // find the datamodel and use its context as the absoluteContext
    if (null != datamodel) {
        final BeanDataModelInvocationHandler handler = (BeanDataModelInvocationHandler) Proxy
                .getInvocationHandler(datamodel);
        absoluteContext = (DataModelBeanContextSupport) handler.getBeanContextChild();
    } else {
        absoluteContext = (DataModelBeanContextSupport) context;
    }

    // make context to contextChild bindings
    for (PropertyDescriptor property : properties.childPropertyDescriptors) {
        for (Property p : properties.allProperties) {
            if (p.getName().equals(property.getName())) {
                if (p.getValue() instanceof MapDataObject) {
                    for (Object obj : ((MapDataObject) p.getValue()).getValues().values()) {
                        addChild(obj);
                    }
                } else {
                    addChild(p.getValue());
                }
                break;
            }
        }
    }

    // delegate our own properties
    dataObject = new BeanDataObjectInvocationHandler<T>(cls, properties.delegatedProperties);

}

From source file:org.hyperic.hq.agent.client.AbstractCommandsClient.java

/**
 * Retrieve a synchronous proxy to a remote service.
 * //from ww  w. java2 s .  c  o m
 * @param serviceInterface The service interface. It is expected that all 
 *                         service interface operations throw an 
 *                         {@link AgentRemoteException}.
 * @return The synchronous proxy.
 * @throws AgentConnectionException if there is an error creating the proxy.
 * @throws IllegalArgumentException if any of the service interface operations 
 *                                  do not throw an {@link AgentRemoteException}.
 */
protected final Object getSynchronousProxy(Class serviceInterface) throws AgentConnectionException {

    TransportUtils.assertOperationsThrowException(serviceInterface, AgentRemoteException.class);

    Object proxy;

    try {
        proxy = _factory.createSyncService(_agent, serviceInterface);
    } catch (Exception e) {
        _log.error("Error creating proxy to remote service.", e);
        throw new AgentConnectionException("Error creating proxy to remote service.", e);
    }

    if (_agent.isUnidirectional()) {
        // For unidirectional agents, if a synchronous request blocks for 
        // more than the specified timeout (see ResponseHandler#RESPONSE_WAIT_TIME) 
        // waiting for the response, then a TimeoutException is thrown. This 
        // exception will be wrapped in an HQ-specific checked exception 
        // (AgentRemoteException).

        final InvocationHandler handler = Proxy.getInvocationHandler(proxy);

        InvocationHandler timeoutExceptionHandler = new InvocationHandler() {

            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

                try {
                    return handler.invoke(proxy, method, args);
                } catch (TimeoutException e) {
                    throw new AgentRemoteException("Timeout occurred waiting on agent response.", e);
                }
            }

        };

        proxy = Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class[] { serviceInterface }, timeoutExceptionHandler);
    }

    return proxy;
}

From source file:org.apache.hadoop.yarn.factories.impl.pb.RpcClientFactoryPBImpl.java

@Override
public void stopClient(Object proxy) {
    try {/*from   ww w . j  a v a2  s  . c  o  m*/
        if (proxy instanceof Closeable) {
            ((Closeable) proxy).close();
            return;
        } else {
            InvocationHandler handler = Proxy.getInvocationHandler(proxy);
            if (handler instanceof Closeable) {
                ((Closeable) handler).close();
                return;
            }
        }
    } catch (Exception e) {
        LOG.error("Cannot call close method due to Exception. " + "Ignoring.", e);
        throw new YarnRuntimeException(e);
    }
    throw new HadoopIllegalArgumentException("Cannot close proxy - is not Closeable or "
            + "does not provide closeable invocation handler " + proxy.getClass());
}

From source file:com.hubspot.utils.circuitbreaker.CircuitBreakerWrapper.java

/**
 * Ensures that the object we're wrapping and it's base interface conform to our restrictions
 * @throws CircuitBreakerWrappingException
 *//*from w w w  .j ava  2  s  .  co m*/
private <T, W extends T> void sanityCheck(W toWrap, Class<T> interfaceToProxy, CircuitBreakerPolicy policy)
        throws CircuitBreakerWrappingException {
    if (toWrap == null) {
        throw new CircuitBreakerWrappingException("Cannot wrap a null object");
    }
    if (interfaceToProxy == null) {
        throw new CircuitBreakerWrappingException("Cannot proxy a null interface");
    }
    if (!interfaceToProxy.isInterface()) {
        throw new CircuitBreakerWrappingException("interfaceToProxy must be an interface");
    }

    try {
        if (Proxy.isProxyClass(toWrap.getClass())
                && Proxy.getInvocationHandler(toWrap) instanceof CircuitBreakerInvocationHandler) {
            throw new CircuitBreakerWrappingException("Object is already wrapped in a circuit breaker.");
        }
    } catch (IllegalArgumentException ex) {
        // "this should never happen", but if it does, we'll log our own logic error
        // before throwing the bad wrap
        getLog().error("IllegalArgumentException when trying to check for previous wrap", ex);
        throw new CircuitBreakerWrappingException("Trouble detecting whether object was already proxied");
    }
}

From source file:org.springframework.ldap.pool2.factory.DirContextPooledObjectFactoryTest.java

@Test
public void testMakeObjectReadOnly() throws Exception {
    final DirContextPooledObjectFactory objectFactory = new DirContextPooledObjectFactory();

    DirContext readOnlyContextMock = mock(DirContext.class);

    when(contextSourceMock.getReadOnlyContext()).thenReturn(readOnlyContextMock);
    objectFactory.setContextSource(contextSourceMock);

    final PooledObject createdDirContext = objectFactory.makeObject(DirContextType.READ_ONLY);
    InvocationHandler invocationHandler = Proxy.getInvocationHandler(createdDirContext.getObject());
    assertThat(readOnlyContextMock).isEqualTo(Whitebox.getInternalState(invocationHandler, "target"));
}

From source file:com.lambdaworks.redis.RedisConnectionPool.java

private PooledObjectFactory<T> createFactory(final RedisConnectionProvider<T> redisConnectionProvider) {
    return new BasePooledObjectFactory<T>() {

        @SuppressWarnings("unchecked")
        @Override// w  w w  .  j  a  v  a  2s.c  om
        public T create() throws Exception {

            T connection = redisConnectionProvider.createConnection();
            PooledConnectionInvocationHandler<T> h = new PooledConnectionInvocationHandler<>(connection,
                    RedisConnectionPool.this);

            Object proxy = Proxy.newProxyInstance(getClass().getClassLoader(),
                    new Class<?>[] { redisConnectionProvider.getComponentType() }, h);

            return (T) proxy;
        }

        @Override
        public PooledObject<T> wrap(T obj) {
            return new DefaultPooledObject<>(obj);
        }

        @Override
        public boolean validateObject(PooledObject<T> p) {
            return Connections.isOpen(p.getObject());
        }

        @Override
        @SuppressWarnings("unchecked")
        public void destroyObject(PooledObject<T> p) throws Exception {

            T object = p.getObject();
            if (Proxy.isProxyClass(object.getClass())) {
                PooledConnectionInvocationHandler<T> invocationHandler = (PooledConnectionInvocationHandler<T>) Proxy
                        .getInvocationHandler(object);

                object = invocationHandler.getConnection();
            }

            Connections.close(object);
        }
    };
}

From source file:org.apache.olingo.fit.proxy.v3.EntityUpdateTestITCase.java

@Test
public void concurrentModification() {
    Product product = container.getProduct().getByKey(-10).load();
    final String etag = ((EntityInvocationHandler) Proxy.getInvocationHandler(product)).getETag();
    assertTrue(StringUtils.isNotBlank(etag));

    final String baseConcurrency = String.valueOf(System.currentTimeMillis());
    product.setBaseConcurrency(baseConcurrency);

    container.flush();//from  w  w w.j  a  v a2  s  .c o m

    product = container.getProduct().getByKey(-10).load();
    assertEquals(baseConcurrency, product.getBaseConcurrency());
}

From source file:com.msopentech.odatajclient.proxy.EntityUpdateTestITCase.java

@Test
public void concurrentModification() {
    Product product = container.getProduct().get(-10);
    final String etag = ((EntityTypeInvocationHandler) Proxy.getInvocationHandler(product)).getETag();
    assertTrue(StringUtils.isNotBlank(etag));

    final String baseConcurrency = String.valueOf(System.currentTimeMillis());
    product.setBaseConcurrency(baseConcurrency);

    container.flush();//from   w  w  w  .  ja v  a  2s .c o m

    product = container.getProduct().get(-10);
    assertEquals(baseConcurrency, product.getBaseConcurrency());
    assertNotEquals(etag, ((EntityTypeInvocationHandler) Proxy.getInvocationHandler(product)).getETag());
}