Example usage for java.lang.reflect Proxy newProxyInstance

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

Introduction

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

Prototype

private static Object newProxyInstance(Class<?> caller, 
            Constructor<?> cons, InvocationHandler h) 

Source Link

Usage

From source file:org.jspresso.hrsample.backend.JspressoModelTest.java

/**
 * Tests computed fire property change. See bug 708.
 *
 * @throws Throwable//from w  w  w. j a va 2s  .c om
 *     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);
    }
}

From source file:com.msopentech.odatajclient.proxy.api.EntityContainerFactory.java

/**
 * Return an initialized concrete implementation of the passed EntityContainer interface.
 *
 * @param <T> interface annotated as EntityContainer
 * @param reference class object of the EntityContainer annotated interface
 * @return an initialized concrete implementation of the passed reference
 * @throws IllegalStateException if <tt>serviceRoot</tt> was not set
 * @throws IllegalArgumentException if the passed reference is not an interface annotated as EntityContainer
 * @see com.msopentech.odatajclient.proxy.api.annotations.EntityContainer
 *///from w  w w.ja v a 2 s. com
@SuppressWarnings("unchecked")
public <T> T getEntityContainer(final Class<T> reference)
        throws IllegalStateException, IllegalArgumentException {
    if (StringUtils.isBlank(serviceRoot)) {
        throw new IllegalStateException("serviceRoot was not set");
    }

    if (!ENTITY_CONTAINERS.containsKey(reference)) {
        final Object entityContainer = Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class<?>[] { reference },
                EntityContainerInvocationHandler.getInstance(client, reference, this));
        ENTITY_CONTAINERS.put(reference, entityContainer);
    }
    return (T) ENTITY_CONTAINERS.get(reference);
}

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

private HttpResource createLazyResource(String source, GetMethod method, List<CachedArtifact> artifacts) {
    LazyResourceInvocationHandler invocationHandler = new LazyResourceInvocationHandler(source, method,
            artifacts);/*from   w  w  w .j a  v a 2 s .co  m*/
    return HttpResource.class.cast(Proxy.newProxyInstance(getClass().getClassLoader(),
            new Class<?>[] { HttpResource.class }, invocationHandler));
}

From source file:org.alfresco.repo.service.StoreRedirectorProxyFactory.java

@SuppressWarnings("unchecked")
public void afterPropertiesSet() throws ServiceException {
    ParameterCheck.mandatory("Proxy Interface", proxyInterface);
    ParameterCheck.mandatory("Default Binding", defaultBinding);

    // Setup the redirector proxy
    this.redirectorProxy = (I) Proxy.newProxyInstance(proxyInterface.getClassLoader(),
            new Class[] { proxyInterface, StoreRedirector.class }, new RedirectorInvocationHandler());
}

From source file:com.github.steveash.typedconfig.resolver.ProxyValueResolver.java

@SuppressWarnings("unchecked")
private <T> T makeProxyForResolvers(final Class<?> interfaze,
        final ImmutableMap<Method, ValueResolver> propertyResolvers) throws NoSuchMethodException {

    final ImmutableMap<Method, ValueResolver> allResolvers = addInternalResolvers(interfaze, propertyResolvers);
    final Method equalsMethod = Object.class.getDeclaredMethod("equals", Object.class);

    InvocationHandler handler = new InvocationHandler() {

        @Override/*  w  w  w.j  av  a  2 s .co  m*/
        public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {

            ValueResolver valueResolver = allResolvers.get(method);
            if (valueResolver != null)
                return valueResolver.resolve();
            if (equalsMethod.equals(method))
                return proxyEquals(interfaze, propertyResolvers, args[0]);

            throw new IllegalStateException("no method is known for " + method);
        }
    };
    return (T) Proxy.newProxyInstance(getClass().getClassLoader(),
            new Class<?>[] { interfaze, ProxiedConfiguration.class }, handler);
}

From source file:com.mirth.connect.connectors.jms.xa.ConnectionFactoryWrapper.java

public TopicConnection createTopicConnection(String username, String password) throws JMSException {
    XATopicConnection xatc = ((XATopicConnectionFactory) factory).createXATopicConnection(username, password);
    TopicConnection proxy = (TopicConnection) Proxy.newProxyInstance(Connection.class.getClassLoader(),
            new Class[] { TopicConnection.class }, new ConnectionInvocationHandler(xatc));
    return proxy;
}

From source file:com.seer.datacruncher.eventtrigger.DynamicClassLoader.java

public Object newProxyInstance(Class interfaceClass, String implClassName) throws RuntimeException {
    JVInvocationHandler handler = new JVInvocationHandler(implClassName);
    return Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class[] { interfaceClass }, handler);
}

From source file:org.apache.hadoop.hbase.ipc.SecureRpcEngine.java

/**
 * Construct a client-side proxy object that implements the named protocol,
 * talking to a server at the named address.
 *
 * @param protocol interface/*w  w w.j a  v  a2  s. c  o m*/
 * @param clientVersion version we are expecting
 * @param addr remote address
 * @param conf configuration
 * @return proxy
 * @throws java.io.IOException e
 */
@Override
public <T extends VersionedProtocol> T getProxy(Class<T> protocol, long clientVersion, InetSocketAddress addr,
        Configuration conf, int rpcTimeout) throws IOException {
    if (this.client == null) {
        throw new IOException("Client must be initialized by calling setConf(Configuration)");
    }

    T proxy = (T) Proxy.newProxyInstance(protocol.getClassLoader(), new Class[] { protocol },
            new Invoker(this.client, protocol, addr, User.getCurrent(), HBaseRPC.getRpcTimeout(rpcTimeout)));
    /*
     * TODO: checking protocol version only needs to be done once when we setup a new
     * SecureClient.Connection.  Doing it every time we retrieve a proxy instance is resulting
     * in unnecessary RPC traffic.
     */
    long serverVersion = proxy.getProtocolVersion(protocol.getName(), clientVersion);
    if (serverVersion != clientVersion) {
        throw new HBaseRPC.VersionMismatch(protocol.getName(), clientVersion, serverVersion);
    }
    return proxy;
}

From source file:org.apache.hadoop.ipc.ProtobufRpcEngine.java

@Override
public ProtocolProxy<ProtocolMetaInfoPB> getProtocolMetaInfoProxy(ConnectionId connId, Configuration conf,
        SocketFactory factory) throws IOException {
    Class<ProtocolMetaInfoPB> protocol = ProtocolMetaInfoPB.class;
    return new ProtocolProxy<ProtocolMetaInfoPB>(protocol,
            (ProtocolMetaInfoPB) Proxy.newProxyInstance(protocol.getClassLoader(), new Class[] { protocol },
                    new Invoker(protocol, connId, conf, factory)),
            false);/*from   w  w  w  . j  a  va  2  s  .  c  om*/
}

From source file:com.facebook.GraphObjectWrapper.java

private static Map<String, Object> createGraphObjectProxyForMap(JSONObject state) {
    Class<?>[] interfaces = new Class[] { Map.class };
    GraphObjectProxy graphObjectProxy = new GraphObjectProxy(state, Map.class);

    @SuppressWarnings("unchecked")
    Map<String, Object> graphObject = (Map<String, Object>) Proxy
            .newProxyInstance(GraphObject.class.getClassLoader(), interfaces, graphObjectProxy);

    return graphObject;
}