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.broadleafcommerce.common.cache.AbstractCacheMissAware.java

/**
 * Retrieve a null representation of the cache item. This representation is the same for
 * all cache misses and is used as the object representation to store in the cache for a
 * cache miss./*from   ww w .j a  v a2  s  .c  o m*/
 *
 * @param responseClass the class representing the type of the cache item
 * @param <T> the type of the cache item
 * @return the null representation for the cache item
 */
protected synchronized <T> T getNullObject(final Class<T> responseClass) {
    if (nullObject == null) {
        Class<?>[] interfaces = (Class<?>[]) ArrayUtils.add(ClassUtils.getAllInterfacesForClass(responseClass),
                Serializable.class);
        nullObject = Proxy.newProxyInstance(getClass().getClassLoader(), interfaces, new InvocationHandler() {
            @Override
            public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
                if (method.getName().equals("equals")) {
                    return !(objects[0] == null) && objects[0].hashCode() == 31;
                } else if (method.getName().equals("hashCode")) {
                    return 31;
                } else if (method.getName().equals("toString")) {
                    return "Null_" + responseClass.getSimpleName();
                }
                throw new IllegalAccessException("Not a real object");
            }
        });
    }
    return (T) nullObject;
}

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

private void setObjects(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];
                XmlObjectInfo objectInfo = m_pathToModelMap.get(path);
                objectInfo.setObject(object);
            }/*  w w  w.j a v  a  2  s  .c  om*/
            if (method.getName().equals("provideFactory")) {
                Class<?> factoryType = (Class<?>) args[0];
                String methodName = (String) args[1];
                Object[] factoryArgs = (Object[]) args[2];
                return UiBinderParser.createProvidedFactory(m_context, factoryType, methodName, factoryArgs);
            }
            if (method.getName().equals("provideField")) {
                Class<?> fieldType = (Class<?>) args[0];
                String fieldName = (String) args[1];
                return UiBinderParser.createProvidedField(m_context, fieldType, fieldName);
            }
            return null;
        }
    });
    ReflectionUtils.setField(binder, "dtObjectHandler", handler);
}

From source file:com.github.jknack.handlebars.internal.BaseTemplate.java

/**
 * Creates a new {@link TypeSafeTemplate}.
 *
 * @param rootType The target type.//from w  ww.j a  v a2 s .  c  om
 * @param template The target template.
 * @return A new {@link TypeSafeTemplate}.
 */
private static Object newTypeSafeTemplate(final Class<?> rootType, final Template template) {
    return Proxy.newProxyInstance(template.getClass().getClassLoader(), new Class[] { rootType },
            new InvocationHandler() {
                private Map<String, Object> attributes = new HashMap<String, Object>();

                @Override
                public Object invoke(final Object proxy, final Method method, final Object[] args)
                        throws IOException {
                    String methodName = method.getName();
                    if ("apply".equals(methodName)) {
                        Context context = Context.newBuilder(args[0]).combine(attributes).build();
                        attributes.clear();
                        if (args.length == 2) {
                            template.apply(context, (Writer) args[1]);
                            return null;
                        }
                        return template.apply(context);
                    }

                    if (Modifier.isPublic(method.getModifiers()) && methodName.startsWith("set")) {
                        String attrName = StringUtils.uncapitalize(methodName.substring("set".length()));
                        if (args != null && args.length == 1 && attrName.length() > 0) {
                            attributes.put(attrName, args[0]);
                            if (TypeSafeTemplate.class.isAssignableFrom(method.getReturnType())) {
                                return proxy;
                            }
                            return null;
                        }
                    }
                    String message = String.format(
                            "No handler method for: '%s(%s)', expected method signature is: 'setXxx(value)'",
                            methodName, args == null ? "" : join(args, ", "));
                    throw new UnsupportedOperationException(message);
                }
            });
}

From source file:org.apache.fop.events.DefaultEventBroadcaster.java

/**
 * Creates a dynamic proxy for the given EventProducer interface that will handle the
 * conversion of the method call into the broadcasting of an event instance.
 * @param clazz a descendant interface of EventProducer
 * @return the EventProducer instance// w  ww  . j  av a2  s.  c  om
 */
protected EventProducer createProxyFor(Class clazz) {
    final EventProducerModel producerModel = getEventProducerModel(clazz);
    if (producerModel == null) {
        throw new IllegalStateException("Event model doesn't contain the definition for " + clazz.getName());
    }
    return (EventProducer) Proxy.newProxyInstance(clazz.getClassLoader(), new Class[] { clazz },
            new InvocationHandler() {
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    String methodName = method.getName();
                    EventMethodModel methodModel = producerModel.getMethod(methodName);
                    String eventID = producerModel.getInterfaceName() + "." + methodName;
                    if (methodModel == null) {
                        throw new IllegalStateException("Event model isn't consistent"
                                + " with the EventProducer interface. Please rebuild FOP!"
                                + " Affected method: " + eventID);
                    }
                    Map params = new java.util.HashMap();
                    int i = 1;
                    Iterator iter = methodModel.getParameters().iterator();
                    while (iter.hasNext()) {
                        EventMethodModel.Parameter param = (EventMethodModel.Parameter) iter.next();
                        params.put(param.getName(), args[i]);
                        i++;
                    }
                    Event ev = new Event(args[0], eventID, methodModel.getSeverity(), params);
                    broadcastEvent(ev);

                    if (ev.getSeverity() == EventSeverity.FATAL) {
                        EventExceptionManager.throwException(ev, methodModel.getExceptionClass());
                    }
                    return null;
                }
            });
}

From source file:org.corfudb.runtime.protocols.AsyncPooledThriftClient.java

/**
 * Gets a client instance that implements the AsyncIface interface that
 * connects to the given connection string.
 *
 * @param <T>/*from www .  j  a  v  a2  s.  com*/
 * @param asyncIfaceClass
 *          the AsyncIface interface to pool.
 * @param connectionStr
 *          the connection string.
 * @return the client instance.
 */
@SuppressWarnings("unchecked")
public <T> T getClient(final Class<T> asyncIfaceClass) {
    return (T) Proxy.newProxyInstance(asyncIfaceClass.getClassLoader(), new Class[] { asyncIfaceClass },
            new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    return execute(new AsyncCall(asyncIfaceClass, method, args, _connection));
                }
            });
}

From source file:grails.plugin.springsecurity.web.access.GrailsWebInvocationPrivilegeEvaluator.java

static HttpServletResponse createInstance() {
    return (HttpServletResponse) Proxy.newProxyInstance(HttpServletResponse.class.getClassLoader(),
            new Class[] { HttpServletResponse.class }, new InvocationHandler() {
                public Object invoke(Object proxy, Method method, Object[] args) {
                    throw new UnsupportedOperationException();
                }//from  w w w  .j ava 2s. co  m
            });
}

From source file:org.eclipse.wb.internal.xwt.parser.XwtRenderer.java

/**
 * Renders current content of {@link EditorContext} and fill objects for {@link XmlObjectInfo}s.
 *//*from   ww  w.  j ava 2 s . c  o  m*/
public void render() throws Exception {
    GlobalStateXml.activate(m_rootModel);
    // path -> model
    m_rootModel.accept(new ObjectInfoVisitor() {
        @Override
        public void endVisit(ObjectInfo objectInfo) throws Exception {
            if (objectInfo instanceof XmlObjectInfo) {
                XmlObjectInfo xmlObjectInfo = (XmlObjectInfo) objectInfo;
                CreationSupport creationSupport = xmlObjectInfo.getCreationSupport();
                if (!XmlObjectUtils.isImplicit(xmlObjectInfo)) {
                    DocumentElement element = creationSupport.getElement();
                    String path = XwtParser.getPath(element);
                    m_pathToModelMap.put(path, xmlObjectInfo);
                }
            }
        }
    });
    m_context.getBroadcastSupport().addListener(null, m_broadcast_setObjectAfter);
    // prepare IXWTLoader with intercepting IMetaclass loading 
    IXWTLoader loader;
    {
        final IXWTLoader loader0 = XWTLoaderManager.getActive();
        loader = (IXWTLoader) Proxy.newProxyInstance(getClass().getClassLoader(),
                new Class<?>[] { IXWTLoader.class }, new InvocationHandler() {
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        Object result = method.invoke(loader0, args);
                        String methodSignature = ReflectionUtils.getMethodSignature(method);
                        if (methodSignature.equals("registerMetaclass(java.lang.Class)")
                                || methodSignature.equals("getMetaclass(java.lang.String,java.lang.String)")) {
                            IMetaclass metaclass = (IMetaclass) result;
                            hookProperties(metaclass);
                            hookProperties_ofExposedWidgets(metaclass);
                        }
                        return result;
                    }

                    private void hookProperties_ofExposedWidgets(IMetaclass metaclass) throws Exception {
                        for (Method typeMethod : metaclass.getType().getMethods()) {
                            Class<?> returnType = typeMethod.getReturnType();
                            if (typeMethod.getParameterTypes().length == 0
                                    && Widget.class.isAssignableFrom(returnType)) {
                                metaclass = (IMetaclass) ReflectionUtils.invokeMethod(loader0,
                                        "registerMetaclass(java.lang.Class)", returnType);
                                hookProperties(metaclass);
                            }
                        }
                    }
                });
    }
    // provide ResourceLoader with "postCreation"
    Core profile = new Core(new IElementLoaderFactory() {
        private int m_level;

        public IVisualElementLoader createElementLoader(IRenderingContext context, IXWTLoader loader) {
            return new ResourceLoader(context, loader) {
                @Override
                protected Integer getStyleValue(Element element, int styles) {
                    Integer styleValue = super.getStyleValue(element, styles);
                    if (styleValue != null) {
                        String path = XwtParser.getPath(element);
                        XmlObjectInfo xmlObject = m_pathToModelMap.get(path);
                        if (xmlObject != null) {
                            xmlObject.registerAttributeValue("x:Style", styleValue);
                        }
                    }
                    return styleValue;
                }

                @Override
                protected void postCreation0(final Element element, final Object targetObject) {
                    if (m_level > 1) {
                        return;
                    }
                    ExecutionUtils.runRethrow(new RunnableEx() {
                        public void run() throws Exception {
                            postCreationEx(element, targetObject);
                        }
                    });
                }

                private void postCreationEx(Element element, Object targetObject) throws Exception {
                    String path = XwtParser.getPath(element);
                    XmlObjectInfo xmlObjectInfo = m_pathToModelMap.get(path);
                    if (xmlObjectInfo == null) {
                        return;
                    }
                    // wrapper Shell, ignore it
                    {
                        Class<? extends Object> targetClass = targetObject.getClass();
                        if (targetClass != xmlObjectInfo.getDescription().getComponentClass()) {
                            if (targetClass == Shell.class) {
                                return;
                            }
                        }
                    }
                    // set Object
                    xmlObjectInfo.setObject(targetObject);
                }

                ////////////////////////////////////////////////////////////////////////////
                //
                // Tweaks for handling tested XWT files
                //
                ////////////////////////////////////////////////////////////////////////////
                private final Set<Element> m_processedElements = Sets.newHashSet();

                private boolean isRoot(Element element) {
                    if (!m_processedElements.contains(element)) {
                        m_processedElements.add(element);
                        String path = element.getPath();
                        return "0".equals(path);
                    }
                    return false;
                }

                @Override
                protected Object doCreate(Object parent, Element element, Class<?> constraintType,
                        Map<String, Object> options) throws Exception {
                    boolean isRoot = isRoot(element);
                    try {
                        if (isRoot) {
                            m_level++;
                        }
                        return super.doCreate(parent, element, constraintType, options);
                    } finally {
                        if (isRoot) {
                            m_level--;
                        }
                    }
                }
            };
        }
    }, loader);
    // render
    XWT.applyProfile(profile);
    ILoadingContext _loadingContext = XWT.getLoadingContext();
    XWT.setLoadingContext(new DefaultLoadingContext(m_context.getClassLoader()));
    try {
        URL url = m_context.getFile().getLocationURI().toURL();
        String content = m_context.getContent();
        Map<String, Object> options = Maps.newHashMap();
        options.put(IXWTLoader.DESIGN_MODE_PROPERTY, Boolean.TRUE);
        content = removeCompositeClassAttribute(content);
        XwtParser.configureForForms(m_context, options);
        XWT.loadWithOptions(IOUtils.toInputStream(content), url, options);
    } finally {
        XWT.setLoadingContext(_loadingContext);
        XWT.restoreProfile();
    }
}

From source file:org.broadleafcommerce.openadmin.web.rulebuilder.service.AbstractRuleBuilderFieldService.java

@Override
@SuppressWarnings("unchecked")
public void setFields(final List<FieldData> fields) {
    List<FieldData> proxyFields = (List<FieldData>) Proxy.newProxyInstance(getClass().getClassLoader(),
            new Class<?>[] { List.class }, new InvocationHandler() {
                @Override//from   w  w  w  .j a v a  2s .  c om
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    if (method.getName().equals("add")) {
                        FieldData fieldData = (FieldData) args[0];
                        testFieldName(fieldData);
                    }
                    if (method.getName().equals("addAll")) {
                        Collection<FieldData> addCollection = (Collection<FieldData>) args[0];
                        Iterator<FieldData> itr = addCollection.iterator();
                        while (itr.hasNext()) {
                            FieldData fieldData = itr.next();
                            testFieldName(fieldData);
                        }
                    }
                    return method.invoke(fields, args);
                }

                private void testFieldName(FieldData fieldData) throws ClassNotFoundException {
                    if (!StringUtils.isEmpty(fieldData.getFieldName()) && dynamicEntityDao != null) {
                        Class<?>[] dtos = dynamicEntityDao
                                .getAllPolymorphicEntitiesFromCeiling(Class.forName(getDtoClassName()));
                        if (ArrayUtils.isEmpty(dtos)) {
                            dtos = new Class<?>[] { Class.forName(getDtoClassName()) };
                        }
                        Field field = null;
                        for (Class<?> dto : dtos) {
                            field = dynamicEntityDao.getFieldManager().getField(dto, fieldData.getFieldName());
                            if (field != null) {
                                break;
                            }
                        }
                        if (field == null) {
                            throw new IllegalArgumentException(
                                    "Unable to find the field declared in FieldData ("
                                            + fieldData.getFieldName() + ") on the target class ("
                                            + getDtoClassName()
                                            + "), or any registered entity class that derives from it.");
                        }
                    }
                }
            });
    this.fields = proxyFields;
}

From source file:net.bull.javamelody.SpringDataSourceBeanPostProcessor.java

private Object createProxy(final Object bean, final String beanName) {
    final InvocationHandler invocationHandler = new InvocationHandler() {
        /** {@inheritDoc} */
        @Override/*from   w w  w  .  j  a  v  a 2  s. c  o m*/
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            Object result = method.invoke(bean, args);
            if (result instanceof DataSource) {
                result = JdbcWrapper.SINGLETON.createDataSourceProxy(beanName, (DataSource) result);
            }
            return result;
        }
    };
    return JdbcWrapper.createProxy(bean, invocationHandler);
}

From source file:org.pegadi.client.ApplicationLauncher.java

/**
 * This method registers a listener for the Quit-menuitem on OS X application menu.
 * To avoid platform dependent compilation, reflection is utilized.
 * <p/>// ww  w  .  j av a  2s .  c o m
 * Basically what happens, is this:
 * <p/>
 * Application app = Application.getApplication();
 * app.addApplicationListener(new ApplicationAdapter() {
 * public void handleQuit(ApplicationEvent e) {
 * e.setHandled(false);
 * conditionalExit();
 * }
 * });
 */
private void registerOSXApplicationMenu() {

    try {
        ClassLoader cl = getClass().getClassLoader();

        // Create class-objects for the classes and interfaces we need
        final Class comAppleEawtApplicationClass = cl.loadClass("com.apple.eawt.Application");
        final Class comAppleEawtApplicationListenerInterface = cl
                .loadClass("com.apple.eawt.ApplicationListener");
        final Class comAppleEawtApplicationEventClass = cl.loadClass("com.apple.eawt.ApplicationEvent");
        final Method applicationEventSetHandledMethod = comAppleEawtApplicationEventClass
                .getMethod("setHandled", new Class[] { boolean.class });

        // Set up invocationhandler-object to recieve events from OS X application menu
        InvocationHandler handler = new InvocationHandler() {

            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                if (method.getName().equals("handleQuit")) {
                    applicationEventSetHandledMethod.invoke(args[0], new Object[] { Boolean.FALSE });
                    conditionalExit();
                }
                return null;
            }
        };

        // Create applicationlistener proxy
        Object applicationListenerProxy = Proxy.newProxyInstance(cl,
                new Class[] { comAppleEawtApplicationListenerInterface }, handler);

        // Get a real Application-object
        Method applicationGetApplicationMethod = comAppleEawtApplicationClass.getMethod("getApplication",
                new Class[0]);
        Object theApplicationObject = applicationGetApplicationMethod.invoke(null, new Object[0]);

        // Add the proxy application object as listener
        Method addApplicationListenerMethod = comAppleEawtApplicationClass.getMethod("addApplicationListener",
                new Class[] { comAppleEawtApplicationListenerInterface });
        addApplicationListenerMethod.invoke(theApplicationObject, new Object[] { applicationListenerProxy });

    } catch (Exception e) {
        log.info("we are not on OSX");
    }
}