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:ome.tools.hibernate.SessionStatus.java

public EmptySessionHolder() {
    super((Session) Proxy.newProxyInstance(Session.class.getClassLoader(), new Class[] { Session.class },
            new InvocationHandler() {
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    String name = method.getName();
                    if (name.equals("toString")) {
                        return "NULL SESSION PROXY";
                    }//  w  w  w  .  j a  va2 s . c o m

            else if (name.equals("hashCode")) {
                        return 0;
                    } else if (name.equals("equals")) {
                        return args[0] == null ? false : proxy == args[0];
                    } else {
                        throw new RuntimeException("No methods allowed");
                    }
                }
            }));
}

From source file:be.idamediafoundry.sofa.livecycle.dsc.util.AnnotationDrivenQDoxComponentInfoExtractor.java

private <T extends java.lang.annotation.Annotation> T convertToJavaLang(final Annotation annotation,
        final Class<T> expectedType) {
    try {/*from ww  w.j  ava2s.  c o m*/
        final Class<?> annotationClass = Class.forName(annotation.getType().getFullyQualifiedName());
        @SuppressWarnings("unchecked")
        T proxy = (T) Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[] { annotationClass },
                new InvocationHandler() {

                    public Object invoke(Object instance, Method method, Object[] args) throws Throwable {
                        if (method.getName().equals("toString")) {
                            return "Proxied annotation of type " + annotationClass;
                        } else if (method.getName().equals("getClass")) {
                            return annotationClass;
                        }

                        Object value = annotation.getProperty(method.getName());
                        if (value == null) {
                            return method.getDefaultValue();
                        }
                        if (value instanceof Annotation) {
                            java.lang.annotation.Annotation sub = convertToJavaLang((Annotation) value,
                                    java.lang.annotation.Annotation.class);
                            return sub;
                        } else {
                            AnnotationConstant constant = (AnnotationConstant) value;
                            value = constant.getValue();
                            return value;
                        }
                    }
                });

        return proxy;

    } catch (ClassNotFoundException e) {
        throw new IllegalArgumentException(
                "The source code is annotated with a class that could not be found on your project's classpath, please fix this!",
                e);
    }
}

From source file:com.mirth.connect.client.core.Client.java

@SuppressWarnings("unchecked")
public <T> T getServlet(final Class<T> servletInterface, final ExecuteType executeType) {
    return (T) Proxy.newProxyInstance(
            AccessController.doPrivileged(ReflectionHelper.getClassLoaderPA(servletInterface)),
            new Class[] { servletInterface }, new InvocationHandler() {
                @Override/*  www .j  ava2 s .c om*/
                public Object invoke(Object proxy, Method method, Object[] args) throws ClientException {
                    try {
                        WebTarget target = client.target(api);

                        Operation operation = OperationUtil.getOperation(servletInterface, method);
                        if (operation != null) {
                            target.property(ServerConnection.OPERATION_PROPERTY, operation);
                        }

                        if (executeType != null) {
                            target.property(ServerConnection.EXECUTE_TYPE_PROPERTY, executeType);
                        }

                        if (args == null && method.getName().equals("toString")) {
                            return target.toString();
                        }

                        T resource = WebResourceFactory.newResource(servletInterface, target);
                        Object result = method.invoke(resource, args);

                        // Make sure to return the right type
                        if (result == null && method.getReturnType().isPrimitive()) {
                            return method.getReturnType() == boolean.class ? false : (byte) 0x00;
                        }
                        return result;
                    } catch (Throwable t) {
                        Throwable cause = t;
                        if (cause instanceof InvocationTargetException && cause.getCause() != null) {
                            cause = cause.getCause();
                        }
                        if (cause instanceof ProcessingException && cause.getCause() != null) {
                            cause = cause.getCause();
                        }
                        if (cause instanceof ClientException) {
                            throw (ClientException) cause;
                        } else {
                            throw new ClientException(cause);
                        }
                    }
                }
            });
}

From source file:org.talend.updates.runtime.model.P2ExtraFeature.java

@Override
public IStatus install(final IProgressMonitor progress, List<URI> allRepoUris) throws ExtraFeatureException {
    IStatus doInstallStatus = null;//from w  ww .j a v a 2s.c o  m
    File configIniBackupFile = null;
    Map<File, File> unzippedPatches = new HashMap<>();
    try {
        if (!isUseLegacyP2Install()) {
            // backup the config.ini
            configIniBackupFile = copyConfigFile(null);
        } // else legacy p2 install will update the config.ini
        doInstallStatus = installP2(progress, allRepoUris);
        if (doInstallStatus == null || !doInstallStatus.isOK()) {
            return doInstallStatus;
        }
        unzippedPatches = unzipPatches(progress, allRepoUris);
        storeInstalledFeatureMessage();
    } catch (IOException e) {
        throw new ExtraFeatureException(new ProvisionException(
                Messages.createErrorStatus(e, "ExtraFeaturesFactory.restore.config.error"))); //$NON-NLS-1$
    } finally {
        boolean isInstalled = false;
        if (doInstallStatus != null) {
            switch (doInstallStatus.getSeverity()) {
            case IStatus.OK:
            case IStatus.INFO:
            case IStatus.WARNING:
                isInstalled = true;
                break;
            default:
                isInstalled = false;
                break;
            }
        }
        IProgressMonitor monitor2 = progress;
        if (isInstalled) {
            if (progress != null) {
                monitor2 = (IProgressMonitor) Proxy.newProxyInstance(progress.getClass().getClassLoader(),
                        new Class[] { IProgressMonitor.class }, new InvocationHandler() {

                            @Override
                            public Object invoke(Object obj, Method method, Object[] args) throws Throwable {
                                if (method == null) {
                                    return null;
                                }
                                if (StringUtils.equals(method.getName(), "isCanceled")) { //$NON-NLS-1$
                                    return Boolean.FALSE;
                                }
                                return method.invoke(progress, args);
                            }
                        });
            }
            try {
                afterInstallP2(monitor2, unzippedPatches);
            } catch (Exception e) {
                ExceptionHandler.process(e);
            }
        }
        // restore the config.ini
        if (configIniBackupFile != null) { // must existed backup file.
            try {
                copyConfigFile(configIniBackupFile);
            } catch (IOException e) {
                throw new P2ExtraFeatureException(new ProvisionException(
                        Messages.createErrorStatus(e, "ExtraFeaturesFactory.back.config.error"))); //$NON-NLS-1$
            }
        }
        if (isInstalled) {
            try {
                afterRestoreConfigFile(monitor2, unzippedPatches);
            } catch (Exception e) {
                ExceptionHandler.process(e);
            }
        }
        if (unzippedPatches != null && !unzippedPatches.isEmpty()) {
            for (Map.Entry<File, File> patchEntry : unzippedPatches.entrySet()) {
                FilesUtils.deleteFolder(patchEntry.getValue(), true);
            }
        }
    }
    return doInstallStatus;
}

From source file:mondrian.xmla.impl.Olap4jXmlaServlet.java

/**
 * Returns something that implements {@link OlapConnection} but still
 * behaves as the wrapper returned by the connection pool.
 *
 * <p>In other words we want the "close" method to play nice and do all the
 * pooling actions while we want all the olap methods to execute directly on
 * the un-wrapped OlapConnection object.
 *//*from w w w.j a  v a 2 s. c  o m*/
private static OlapConnection createDelegatingOlapConnection(final Connection connection,
        final OlapConnection olapConnection) {
    return (OlapConnection) Proxy.newProxyInstance(olapConnection.getClass().getClassLoader(),
            new Class[] { OlapConnection.class }, new InvocationHandler() {
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    if ("unwrap".equals(method.getName())
                            || OlapConnection.class.isAssignableFrom(method.getDeclaringClass())) {
                        return method.invoke(olapConnection, args);
                    } else {
                        return method.invoke(connection, args);
                    }
                }
            });
}

From source file:org.hyperic.hq.product.jmx.MxUtil.java

public static JMXConnector getCachedMBeanConnector(Properties config)
        throws MalformedURLException, IOException {
    String jmxUrl = config.getProperty(MxUtil.PROP_JMX_URL);
    String user = config.getProperty(PROP_JMX_USERNAME);
    String pass = config.getProperty(PROP_JMX_PASSWORD);
    JMXConnectorKey key = new JMXConnectorKey(jmxUrl, user, pass);
    JMXConnector rtn = null;//  w ww  .  j ava  2  s  .  c o m
    synchronized (mbeanConns) {
        rtn = mbeanConns.get(key);
        if (rtn == null) {
            rtn = getMBeanConnector(config);
            mbeanConns.put(key, rtn);
        }
        try {
            // ensure that the connection is not broken
            rtn.getMBeanServerConnection();
        } catch (IOException e) {
            close(rtn);
            rtn = getMBeanConnector(config);
            mbeanConns.put(key, rtn);
        }
    }
    final JMXConnector c = rtn;
    final InvocationHandler handler = new InvocationHandler() {
        private final JMXConnector conn = c;

        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            if (method.getName().equals("close")) {
                return null;
            }
            synchronized (conn) {
                return method.invoke(conn, args);
            }
        }
    };
    return (JMXConnector) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
            new Class<?>[] { JMXConnector.class }, handler);
}

From source file:org.itest.impl.ITestRandomObjectGeneratorImpl.java

protected Object newDynamicProxy(Type type, final Map<String, Type> itestGenericMap,
        final ITestContext iTestContext) {
    final Class<?> clazz = ITestTypeUtil.getRawClass(type);
    final Map<String, Object> methodResults = new HashMap<String, Object>();

    Object res = Proxy.newProxyInstance(clazz.getClassLoader(), new Class<?>[] { clazz },
            new InvocationHandler() {

                @Override/* w  ww  .java  2 s .c  om*/
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    String mSignature = ITestUtils.getMethodSingnature(method, true);
                    if (methodResults.containsKey(mSignature)) {
                        return methodResults.get(mSignature);
                    }
                    throw new ITestMethodExecutionException(
                            "Implementation of " + clazz.getName() + "." + mSignature + " not provided", null);
                }
            });

    Map<String, Type> map = ITestTypeUtil.getTypeMap(type, new HashMap<String, Type>());

    Class<?> t = clazz;
    do {
        for (Method m : t.getDeclaredMethods()) {
            if (!Modifier.isStatic(m.getModifiers())) {
                String signature = ITestUtils.getMethodSingnature(m, true);
                ITestParamState iTestState = iTestContext.getCurrentParam();
                ITestParamState mITestState = iTestState == null ? null : iTestState.getElement(signature);
                if (null == mITestState) {
                    mITestState = iTestState == null ? null
                            : iTestState.getElement(signature = ITestUtils.getMethodSingnature(m, false));
                }
                fillMethod(m, res, signature, map, iTestContext, methodResults);
            }
        }
        map = ITestTypeUtil.getTypeMap(clazz, map);
    } while ((t = t.getSuperclass()) != null);

    return res;
}

From source file:org.soybeanMilk.test.unit.core.TestInvoke.java

@Test
public void execute_genericMethod_resolverIsProxy_resolveBase() throws Exception {
    SubSubSubGenericResolver resolver = (SubSubSubGenericResolver) Proxy.newProxyInstance(
            SubSubSubGenericResolver.class.getClassLoader(), new Class<?>[] { SubSubSubGenericResolver.class },
            new InvocationHandler() {
                private Object handler = new SubSubSubGenericResolverImpl();

                public Object invoke(Object arg0, Method arg1, Object[] arg2) throws Throwable {
                    return arg1.invoke(handler, arg2);
                }/*from  w  w  w.j  av  a 2  s. c  o  m*/
            });

    Arg[] args = new Arg[1];
    args[0] = new KeyArg("arg0");
    Invoke invoke = new Invoke(null, new ObjectResolver(resolver), "resolveBase", args, "result");

    Map<String, Object> src = new HashMap<String, Object>();
    src.put("id", 1);
    src.put("name", "generic");
    src.put("age", 5);

    ObjectSource os = new HashMapObjectSource(new DefaultGenericConverter());
    os.set("arg0", src);

    invoke.execute(os);

    JavaBeanSub re = os.get("result");

    Assert.assertEquals(1, re.getId().intValue());
    Assert.assertEquals("generic", re.getName());
    Assert.assertEquals(5, re.getAge().intValue());
}

From source file:org.apache.htrace.core.Tracer.java

/**
 * Returns an object that will trace all calls to itself.
 *///from  w  ww  . j  av  a  2  s. c o  m
@SuppressWarnings("unchecked")
<T, V> T createProxy(final T instance) {
    InvocationHandler handler = new InvocationHandler() {
        @Override
        public Object invoke(Object obj, Method method, Object[] args) throws Throwable {
            try (TraceScope scope = Tracer.this.newScope(method.getName());) {
                return method.invoke(instance, args);
            } catch (Throwable ex) {
                ex.printStackTrace();
                throw ex;
            }
        }
    };
    return (T) Proxy.newProxyInstance(instance.getClass().getClassLoader(), instance.getClass().getInterfaces(),
            handler);
}

From source file:org.soybeanMilk.test.unit.core.TestInvoke.java

@Test
public void execute_genericMethod_resolverIsProxy_resolveSub() throws Exception {
    SubSubSubGenericResolver resolver = (SubSubSubGenericResolver) Proxy.newProxyInstance(
            SubSubSubGenericResolver.class.getClassLoader(), new Class<?>[] { SubSubSubGenericResolver.class },
            new InvocationHandler() {
                private Object handler = new SubSubSubGenericResolverImpl();

                public Object invoke(Object arg0, Method arg1, Object[] arg2) throws Throwable {
                    return arg1.invoke(handler, arg2);
                }//from   w w w .j av  a  2 s . co  m
            });

    Arg[] args = new Arg[1];
    args[0] = new KeyArg("arg0");
    Invoke invoke = new Invoke(null, new ObjectResolver(resolver), "resolveSub", args, "result");

    Map<String, Object> src = new HashMap<String, Object>();
    src.put("id", 1);
    src.put("name", "generic");
    src.put("age", 5);

    ObjectSource os = new HashMapObjectSource(new DefaultGenericConverter());
    os.set("arg0", src);

    invoke.execute(os);

    JavaBeanSub re = os.get("result");

    Assert.assertEquals(1, re.getId().intValue());
    Assert.assertEquals("generic", re.getName());
    Assert.assertEquals(5, re.getAge().intValue());
}