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 List<Invocation> recordedInvocations(Object object) {
    RecordingInvocationHandler ih = null;
    if (object instanceof RecordingProxy) {
        ih = ((RecordingProxy) object).getInvocationHandler$$$();
    } else {/*from  ww  w. ja  v  a 2s  .  c  om*/
        ih = (RecordingInvocationHandler) Proxy.getInvocationHandler(object);
    }
    return ih.recordedInvocations;
}

From source file:com.gs.jrpip.client.FastServletProxyInvocationHandler.java

/**
 * Handles the object invocation.//from  w  w w .ja  v a2s. com
 *
 * @param proxy  the proxy object to invoke
 * @param method the method to call
 * @param args   the arguments to the proxy object
 */
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    String simpleMethodName = method.getName();
    Class[] params = method.getParameterTypes();

    // equals and hashCode are special cased
    if ("equals".equals(simpleMethodName) && params.length == 1 && params[0].equals(Object.class)) {
        Object value = args[0];
        if (value == null || !Proxy.isProxyClass(value.getClass())) {
            return Boolean.FALSE;
        }

        FastServletProxyInvocationHandler handler = (FastServletProxyInvocationHandler) Proxy
                .getInvocationHandler(value);

        return this.url.equals(handler.getURL()) ? Boolean.TRUE : Boolean.FALSE;
    }
    if ("hashCode".equals(simpleMethodName) && params.length == 0) {
        return Integer.valueOf(this.url.hashCode());
    }
    if ("toString".equals(simpleMethodName) && params.length == 0) {
        return "[FastServletProxyInvocationHandler " + this.url + ']';
    }

    return this.invokeRemoteMethod(proxy, method, args);
}

From source file:org.gradle.api.internal.artifacts.repositories.transport.http.HttpResourceCollection.java

private void releasePriorResources() {
    for (Resource resource : resources.values()) {
        LazyResourceInvocationHandler invocationHandler = (LazyResourceInvocationHandler) Proxy
                .getInvocationHandler(resource);
        invocationHandler.release();//from w  w w .j a  va  2s  .com
    }
}

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

public DataModel assignControlLevel(final DataModel datamodel, final ControlLevel controlLevel) {

    final BeanDataModelInvocationHandler handler = (BeanDataModelInvocationHandler) Proxy
            .getInvocationHandler(datamodel);

    handler.setControlLevel(controlLevel);

    return datamodel;
}

From source file:org.apache.olingo.ext.proxy.commons.PrimitiveCollectionInvocationHandler.java

@Override
public boolean equals(final Object obj) {
    if (obj instanceof Proxy) {
        final InvocationHandler handler = Proxy.getInvocationHandler(obj);
        if (handler instanceof PrimitiveCollectionInvocationHandler) {
            return items.equals(PrimitiveCollectionInvocationHandler.class.cast(handler).items);
        }/*w  ww  .  ja v  a  2s.co  m*/
    }

    return false;
}

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

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

    DirContext readWriteContextMock = mock(DirContext.class);

    when(contextSourceMock.getReadWriteContext()).thenReturn(readWriteContextMock);
    objectFactory.setContextSource(contextSourceMock);

    final PooledObject createdDirContext = objectFactory.makeObject(DirContextType.READ_WRITE);

    InvocationHandler invocationHandler = Proxy.getInvocationHandler(createdDirContext.getObject());
    assertThat(readWriteContextMock).isEqualTo(Whitebox.getInternalState(invocationHandler, "target"));
}

From source file:org.apache.olingo.ext.proxy.utils.CoreUtils.java

public static ClientValue getODataValue(final EdmEnabledODataClient client, final EdmTypeInfo type,
        final Object obj) {

    final ClientValue value;

    if (type.isCollection()) {
        value = client.getObjectFactory().newCollectionValue(type.getFullQualifiedName().toString());

        final EdmTypeInfo intType = new EdmTypeInfo.Builder().setEdm(client.getCachedEdm())
                .setTypeExpression(type.getFullQualifiedName().toString()).build();

        for (Object collectionItem : (Collection<?>) obj) {
            if (intType.isPrimitiveType()) {
                value.asCollection().add(getODataValue(client, intType, collectionItem).asPrimitive());
            } else if (intType.isEnumType()) {
                value.asCollection().add((getODataValue(client, intType, collectionItem)).asEnum());
            } else if (intType.isComplexType()) {
                value.asCollection().add(getODataValue(client, intType, collectionItem).asComplex());
            } else {
                throw new UnsupportedOperationException(
                        "Unsupported object type " + intType.getFullQualifiedName());
            }/*from  w  w  w.  j a v a2s. co  m*/
        }
    } else if (type.isComplexType()) {

        final Object objHandler = Proxy.getInvocationHandler(obj);
        if (objHandler instanceof ComplexInvocationHandler) {
            value = ((ComplexInvocationHandler) objHandler).getComplex();

            final Class<?> typeRef = ((ComplexInvocationHandler) objHandler).getTypeRef();

            for (Map.Entry<String, Object> changes : ((ComplexInvocationHandler) objHandler)
                    .getPropertyChanges().entrySet()) {
                try {
                    value.asComplex().add(getODataComplexProperty(client, type.getFullQualifiedName(),
                            changes.getKey(), changes.getValue()));
                } catch (Exception ignore) {
                    // ignore value
                    LOG.warn("Error attaching complex {} for field '{}.{}'", type.getFullQualifiedName(),
                            typeRef.getName(), changes.getKey(), ignore);
                }
            }

        } else {
            throw new IllegalArgumentException(objHandler.getClass().getName() + "' is not a complex value");
        }

    } else if (type.isEnumType()) {
        value = client.getObjectFactory().newEnumValue(type.getFullQualifiedName().toString(),
                ((Enum<?>) obj).name());
    } else {
        value = client.getObjectFactory().newPrimitiveValueBuilder().setType(type.getPrimitiveTypeKind())
                .setValue(obj).build();
    }

    return value;
}

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  w w .j a  v  a2s . c  o  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}/*  w ww  . j  av  a2  s  .co  m*/
 */
@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:org.jspresso.hrsample.backend.JspressoModelTest.java

/**
 * Tests computed fire property change. See bug 708.
 *
 * @throws Throwable// w w  w. j  a  v  a 2 s.com
 *     whenever an unexpected error occurs.
 */
@Test
public void testComputedFirePropertyChange() throws Throwable {
    final HibernateBackendController hbc = (HibernateBackendController) getBackendController();
    boolean wasThrowExceptionOnBadUsage = hbc.isThrowExceptionOnBadUsage();
    try {
        hbc.setThrowExceptionOnBadUsage(false);
        EnhancedDetachedCriteria employeeCriteria = EnhancedDetachedCriteria.forClass(Employee.class);
        Employee employee = hbc.findFirstByCriteria(employeeCriteria, EMergeMode.MERGE_KEEP, Employee.class);
        ControllerAwareEntityInvocationHandler handlerSpy = (ControllerAwareEntityInvocationHandler) spy(
                Proxy.getInvocationHandler(employee));
        Employee employeeMock = (Employee) Proxy.newProxyInstance(getClass().getClassLoader(),
                new Class<?>[] { Employee.class }, handlerSpy);

        Method firePropertyChangeMethod = Employee.class.getMethod("firePropertyChange", String.class,
                Object.class, Object.class);

        employeeMock.setBirthDate(new Date(0));
        verify(handlerSpy, never()).invoke(eq(employeeMock), eq(firePropertyChangeMethod),
                argThat(new PropertyMatcher(Employee.AGE)));

        PropertyChangeListener fakeListener = new PropertyChangeListener() {

            @Override
            public void propertyChange(PropertyChangeEvent evt) {
                // NO-OP
            }
        };

        employeeMock.addPropertyChangeListener(fakeListener);
        employeeMock.setBirthDate(new Date(1));
        verify(handlerSpy, times(1)).invoke(eq(employeeMock), eq(firePropertyChangeMethod),
                argThat(new PropertyMatcher(Employee.AGE)));

        employeeMock.removePropertyChangeListener(fakeListener);
        employeeMock.setBirthDate(new Date(2));
        verify(handlerSpy, times(1)).invoke(eq(employeeMock), eq(firePropertyChangeMethod),
                argThat(new PropertyMatcher(Employee.AGE)));

        employeeMock.addPropertyChangeListener(Employee.AGE, fakeListener);
        employeeMock.setBirthDate(new Date(3));
        verify(handlerSpy, times(2)).invoke(eq(employeeMock), eq(firePropertyChangeMethod),
                argThat(new PropertyMatcher(Employee.AGE)));
    } finally {
        hbc.setThrowExceptionOnBadUsage(wasThrowExceptionOnBadUsage);
    }
}