001    /*
002     * Licensed to the Apache Software Foundation (ASF) under one or more
003     * contributor license agreements.  See the NOTICE file distributed with
004     * this work for additional information regarding copyright ownership.
005     * The ASF licenses this file to You under the Apache License, Version 2.0
006     * (the "License"); you may not use this file except in compliance with
007     * the License.  You may obtain a copy of the License at
008     *
009     *      http://www.apache.org/licenses/LICENSE-2.0
010     *
011     * Unless required by applicable law or agreed to in writing, software
012     * distributed under the License is distributed on an "AS IS" BASIS,
013     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014     * See the License for the specific language governing permissions and
015     * limitations under the License.
016     */
017    
018    package org.apache.commons.lang3.event;
019    
020    import java.lang.reflect.InvocationHandler;
021    import java.lang.reflect.InvocationTargetException;
022    import java.lang.reflect.Method;
023    import java.lang.reflect.Proxy;
024    import java.util.Arrays;
025    import java.util.HashSet;
026    import java.util.Set;
027    
028    import org.apache.commons.lang3.reflect.MethodUtils;
029    
030    /**
031     * Provides some useful event-based utility methods.
032     *
033     * @since 3.0
034     * @version $Id: EventUtils.java 1091072 2011-04-11 13:42:03Z mbenson $
035     */
036    public class EventUtils {
037    
038        /**
039         * Adds an event listener to the specified source.  This looks for an "add" method corresponding to the event
040         * type (addActionListener, for example).
041         * @param eventSource   the event source
042         * @param listenerType  the event listener type
043         * @param listener      the listener
044         * @param <L>           the event listener type
045         *
046         * @throws IllegalArgumentException if the object doesn't support the listener type
047         */
048        public static <L> void addEventListener(Object eventSource, Class<L> listenerType, L listener) {
049            try {
050                MethodUtils.invokeMethod(eventSource, "add" + listenerType.getSimpleName(), listener);
051            } catch (NoSuchMethodException e) {
052                throw new IllegalArgumentException("Class " + eventSource.getClass().getName()
053                        + " does not have a public add" + listenerType.getSimpleName()
054                        + " method which takes a parameter of type " + listenerType.getName() + ".");
055            } catch (IllegalAccessException e) {
056                throw new IllegalArgumentException("Class " + eventSource.getClass().getName()
057                        + " does not have an accessible add" + listenerType.getSimpleName ()
058                        + " method which takes a parameter of type " + listenerType.getName() + ".");
059            } catch (InvocationTargetException e) {
060                throw new RuntimeException("Unable to add listener.", e.getCause());
061            }
062        }
063    
064        /**
065         * Binds an event listener to a specific method on a specific object.
066         *
067         * @param <L>          the event listener type
068         * @param target       the target object
069         * @param methodName   the name of the method to be called
070         * @param eventSource  the object which is generating events (JButton, JList, etc.)
071         * @param listenerType the listener interface (ActionListener.class, SelectionListener.class, etc.)
072         * @param eventTypes   the event types (method names) from the listener interface (if none specified, all will be
073         *                     supported)
074         */
075        public static <L> void bindEventsToMethod(Object target, String methodName, Object eventSource,
076                Class<L> listenerType, String... eventTypes) {
077            final L listener = listenerType.cast(Proxy.newProxyInstance(target.getClass().getClassLoader(),
078                    new Class[] { listenerType }, new EventBindingInvocationHandler(target, methodName, eventTypes)));
079            addEventListener(eventSource, listenerType, listener);
080        }
081    
082        private static class EventBindingInvocationHandler implements InvocationHandler {
083            private final Object target;
084            private final String methodName;
085            private final Set<String> eventTypes;
086    
087            /**
088             * Creates a new instance of {@code EventBindingInvocationHandler}.
089             *
090             * @param target the target object for method invocations
091             * @param methodName the name of the method to be invoked
092             * @param eventTypes the names of the supported event types
093             */
094            EventBindingInvocationHandler(final Object target, final String methodName, String[] eventTypes) {
095                this.target = target;
096                this.methodName = methodName;
097                this.eventTypes = new HashSet<String>(Arrays.asList(eventTypes));
098            }
099    
100            /**
101             * Handles a method invocation on the proxy object.
102             *
103             * @param proxy the proxy instance
104             * @param method the method to be invoked
105             * @param parameters the parameters for the method invocation
106             * @return the result of the method call
107             * @throws Throwable if an error occurs
108             */
109            public Object invoke(final Object proxy, final Method method, final Object[] parameters) throws Throwable {
110                if (eventTypes.isEmpty() || eventTypes.contains(method.getName())) {
111                    if (hasMatchingParametersMethod(method)) {
112                        return MethodUtils.invokeMethod(target, methodName, parameters);
113                    } else {
114                        return MethodUtils.invokeMethod(target, methodName);
115                    }
116                }
117                return null;
118            }
119    
120            /**
121             * Checks whether a method for the passed in parameters can be found.
122             *
123             * @param method the listener method invoked
124             * @return a flag whether the parameters could be matched
125             */
126            private boolean hasMatchingParametersMethod(final Method method) {
127                return MethodUtils.getAccessibleMethod(target.getClass(), methodName, method.getParameterTypes()) != null;
128            }
129        }
130    }