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:org.apache.nifi.controller.service.StandardControllerServiceProvider.java

@Override
public ControllerServiceNode createControllerService(final String type, final String id,
        final boolean firstTimeAdded) {
    if (type == null || id == null) {
        throw new NullPointerException();
    }/* w  w  w .j  a v  a2  s.c om*/

    final ClassLoader currentContextClassLoader = Thread.currentThread().getContextClassLoader();
    try {
        final ClassLoader cl = ExtensionManager.getClassLoader(type, id);
        final Class<?> rawClass;

        try {
            if (cl == null) {
                rawClass = Class.forName(type);
            } else {
                Thread.currentThread().setContextClassLoader(cl);
                rawClass = Class.forName(type, false, cl);
            }
        } catch (final Exception e) {
            logger.error("Could not create Controller Service of type " + type + " for ID " + id
                    + "; creating \"Ghost\" implementation", e);
            Thread.currentThread().setContextClassLoader(currentContextClassLoader);
            return createGhostControllerService(type, id);
        }

        final Class<? extends ControllerService> controllerServiceClass = rawClass
                .asSubclass(ControllerService.class);

        final ControllerService originalService = controllerServiceClass.newInstance();
        final AtomicReference<ControllerServiceNode> serviceNodeHolder = new AtomicReference<>(null);
        final InvocationHandler invocationHandler = new InvocationHandler() {
            @Override
            public Object invoke(final Object proxy, final Method method, final Object[] args)
                    throws Throwable {

                final String methodName = method.getName();
                if ("initialize".equals(methodName) || "onPropertyModified".equals(methodName)) {
                    throw new UnsupportedOperationException(
                            method + " may only be invoked by the NiFi framework");
                }

                final ControllerServiceNode node = serviceNodeHolder.get();
                final ControllerServiceState state = node.getState();
                final boolean disabled = state != ControllerServiceState.ENABLED; // only allow method call if service state is ENABLED.
                if (disabled && !validDisabledMethods.contains(method)) {
                    // Use nar class loader here because we are implicitly calling toString() on the original implementation.
                    try (final NarCloseable narCloseable = NarCloseable.withComponentNarLoader(
                            originalService.getClass(), originalService.getIdentifier())) {
                        throw new IllegalStateException("Cannot invoke method " + method
                                + " on Controller Service " + originalService.getIdentifier()
                                + " because the Controller Service is disabled");
                    } catch (final Throwable e) {
                        throw new IllegalStateException(
                                "Cannot invoke method " + method + " on Controller Service with identifier "
                                        + id + " because the Controller Service is disabled");
                    }
                }

                try (final NarCloseable narCloseable = NarCloseable
                        .withComponentNarLoader(originalService.getClass(), originalService.getIdentifier())) {
                    return method.invoke(originalService, args);
                } catch (final InvocationTargetException e) {
                    // If the ControllerService throws an Exception, it'll be wrapped in an InvocationTargetException. We want
                    // to instead re-throw what the ControllerService threw, so we pull it out of the InvocationTargetException.
                    throw e.getCause();
                }
            }
        };

        final ControllerService proxiedService;
        if (cl == null) {
            proxiedService = (ControllerService) Proxy.newProxyInstance(getClass().getClassLoader(),
                    getInterfaces(controllerServiceClass), invocationHandler);
        } else {
            proxiedService = (ControllerService) Proxy.newProxyInstance(cl,
                    getInterfaces(controllerServiceClass), invocationHandler);
        }
        logger.info("Created Controller Service of type {} with identifier {}", type, id);

        final ComponentLog serviceLogger = new SimpleProcessLogger(id, originalService);
        originalService.initialize(new StandardControllerServiceInitializationContext(id, serviceLogger, this,
                getStateManager(id), nifiProperties));

        final ComponentLog logger = new SimpleProcessLogger(id, originalService);
        final ValidationContextFactory validationContextFactory = new StandardValidationContextFactory(this,
                variableRegistry);

        final ControllerServiceNode serviceNode = new StandardControllerServiceNode(proxiedService,
                originalService, id, validationContextFactory, this, variableRegistry, logger);
        serviceNodeHolder.set(serviceNode);
        serviceNode.setName(rawClass.getSimpleName());

        if (firstTimeAdded) {
            try (final NarCloseable x = NarCloseable.withComponentNarLoader(originalService.getClass(),
                    originalService.getIdentifier())) {
                ReflectionUtils.invokeMethodsWithAnnotation(OnAdded.class, originalService);
            } catch (final Exception e) {
                throw new ComponentLifeCycleException(
                        "Failed to invoke On-Added Lifecycle methods of " + originalService, e);
            }
        }

        return serviceNode;
    } catch (final Throwable t) {
        throw new ControllerServiceInstantiationException(t);
    } finally {
        if (currentContextClassLoader != null) {
            Thread.currentThread().setContextClassLoader(currentContextClassLoader);
        }
    }
}

From source file:com.google.gdt.eclipse.designer.uibinder.parser.UiBinderParser.java

/**
 * Handle object before setting attributes, so get default property values.
 */// ww  w .jav  a 2 s  .co  m
private void createModels(Object binder) throws Exception {
    ClassLoader classLoader = binder.getClass().getClassLoader();
    String handlerClassName = binder.getClass().getName() + "$DTObjectHandler";
    Class<?> handlerClass = classLoader.loadClass(handlerClassName);
    Object handler = Proxy.newProxyInstance(classLoader, new Class[] { handlerClass }, new InvocationHandler() {
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            if (method.getName().equals("handle")) {
                String path = (String) args[0];
                Object object = args[1];
                createModel(path, object);
            }
            if (method.getName().equals("provideFactory")) {
                Class<?> factoryType = (Class<?>) args[0];
                String methodName = (String) args[1];
                Object[] factoryArgs = (Object[]) args[2];
                return createProvidedFactory(m_context, factoryType, methodName, factoryArgs);
            }
            if (method.getName().equals("provideField")) {
                Class<?> fieldType = (Class<?>) args[0];
                String fieldName = (String) args[1];
                return createProvidedField(m_context, fieldType, fieldName);
            }
            return null;
        }
    });
    ReflectionUtils.setField(binder, "dtObjectHandler", handler);
}

From source file:ch.digitalfondue.npjt.QueryFactory.java

@SuppressWarnings("unchecked")
public <T> T from(final Class<T> clazz) {

    return (T) Proxy.newProxyInstance(clazz.getClassLoader(), new Class[] { clazz }, new InvocationHandler() {
        @Override/*from ww w.ja v a2 s  . com*/
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            boolean hasAnnotation = method.getAnnotation(Query.class) != null;
            if (hasAnnotation) {
                QueryTypeAndQuery qs = extractQueryAnnotation(clazz, method);
                return qs.type.apply(qs.query, qs.rowMapperClass, jdbc, method, args, columnMapperFactories.set,
                        parameterConverters.set);
            } else if (method.getReturnType().equals(NamedParameterJdbcTemplate.class) && args == null) {
                return jdbc;
            } else if (IS_DEFAULT_METHOD != null && (boolean) IS_DEFAULT_METHOD.invoke(method)) {
                final Class<?> declaringClass = method.getDeclaringClass();
                return LOOKUP_CONSTRUCTOR.newInstance(declaringClass, MethodHandles.Lookup.PRIVATE)
                        .unreflectSpecial(method, declaringClass).bindTo(proxy).invokeWithArguments(args);
            } else {
                throw new IllegalArgumentException(
                        String.format("missing @Query annotation for method %s in interface %s",
                                method.getName(), clazz.getSimpleName()));
            }

        }
    }

    );
}

From source file:org.overlord.commons.auth.filters.SamlBearerTokenAuthFilter.java

/**
 * Wrap/proxy the http request./*from   ww w  .j  ava 2  s .  co  m*/
 * @param request
 * @param principal
 */
private HttpServletRequest proxyRequest(final ServletRequest request, final SimplePrincipal principal) {
    InvocationHandler handler = new InvocationHandler() {
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            if (method.getName().equals("getUserPrincipal")) { //$NON-NLS-1$
                return principal;
            } else if (method.getName().equals("getRemoteUser")) { //$NON-NLS-1$
                return principal.getName();
            } else if (method.getName().equals("isUserInRole")) { //$NON-NLS-1$
                String role = (String) args[0];
                return principal.getRoles().contains(role);
            }
            return method.invoke(request, args);
        }
    };
    return (HttpServletRequest) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
            new Class[] { HttpServletRequest.class }, handler);
}

From source file:fr.xebia.management.ServletContextAwareMBeanServerFactory.java

public MBeanServer getObject() throws Exception {
    if (instance == null) {
        InvocationHandler invocationHandler = new InvocationHandler() {
            /**//w  w w.j a  v  a 2 s  .com
             * <p>
             * Copy the given <code>objectName</code> adding the extra
             * attributes.
             * </p>
             */
            protected ObjectName addExtraAttributesToObjectName(ObjectName objectName)
                    throws MalformedObjectNameException {
                Hashtable<String, String> table = new Hashtable<String, String>(
                        objectName.getKeyPropertyList());
                table.putAll(objectNameExtraAttributes);

                ObjectName result = ObjectName.getInstance(objectName.getDomain(), table);
                logger.trace("addExtraAttributesToObjectName({}): {}", objectName, result);

                return result;
            }

            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Object[] modifiedArgs = args.clone();
                for (int i = 0; i < modifiedArgs.length; i++) {
                    Object arg = modifiedArgs[i];
                    if (arg instanceof ObjectName) {
                        ObjectName objectName = (ObjectName) arg;
                        modifiedArgs[i] = addExtraAttributesToObjectName(objectName);
                    }
                }
                if (logger.isDebugEnabled()) {
                    logger.debug(method + " : " + Arrays.asList(modifiedArgs));
                }
                try {
                    return method.invoke(server, modifiedArgs);
                } catch (InvocationTargetException ite) {
                    throw ite.getCause();
                }
            }
        };
        instance = (MBeanServer) Proxy.newProxyInstance(ClassUtils.getDefaultClassLoader(),
                new Class[] { MBeanServer.class }, invocationHandler);

    }
    return instance;
}

From source file:org.apache.xmlgraphics.image.loader.util.ImageUtil.java

/**
 * Decorates an ImageInputStream so the flush*() methods are ignored and have no effect.
 * The decoration is implemented using a dynamic proxy.
 * @param in the ImageInputStream//from   www  . jav a2 s  . c  o  m
 * @return the decorated ImageInputStream
 */
public static ImageInputStream ignoreFlushing(final ImageInputStream in) {
    return (ImageInputStream) Proxy.newProxyInstance(in.getClass().getClassLoader(),
            new Class[] { ImageInputStream.class }, new InvocationHandler() {
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    String methodName = method.getName();
                    //Ignore calls to flush*()
                    if (!methodName.startsWith("flush")) {
                        try {
                            return method.invoke(in, args);
                        } catch (InvocationTargetException ite) {
                            throw ite.getCause();
                        }
                    } else {
                        return null;
                    }
                }
            });
}

From source file:com.brighttag.agathon.resources.ValidatingJacksonJsonProviderTest.java

/**
 * Necessary to "instantiate" an annotation, since mocking #annotationType() fails.
 * @see http://stackoverflow.com/questions/2786292
 *///from ww  w  .java2 s  .  co m
private <T extends Annotation> Annotation createMockAnnotation(final Class<T> klass) {
    return (Annotation) Proxy.newProxyInstance(klass.getClassLoader(), new Class[] { Annotation.class },
            new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) {
                    return klass; // only getClass() or annotationType() should be called.
                }
            });
}

From source file:com.medallia.spider.api.StRenderer.java

private Object createInput(Class<?> x, final DynamicInputImpl dynamicInput) {
    return Proxy.newProxyInstance(x.getClassLoader(), new Class<?>[] { x }, new InvocationHandler() {
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            return dynamicInput.getInput(method.getName(), method.getReturnType(), method);
        }//from ww  w .j  av a 2 s.  c o  m
    });
}

From source file:org.apache.hadoop.metrics2.impl.MetricsSystemImpl.java

@Override
public synchronized void register(final Callback callback) {
    callbacks.add((Callback) Proxy.newProxyInstance(callback.getClass().getClassLoader(),
            new Class<?>[] { Callback.class }, new InvocationHandler() {
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    try {
                        return method.invoke(callback, args);
                    } catch (Exception e) {
                        LOG.warn("Caught exception in callback " + method.getName(), e);
                    }//from   ww w. ja  va2s .c om
                    return null;
                }
            }));
}

From source file:org.apache.hadoop.hbase.fs.HFileSystem.java

private static ClientProtocol createReorderingProxy(final ClientProtocol cp, final ReorderBlocks lrb,
        final Configuration conf) {
    return (ClientProtocol) Proxy.newProxyInstance(cp.getClass().getClassLoader(),
            new Class[] { ClientProtocol.class, Closeable.class }, new InvocationHandler() {
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    try {
                        if ((args == null || args.length == 0) && "close".equals(method.getName())) {
                            RPC.stopProxy(cp);
                            return null;
                        } else {
                            Object res = method.invoke(cp, args);
                            if (res != null && args != null && args.length == 3
                                    && "getBlockLocations".equals(method.getName())
                                    && res instanceof LocatedBlocks && args[0] instanceof String
                                    && args[0] != null) {
                                lrb.reorderBlocks(conf, (LocatedBlocks) res, (String) args[0]);
                            }//from   ww  w . java  2s.c  o  m
                            return res;
                        }
                    } catch (InvocationTargetException ite) {
                        // We will have this for all the exception, checked on not, sent
                        //  by any layer, including the functional exception
                        Throwable cause = ite.getCause();
                        if (cause == null) {
                            throw new RuntimeException("Proxy invocation failed and getCause is null", ite);
                        }
                        if (cause instanceof UndeclaredThrowableException) {
                            Throwable causeCause = cause.getCause();
                            if (causeCause == null) {
                                throw new RuntimeException("UndeclaredThrowableException had null cause!");
                            }
                            cause = cause.getCause();
                        }
                        throw cause;
                    }
                }
            });
}