Example usage for java.lang.reflect InvocationHandler InvocationHandler

List of usage examples for java.lang.reflect InvocationHandler InvocationHandler

Introduction

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

Prototype

InvocationHandler

Source Link

Usage

From source file:EventTracerTest.java

public EventTracer() {
    // the handler for all event proxies
    handler = new InvocationHandler() {
        public Object invoke(Object proxy, Method method, Object[] args) {
            System.out.println(method + ":" + args[0]);
            return null;
        }/*from  w w w .  j av  a2  s. c  o  m*/
    };
}

From source file:org.ops4j.pax.exam.rbc.client.RemoteBundleContextClient.java

/**
 * {@inheritDoc}//w  w w  .ja va 2  s  .  c o m
 * Returns a dynamic proxy in place of the actual service, forwarding the calls via the remote bundle context.
 */
@SuppressWarnings("unchecked")
public <T> T getService(final Class<T> serviceType, final long timeoutInMillis) {
    return (T) Proxy.newProxyInstance(getClass().getClassLoader(), new Class<?>[] { serviceType },
            new InvocationHandler() {
                /**
                 * {@inheritDoc}
                 * Delegates the call to remote bundle context.
                 */
                public Object invoke(final Object proxy, final Method method, final Object[] params)
                        throws Throwable {
                    try {
                        return getRemoteBundleContext().remoteCall(method.getDeclaringClass(), method.getName(),
                                method.getParameterTypes(), timeoutInMillis, params);
                    } catch (InvocationTargetException e) {
                        throw e.getCause();
                    } catch (RemoteException e) {
                        throw new TestContainerException("Remote exception", e);
                    } catch (Exception e) {
                        throw new TestContainerException("Invocation exception", e);
                    }
                }
            });
}

From source file:org.rhq.plugins.cassandra.DiscoveryTest.java

@Test
public void testResourceKeyParsing() throws Exception {
    // Mock discovered resources
    Configuration pluginConfiguration = mock(Configuration.class);

    DiscoveredResourceDetails details = new DiscoveredResourceDetails(mock(ResourceType.class),
            "org.apache.cassandra.db:type=ColumnFamilies,keyspace=rhq,columnfamily=raw_metrics", "1", "2", "3",
            mock(Configuration.class), mock(ProcessInfo.class));
    DiscoveredResourceDetails details2 = new DiscoveredResourceDetails(mock(ResourceType.class),
            "org.apache.cassandra.db:type=ColumnFamilies,columnfamily=raw_metrics", "1", "2", "3",
            mock(Configuration.class), mock(ProcessInfo.class));
    final Set<DiscoveredResourceDetails> discoveredResources = new HashSet<DiscoveredResourceDetails>();
    discoveredResources.add(details);//from  w  w  w. j  a v a 2s  . co  m
    discoveredResources.add(details2);

    // Replace method..
    Method discover = MBeanResourceDiscoveryComponent.class.getMethod("discoverResources",
            ResourceDiscoveryContext.class, boolean.class);
    PowerMockito.replace(discover).with(new InvocationHandler() {
        @Override
        public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
            return discoveredResources;
        }
    });

    ColumnFamilyDiscoveryComponent columnFamilyDiscoveryComponent = new ColumnFamilyDiscoveryComponent();

    // Mock keyspace context
    ResourceDiscoveryContext mockContext = mock(ResourceDiscoveryContext.class);
    ResourceContext mockParentContext = mock(ResourceContext.class);
    when(mockContext.getParentResourceContext()).thenReturn(mockParentContext);
    when(mockParentContext.getResourceKey()).thenReturn("rhq");

    assertEquals(mockContext.getParentResourceContext().getResourceKey(), "rhq");

    // Do the actual discovery parsing
    Set<DiscoveredResourceDetails> discoveredResourceDetails = columnFamilyDiscoveryComponent
            .discoverResources(mockContext);
    assertEquals(discoveredResourceDetails.size(), 1);
    for (DiscoveredResourceDetails discoveredResource : discoveredResourceDetails) {
        assertEquals(discoveredResource.getResourceKey(), "raw_metrics");
    }
}

From source file:org.eclipse.wb.internal.rcp.model.rcp.EditorPartInfo.java

private void setEditorSite() throws Exception {
    ClassLoader editorLoader = JavaInfoUtils.getClassLoader(this);
    Class<?> editorSiteClass = editorLoader.loadClass("org.eclipse.ui.IEditorSite");
    Class<?> editorInputClass = editorLoader.loadClass("org.eclipse.ui.IEditorInput");
    // create IEditorSite
    Object editorSite = Proxy.newProxyInstance(editorLoader, new Class<?>[] { editorSiteClass },
            new InvocationHandler() {
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    String signature = ReflectionUtils.getMethodSignature(method);
                    if (signature.equals("toString()")) {
                        return "IEditorSite_stub";
                    }//  w w  w  .j a v  a 2  s .c om
                    if (signature.equals("hashCode()")) {
                        return 0;
                    }
                    if (signature.equals("getId()")) {
                        return getID();
                    }
                    if (signature.equals("getWorkbenchWindow()")) {
                        return DesignerPlugin.getActiveWorkbenchWindow();
                    }
                    // IServiceLocator
                    if (signature.equals("hasService(java.lang.Class)")) {
                        IServiceLocator serviceLocator = DesignerPlugin.getActiveWorkbenchWindow();
                        return serviceLocator.hasService((Class<?>) args[0]);
                    }
                    if (signature.equals("getService(java.lang.Class)")) {
                        IServiceLocator serviceLocator = DesignerPlugin.getActiveWorkbenchWindow();
                        return serviceLocator.getService((Class<?>) args[0]);
                    }
                    // not implemented
                    throw new NotImplementedException(method.toString());
                }
            });
    // create org.eclipse.ui.IEditorInput
    Object editorInput = Proxy.newProxyInstance(editorLoader, new Class<?>[] { editorInputClass },
            new InvocationHandler() {
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    Class<?> returnType = method.getReturnType();
                    return ReflectionUtils.getDefaultValue(returnType);
                }
            });
    // call init(IEditorSite,IEditorInput)
    ReflectionUtils.invokeMethod(getObject(), "init(org.eclipse.ui.IEditorSite,org.eclipse.ui.IEditorInput)",
            editorSite, editorInput);
}

From source file:com.delphix.session.module.rmi.impl.RmiFactoryImpl.java

@Override
public <T> T createProxy(final Class<T> type, final ServiceNexus nexus, final UUID objectId) {
    Object proxy = Proxy.newProxyInstance(RmiFactoryImpl.class.getClassLoader(), new Class[] { type },
            new InvocationHandler() {
                private RmiMethodOrdering ifm = new RmiMethodOrdering(type);

                @Override/*from   ww w . j  a v a  2 s  .  c o  m*/
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    if (args == null) {
                        args = new Object[0];
                    }

                    if (method.getName().equals("close") && args.length == 0) {
                        ObjectDestroyRequest request = new ObjectDestroyRequest();
                        request.setObjectId(objectId);

                        try {
                            nexus.execute(request).get();
                        } catch (InterruptedException e) {
                            throw new DelphixInterruptedException(e);
                        } catch (ExecutionException e) {
                            throw new RuntimeException(ExceptionUtil.unwrap(e));
                        }
                        return null;
                    } else {
                        MethodCallRequest request = new MethodCallRequest();
                        request.setObjectId(objectId);
                        request.setMethod(ifm.getPlacement(method));
                        request.setArguments(args);

                        MethodCallResponse response;
                        try {
                            response = (MethodCallResponse) nexus.execute(request).get();
                        } catch (InterruptedException e) {
                            throw new DelphixInterruptedException(e);
                        } catch (ExecutionException e) {
                            throw new RuntimeException(ExceptionUtil.unwrap(e));
                        }

                        if (response.getException()) {
                            throw ExceptionUtil.unwrap(new ExecutionException((Throwable) response.getValue()));
                        } else {
                            return response.getValue();
                        }
                    }
                }
            });

    return type.cast(proxy);
}

From source file:org.eclipse.wb.internal.rcp.model.rcp.ViewPartInfo.java

/**
 * Initializes this {@link ViewPart} with {@link IViewSite}.
 */// w w  w  .  j  a  v  a 2s  .c  om
@Override
protected void applyActionBars() throws Exception {
    ClassLoader editorLoader = JavaInfoUtils.getClassLoader(this);
    Class<?> viewSiteClass = editorLoader.loadClass("org.eclipse.ui.IViewSite");
    // create IViewSite
    Object viewSite = Proxy.newProxyInstance(editorLoader, new Class<?>[] { viewSiteClass },
            new InvocationHandler() {
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    String signature = ReflectionUtils.getMethodSignature(method);
                    if (signature.equals("toString()")) {
                        return "IViewSite_stub";
                    }
                    if (signature.equals("hashCode()")) {
                        return 0;
                    }
                    if (signature.equals("getActionBars()")) {
                        return m_actionBars;
                    }
                    if (signature.equals("getId()")) {
                        return getID();
                    }
                    if (signature.equals("getSecondaryId()")) {
                        return null;
                    }
                    if (signature.equals("getWorkbenchWindow()")) {
                        return DesignerPlugin.getActiveWorkbenchWindow();
                    }
                    throw new NotImplementedException(method.toString());
                }
            });
    // call init(IViewSite)
    ReflectionUtils.invokeMethod(getObject(), "init(org.eclipse.ui.IViewSite)", viewSite);
}

From source file:com.google.code.guice.repository.configuration.PersistenceUnitConfiguration.java

/**
 * Represents current configuration as an EntityManager proxy. This is required for cases where
 * Configuration's EM can be changed at runtime - such as in Web-environments (see {@link PersistFilter}.
 *
 * @return proxy with EntityManager interface bound to current EM instance
 *
 * @see PersistenceUnitsConfigurationManager#changeEntityManager(String, EntityManager)
 * @see PersistFilter//from   w  w  w  .j a va2s. c  om
 */
public EntityManager asEntityManagerProxy() {
    return (EntityManager) Proxy.newProxyInstance(getClass().getClassLoader(),
            new Class[] { EntityManager.class }, new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    try {
                        return method.invoke(getEntityManager(), args);
                    } catch (InvocationTargetException e) {
                        Throwable t = e.getCause();
                        if (t != null) {
                            throw t;
                        } else {
                            throw e;
                        }
                    }
                }
            });
}

From source file:org.purl.sword.server.fedora.fileHandlers.QucosaMETSFileHandler_AbstractTest.java

@Before
public void setupFedoraRepositoryMock() throws Exception {
    mockFedoraRepository = mock(FedoraRepository.class);
    PowerMockito.whenNew(FedoraRepository.class).withAnyArguments().thenReturn(mockFedoraRepository);
    PowerMockito.replace(method(FedoraRepository.class, "mintPid")).with(new InvocationHandler() {
        private int i = 1;

        @Override/*w  w  w . j a  v  a 2 s  . c om*/
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            return "test:" + (i++);
        }
    });
    when(mockFedoraRepository.mintPid()).thenCallRealMethod();
}

From source file:org.pentaho.platform.web.servlet.JAXRSServlet.java

@Override
public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    if (logger.isDebugEnabled()) {
        logger.debug("servicing request for resource " + request.getPathInfo()); //$NON-NLS-1$
    }//  w  ww .  j a v a  2  s.c o  m

    if (request.getMethod().equals(GET)) {
        // Extension to allow accept type override from mime-type query param
        final String mimeType = request.getParameter(MIME_TYPE);
        if (mimeType != null) {
            final HttpServletRequest originalRequest = request;

            request = (HttpServletRequest) Proxy.newProxyInstance(getClass().getClassLoader(),
                    new Class[] { HttpServletRequest.class }, new InvocationHandler() {
                        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                            if (method.getName().equals(GET_HEADERS) && args.length > 0
                                    && args[0].equals(ACCEPT)) {
                                return new Enumeration() {
                                    boolean hasMore = true;

                                    @Override
                                    public boolean hasMoreElements() {
                                        return hasMore;
                                    }

                                    @Override
                                    public Object nextElement() {
                                        hasMore = false;
                                        return mimeType;
                                    }
                                };
                            }
                            return method.invoke(originalRequest, args);
                        }
                    });
        }
    }
    super.service(request, response);
}

From source file:org.apache.cocoon.components.source.impl.BlockContextSource.java

private static Source adjustName(final TraversableSource source, final String blockName) {
    TraversableSource adjustedSource = (TraversableSource) Proxy.newProxyInstance(
            source.getClass().getClassLoader(), ClassUtils.getAllInterfaces(source), new InvocationHandler() {

                /* (non-Javadoc)
                 * @see java.lang.reflect.InvocationHandler#invoke(java.lang.Object, java.lang.reflect.Method, java.lang.Object[])
                 *//*w  w  w. j a  va 2  s.  co m*/
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    if (method.equals(TraversableSource.class.getMethod("getName", new Class[] {})))
                        return blockName;
                    else
                        return method.invoke(source, args);
                }
            });
    return adjustedSource;
}