Example usage for java.lang.reflect Proxy isProxyClass

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

Introduction

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

Prototype

public static boolean isProxyClass(Class<?> cl) 

Source Link

Document

Returns true if the given class is a proxy class.

Usage

From source file:org.amplafi.hivemind.factory.mock.TestMockBuilderFactory.java

/**
 * simple test to make sure that the {@link MockBuilderFactory} can function in a minimal
 * way as an interceptor.//from   w  w w .  java 2  s .  c  o m
 */
@Test
@SuppressWarnings("unchecked")
public void testAsInterceptorFactory() {
    Log log = LogFactory.getLog(this.getClass());
    MockBuilderFactoryImpl factory = new MockBuilderFactoryImpl(false);
    factory.setLog(log);
    ServicesSetterImpl servicesSetter = new ServicesSetterImpl();
    factory.setServicesSetter(servicesSetter);
    factory.setBuilderFactory(createMock(ServiceImplementationFactory.class));
    // TODO have way to get testing logger.
    ServicePoint servicePoint = getServicePoint();
    final Class dependentServiceClass = ServiceImplementationFactory.class;
    List parameters = createMock(List.class);
    Module invokingModule = getModule(dependentServiceClass);
    servicesSetter.setModule(invokingModule);
    servicesSetter.setLog(log);
    ServicePoint someServicePoint = createMock(ServicePoint.class);
    expect(invokingModule.getServicePoint("someService")).andReturn(someServicePoint);
    replay(invokingModule, someServicePoint);

    List factoryParametersList = new ArrayList();
    List fakeParameter = createMock(List.class);
    replay(fakeParameter);
    // add something to the list that will complain if used.
    factoryParametersList.add(fakeParameter);
    ServiceImplementationFactoryParameters factoryParameters = createMock(
            ServiceImplementationFactoryParameters.class);
    expect(factoryParameters.getInvokingModule()).andReturn(invokingModule).anyTimes();
    expect(factoryParameters.getFirstParameter()).andReturn(factoryParametersList.get(0)).anyTimes();
    expect(factoryParameters.getParameters()).andReturn(factoryParametersList).anyTimes();
    expect(factoryParameters.getServiceInterface()).andReturn(SomeService.class).anyTimes();
    expect(factoryParameters.getServiceId()).andReturn("someService");
    replay(factoryParameters);
    ServiceImplementationFactory rootService = createMock(ServiceImplementationFactory.class);
    final SomeService realCreatedService = createMock(SomeService.class);
    expect(rootService.createCoreServiceImplementation(isA(ServiceImplementationFactoryParameters.class)))
            .andAnswer(new IAnswer<Object>() {

                public Object answer() throws Throwable {
                    ServiceImplementationFactoryParameters object = (ServiceImplementationFactoryParameters) getCurrentArguments()[0];

                    // make sure being passed the proxy
                    assertTrue(Proxy.isProxyClass(object.getInvokingModule().getClass()),
                            "Did not get passed a module proxy");
                    assertTrue(object.getInvokingModule().containsService(dependentServiceClass),
                            dependentServiceClass + ": module does not have service with this interface");
                    //        TODO            List dependentService = (List) object.getInvokingModule().getService(dependentServiceClass);
                    return realCreatedService;
                }

            });
    replay(rootService, realCreatedService);

    InterceptorStack stack = new InterceptorStackImpl(log, servicePoint, rootService);

    // create the interceptor
    factory.createInterceptor(stack, invokingModule, parameters);
    ServiceImplementationFactory intercepted = (ServiceImplementationFactory) stack.peek();

    assertNotNull(intercepted);

    SomeService result = (SomeService) intercepted.createCoreServiceImplementation(factoryParameters);
    MockSwitcher switcher = (MockSwitcher) Proxy.getInvocationHandler(result);
    assertSame(switcher.getRealService(), realCreatedService);
    assertSame(switcher.getUnderlyingService(), realCreatedService);

    // now tell factory that we always want the mock.
    factory.getMockOverride().add(SomeService.class);
    assertSame(switcher.getRealService(), realCreatedService);
    assertNotSame(switcher.getUnderlyingService(), realCreatedService);
}

From source file:org.kuali.rice.ksb.messaging.BusClientFailureProxy.java

protected Object invokeInternal(Object proxyObject, Method method, Object[] params) throws Throwable {
    Set<ServiceConfiguration> servicesTried = null;

    do {//w ww. j  a v  a  2s  .  co  m
        try {
            return method.invoke(getTarget(), params);
        } catch (Throwable throwable) {
            if (isServiceRemovalException(throwable)) {
                synchronized (failoverLock) {
                    LOG.error("Exception caught accessing remote service "
                            + this.serviceConfiguration.getServiceName() + " at "
                            + this.serviceConfiguration.getEndpointUrl(), throwable);
                    if (servicesTried == null) {
                        servicesTried = new HashSet<ServiceConfiguration>();
                        servicesTried.add(serviceConfiguration);
                    }
                    Object failoverService = null;
                    List<Endpoint> endpoints = KsbApiServiceLocator.getServiceBus().getEndpoints(
                            serviceConfiguration.getServiceName(), serviceConfiguration.getApplicationId());
                    for (Endpoint endpoint : endpoints) {
                        if (!servicesTried.contains(endpoint.getServiceConfiguration())) {
                            failoverService = endpoint.getService();
                            if (Proxy.isProxyClass(failoverService.getClass()) && Proxy
                                    .getInvocationHandler(failoverService) instanceof BusClientFailureProxy) {
                                failoverService = ((BusClientFailureProxy) Proxy
                                        .getInvocationHandler(failoverService)).getTarget();
                            }
                            servicesTried.add(endpoint.getServiceConfiguration());
                            break; // KULRICE-8728: BusClientFailureProxy doesn't try all endpoint options
                        }
                    }
                    if (failoverService != null) {
                        LOG.info("Refetched replacement service for service "
                                + this.serviceConfiguration.getServiceName() + " at "
                                + this.serviceConfiguration.getEndpointUrl());
                        // as per KULRICE-4287, reassign target to the new service we just fetched, hopefully this one works better!
                        setTarget(failoverService);
                    } else {
                        LOG.error("Didn't find replacement service throwing exception");
                        throw throwable;
                    }
                }
            } else {
                throw throwable;
            }
        }
    } while (true);
}

From source file:org.jspresso.framework.model.entity.basic.BasicEntityInvocationHandler.java

/**
 * {@inheritDoc}//from  www . j av a  2s  .  c  om
 */
@Override
protected boolean computeEquals(IComponent proxy, Object another) {
    if (proxy == another) {
        return true;
    }
    Object id = straightGetProperty(proxy, IEntity.ID);
    if (id == null) {
        return false;
    }
    if (another instanceof IEntity) {
        Object otherId;
        Class<?> otherContract;

        if (Proxy.isProxyClass(another.getClass())
                && Proxy.getInvocationHandler(another) instanceof BasicEntityInvocationHandler) {
            BasicEntityInvocationHandler otherInvocationHandler = (BasicEntityInvocationHandler) Proxy
                    .getInvocationHandler(another);
            otherContract = otherInvocationHandler.getComponentContract();
            otherId = otherInvocationHandler.straightGetProperty(proxy, IEntity.ID);
        } else {
            otherContract = ((IEntity) another).getComponentContract();
            otherId = ((IEntity) another).getId();
        }
        return new EqualsBuilder().append(getComponentContract(), otherContract).append(id, otherId).isEquals();
    }
    return false;
}

From source file:com.caucho.hessian.client.HessianProxy.java

/**
 * Handles the object invocation.//from   ww  w  .  j ava2 s. co m
 * 
 * @param proxy
 *            the proxy object to invoke
 * @param method
 *            the method to call
 * @param args
 *            the arguments to the proxy object
 */
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    String mangleName;

    synchronized (_mangleMap) {
        mangleName = _mangleMap.get(method);
    }

    if (mangleName == null) {
        String methodName = method.getName();
        Class<?>[] params = method.getParameterTypes();
        // equals and hashCode are special cased
        if (methodName.equals("equals") && params.length == 1 && params[0].equals(Object.class)) {
            Object value = args[0];
            if (value == null || !Proxy.isProxyClass(value.getClass()))
                return Boolean.FALSE;

            Object proxyHandler = Proxy.getInvocationHandler(value);

            if (!(proxyHandler instanceof HessianProxy))
                return Boolean.FALSE;

            HessianProxy handler = (HessianProxy) proxyHandler;

            return new Boolean(_url.equals(handler.getURL()));
        } else if (methodName.equals("hashCode") && params.length == 0)
            return new Integer(_url.hashCode());
        else if (methodName.equals("getHessianType"))
            return proxy.getClass().getInterfaces()[0].getName();
        else if (methodName.equals("getHessianURL"))
            return _url.toString();
        else if (methodName.equals("toString") && params.length == 0)
            return "HessianProxy[" + _url + "]";

        if (!_factory.isOverloadEnabled())
            mangleName = method.getName();
        else
            mangleName = mangleName(method);

        synchronized (_mangleMap) {
            _mangleMap.put(method, mangleName);
        }
    }
    InputStream is = null;
    HessianConnection conn = null;

    try {
        if (log.isLoggable(Level.FINER))
            log.finer("Hessian[" + _url + "] calling " + mangleName);
        conn = sendRequest(mangleName, args);

        if (conn.getStatusCode() != 200) {
            throw new HessianProtocolException("http code is " + conn.getStatusCode());
        }

        is = conn.getInputStream();

        if (log.isLoggable(Level.FINEST)) {
            PrintWriter dbg = new PrintWriter(new LogWriter(log));
            HessianDebugInputStream dIs = new HessianDebugInputStream(is, dbg);

            dIs.startTop2();

            is = dIs;
        }

        AbstractHessianInput in;

        int code = is.read();

        if (code == 'H') {
            int major = is.read();
            int minor = is.read();

            in = _factory.getHessian2Input(is);

            Object value = in.readReply(method.getReturnType());

            return value;
        } else if (code == 'r') {
            int major = is.read();
            int minor = is.read();

            in = _factory.getHessianInput(is);

            in.startReplyBody();

            Object value = in.readObject(method.getReturnType());

            if (value instanceof InputStream) {
                value = new ResultInputStream(conn, is, in, (InputStream) value);
                is = null;
                conn = null;
            } else
                in.completeReply();

            return value;
        } else
            throw new HessianProtocolException("'" + (char) code + "' is an unknown code");
    } catch (HessianProtocolException e) {
        throw new HessianRuntimeException(e);
    } finally {
        try {
            if (is != null)
                is.close();
        } catch (Exception e) {
            log.log(Level.FINE, e.toString(), e);
        }

        try {
            if (conn != null)
                conn.destroy();
        } catch (Exception e) {
            log.log(Level.FINE, e.toString(), e);
        }
    }
}

From source file:com.taobao.itest.spring.context.SpringContextManager.java

private static Object getBean(String name, ApplicationContext applicationContext) {

    // return applicationContext.getBean(name);
    // modified by yufan hsf bean no need to wait config server load
    Object bean = applicationContext.getBean(name);
    if (Proxy.isProxyClass(bean.getClass())) {
        ServiceUtil.waitServiceReady(name);
        try {//hsf??sleep2s
            Thread.sleep(2000);/*from   w ww  .j a  v a2 s.  c  o  m*/
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    return bean;
}

From source file:com.thinkbiganalytics.alerts.rest.AlertsModel.java

public com.thinkbiganalytics.alerts.rest.model.Alert toModel(com.thinkbiganalytics.alerts.api.Alert alert) {
    com.thinkbiganalytics.alerts.api.Alert baseAlert = alert;
    try {//from w  w w . jav  a  2 s. c om
        if (Proxy.isProxyClass(alert.getClass())) {
            SourceAlert sourceAlert = (SourceAlert) Proxy.getInvocationHandler(alert);
            if (sourceAlert != null) {
                baseAlert = sourceAlert.getWrappedAlert();
            }
        }
    } catch (Exception e) {
        //unable to get base alert from proxy.  log the exception but continue
        log.error("Unable to get base alert from wrapped proxy for : {}, {} ", alert, e.getMessage(), e);

    }
    com.thinkbiganalytics.alerts.rest.model.Alert result = new com.thinkbiganalytics.alerts.rest.model.Alert();
    result.setId(alert.getId().toString());
    result.setActionable(alert.isActionable());
    result.setCreatedTime(alert.getCreatedTime());
    result.setLevel(toModel(alert.getLevel()));
    result.setState(toModel(alert.getState()));
    result.setType(alert.getType());
    result.setDescription(alert.getDescription());
    result.setCleared(alert.isCleared());
    result.setContent(alert.getContent() != null ? alert.getContent().toString() : null);
    result.setSubtype(alert.getSubtype());
    alert.getEvents().forEach(e -> result.getEvents().add(toModel(e)));
    if (baseAlert instanceof EntityAlert) {
        result.setEntityId(((EntityAlert) baseAlert).getEntityId() != null
                ? ((EntityAlert) baseAlert).getEntityId().toString()
                : null);
        result.setEntityType(((EntityAlert) baseAlert).getEntityType());
    }
    return result;
}

From source file:org.springframework.flex.remoting.RemotingDestinationExporter.java

/**
 * /*from ww  w. j ava2 s.c om*/
 * {@inheritDoc}
 */
@Override
protected Destination createDestination(String destinationId, MessageBroker broker) {
    Assert.notNull(this.service, "The 'service' property is required.");
    String source = null;
    if (this.service instanceof String) {
        String beanId = (String) service;
        this.service = getBeanFactory().getBean(beanId);
        this.sourceClass = AopUtils.getTargetClass(this.service);
        //As of Spring 3.0.2, AopUtils is guaranteed not to return null
        if (this.sourceClass == null || Proxy.isProxyClass(this.sourceClass)) {
            this.sourceClass = getBeanFactory().getType(beanId);
        }
    } else {
        this.sourceClass = AopUtils.getTargetClass(this.service);
    }
    if (this.sourceClass != null) {
        source = this.sourceClass.getName();
    } else {
        if (log.isWarnEnabled()) {
            log.warn("The source class being exported as RemotingDestination with id '" + destinationId
                    + "' cannot be calculated.");
        }
    }

    // Look up the remoting service
    RemotingService remotingService = (RemotingService) broker
            .getServiceByType(RemotingService.class.getName());
    Assert.notNull(remotingService, "Could not find a proper RemotingService in the Flex MessageBroker.");

    // Register and start the destination
    RemotingDestination destination = (RemotingDestination) remotingService.createDestination(destinationId);

    destination.setFactory(this);
    destination.setSource(source);

    if (log.isInfoEnabled()) {
        log.info("Created remoting destination with id '" + destinationId + "'");
    }

    return destination;
}

From source file:com.wills.clientproxy.HessianLBProxy.java

/**
 * Handles the object invocation./*  ww  w  .  j a  v  a 2 s  .  c  o m*/
 * 
 * @param proxy
 *            the proxy object to invoke
 * @param method
 *            the method to call
 * @param args
 *            the arguments to the proxy object
 */
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    String mangleName;

    HessianClusterNode hcn = _cm.getAvailableNodeByStraitegy();
    if (hcn == null) {
        throw new Exception("no available server node found!");
    }
    if (hcn == null || hcn.getNode() == null) {
        throw new Exception("no server available");
    }

    threadLocal.set(new URL(hcn.getURL() + this._type.getSimpleName()));

    try {
        lock.readLock().lock();
        mangleName = _mangleMap.get(method);
    } finally {
        lock.readLock().unlock();
    }

    if (mangleName == null) {
        String methodName = method.getName();
        Class<?>[] params = method.getParameterTypes();
        // equals and hashCode are special cased
        if (methodName.equals("equals") && params.length == 1 && params[0].equals(Object.class)) {
            Object value = args[0];
            if (value == null || !Proxy.isProxyClass(value.getClass()))
                return Boolean.FALSE;

            Object proxyHandler = Proxy.getInvocationHandler(value);

            if (!(proxyHandler instanceof HessianLBProxy))
                return Boolean.FALSE;

            HessianLBProxy handler = (HessianLBProxy) proxyHandler;

            return new Boolean(false);
        } else if (methodName.equals("hashCode") && params.length == 0)
            return new Integer(_cm.hashCode());
        else if (methodName.equals("getHessianType"))
            return proxy.getClass().getInterfaces()[0].getName();
        else if (methodName.equals("getHessianURL"))
            return threadLocal.get().toString();
        else if (methodName.equals("toString") && params.length == 0)
            return "HessianProxy[" + threadLocal.get() + "]";

        if (!_factory.isOverloadEnabled())
            mangleName = method.getName();
        else
            mangleName = mangleName(method);

        try {
            lock.writeLock().lock();
            _mangleMap.put(method, mangleName);
        } finally {
            lock.writeLock().unlock();
        }
    }
    InputStream is = null;
    HessianConnection conn = null;

    try {
        if (log.isLoggable(Level.FINER))
            log.finer("Hessian[" + threadLocal.get() + "] calling " + mangleName);
        conn = sendRequest(mangleName, args, threadLocal.get());

        if (conn.getStatusCode() != 200) {
            throw new HessianProtocolException("http code is " + conn.getStatusCode());
        }

        is = conn.getInputStream();

        if (log.isLoggable(Level.FINEST)) {
            PrintWriter dbg = new PrintWriter(new LogWriter(log));
            HessianDebugInputStream dIs = new HessianDebugInputStream(is, dbg);

            dIs.startTop2();

            is = dIs;
        }

        AbstractHessianInput in;

        int code = is.read();

        if (code == 'H') {
            int major = is.read();
            int minor = is.read();

            in = _factory.getHessian2Input(is);

            Object value = in.readReply(method.getReturnType());

            return value;
        } else if (code == 'r') {
            int major = is.read();
            int minor = is.read();

            in = _factory.getHessianInput(is);

            in.startReplyBody();

            Object value = in.readObject(method.getReturnType());

            if (value instanceof InputStream) {
                value = new ResultInputStream(conn, is, in, (InputStream) value);
                is = null;
                conn = null;
            } else
                in.completeReply();

            return value;
        } else
            throw new HessianProtocolException("'" + (char) code + "' is an unknown code");
    } catch (HessianProtocolException e) {
        throw new HessianRuntimeException(e);
    } finally {
        try {
            if (is != null)
                is.close();
        } catch (Exception e) {
            log.log(Level.FINE, e.toString(), e);
        }

        try {
            if (conn != null)
                conn.destroy();
        } catch (Exception e) {
            log.log(Level.FINE, e.toString(), e);
        }
    }
}

From source file:io.lettuce.core.support.ConnectionPoolSupportTest.java

@Test
public void softReferencePoolShouldWorkWithPlainConnections() throws Exception {

    SoftReferenceObjectPool<StatefulRedisConnection<String, String>> pool = ConnectionPoolSupport
            .createSoftReferenceObjectPool(() -> client.connect(), false);

    borrowAndReturn(pool);/*from   ww  w .jav a2s.c o  m*/

    StatefulRedisConnection<String, String> connection = pool.borrowObject();
    assertThat(Proxy.isProxyClass(connection.getClass())).isFalse();
    pool.returnObject(connection);

    connection.close();
    pool.close();
}

From source file:io.lettuce.core.support.AsyncConnectionPoolSupportTest.java

@Test
public void wrappedConnectionShouldUseWrappers() {

    AsyncPool<StatefulRedisConnection<String, String>> pool = AsyncConnectionPoolSupport
            .createBoundedObjectPool(() -> client.connectAsync(StringCodec.ASCII, uri),
                    BoundedPoolConfig.create());

    StatefulRedisConnection<String, String> connection = pool.acquire().join();
    RedisCommands<String, String> sync = connection.sync();

    assertThat(connection).isInstanceOf(StatefulRedisConnection.class)
            .isNotInstanceOf(StatefulRedisClusterConnectionImpl.class);
    assertThat(Proxy.isProxyClass(connection.getClass())).isTrue();

    assertThat(sync).isInstanceOf(RedisCommands.class);
    assertThat(connection.async()).isInstanceOf(RedisAsyncCommands.class)
            .isNotInstanceOf(RedisAsyncCommandsImpl.class);
    assertThat(connection.reactive()).isInstanceOf(RedisReactiveCommands.class)
            .isNotInstanceOf(RedisReactiveCommandsImpl.class);
    assertThat(sync.getStatefulConnection()).isInstanceOf(StatefulRedisConnection.class)
            .isNotInstanceOf(StatefulRedisConnectionImpl.class).isSameAs(connection);

    connection.close();//from  w  w w  .jav  a2  s .  co m
    pool.close();
}