001    /*
002      GRANITE DATA SERVICES
003      Copyright (C) 2011 GRANITE DATA SERVICES S.A.S.
004    
005      This file is part of Granite Data Services.
006    
007      Granite Data Services is free software; you can redistribute it and/or modify
008      it under the terms of the GNU Library General Public License as published by
009      the Free Software Foundation; either version 2 of the License, or (at your
010      option) any later version.
011    
012      Granite Data Services is distributed in the hope that it will be useful, but
013      WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
014      FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License
015      for more details.
016    
017      You should have received a copy of the GNU Library General Public License
018      along with this library; if not, see <http://www.gnu.org/licenses/>.
019    */
020    
021    package org.granite.messaging.service;
022    
023    import java.lang.reflect.Method;
024    import java.lang.reflect.ParameterizedType;
025    import java.lang.reflect.Type;
026    import java.lang.reflect.TypeVariable;
027    import java.util.ArrayList;
028    import java.util.Arrays;
029    import java.util.List;
030    
031    import org.granite.config.GraniteConfig;
032    import org.granite.config.flex.Destination;
033    import org.granite.context.GraniteContext;
034    import org.granite.logging.Logger;
035    import org.granite.messaging.amf.io.convert.Converter;
036    import org.granite.messaging.amf.io.convert.Converters;
037    import org.granite.messaging.service.annotations.IgnoredMethod;
038    import org.granite.messaging.service.annotations.RemoteDestination;
039    import org.granite.util.StringUtil;
040    
041    import flex.messaging.messages.Message;
042    
043    /**
044     * @author Franck WOLFF
045     * @author Pedro GONCALVES
046     */
047    public class DefaultMethodMatcher implements MethodMatcher {
048            
049            private static final Logger log = Logger.getLogger(DefaultMethodMatcher.class);
050    
051            
052        public ServiceInvocationContext findServiceMethod(
053            Message message,
054            Destination destination,
055            Object service,
056            String methodName,
057            Object[] params) throws NoSuchMethodException {
058    
059            GraniteConfig config = GraniteContext.getCurrentInstance().getGraniteConfig();
060            Converters converters = config.getConverters();
061    
062            Class<?> serviceClass = service.getClass();
063            Type serviceClassGenericType = getGenericType(serviceClass);
064    
065            MatchingMethod match = null;
066            if (params == null || params.length == 0)
067                match = new MatchingMethod(serviceClass.getMethod(methodName, (Class[])null), null);
068            else {
069                List<MatchingMethod> matchingMethods = new ArrayList<MatchingMethod>();
070                
071                List<Method> methods = new ArrayList<Method>();
072                for (Class<?> serviceInterface : serviceClass.getInterfaces())
073                    methods.addAll(Arrays.asList(serviceInterface.getMethods()));
074                
075                methods.addAll(Arrays.asList(serviceClass.getMethods()));
076                
077                for (Method method : methods) {
078    
079                    if (!methodName.equals(method.getName()))
080                        continue;
081    
082                    Type[] paramTypes = method.getGenericParameterTypes();
083                    if (paramTypes.length != params.length)
084                        continue;
085                    
086                    // Methods marked with @IgnoredMethod cannot be called remotely
087                    if (method.isAnnotationPresent(IgnoredMethod.class))
088                            continue;
089                    
090                    if (serviceClassGenericType != null)
091                        findAndChange(paramTypes, serviceClassGenericType);
092    
093                    Converter[] convertersArray = getConvertersArray(converters, params, paramTypes);
094                    if (convertersArray != null)
095                        matchingMethods.add(new MatchingMethod(method, convertersArray));
096                }
097                
098                if (matchingMethods.size() == 1)
099                    match = matchingMethods.get(0);
100                else if (matchingMethods.size() > 1) {
101                    // Multiple matches found
102                    match = resolveMatchingMethod(matchingMethods, serviceClass);
103                }
104            }
105    
106            if (match == null)
107                throw new NoSuchMethodException(serviceClass.getName() + '.' + methodName + StringUtil.toString(params));
108    
109            params = convert(match.convertersArray, params, match.serviceMethod.getGenericParameterTypes());
110    
111            return new ServiceInvocationContext(message, destination, service, match.serviceMethod, params);
112        }
113    
114        protected Converter[] getConvertersArray(Converters converters, Object[] values, Type[] targetTypes) {
115            Converter[] convertersArray = new Converter[values.length];
116            for (int i = 0; i < values.length; i++) {
117                convertersArray[i] = converters.getConverter(values[i], targetTypes[i]);
118                if (convertersArray[i] == null)
119                    return null;
120            }
121            return convertersArray;
122        }
123    
124        protected Object[] convert(Converter[] convertersArray, Object[] values, Type[] targetTypes) {
125            if (values.length > 0) {
126                for (int i = 0; i < convertersArray.length; i++)
127                    values[i] = convertersArray[i].convert(values[i], targetTypes[i]);
128            }
129            return values;
130        }
131        
132        protected MatchingMethod resolveMatchingMethod(List<MatchingMethod> methods, Class<?> serviceClass) {
133    
134            // Prefer methods of interfaces/classes marked with @RemoteDestination
135            for (MatchingMethod m : methods) {
136                if (m.serviceMethod.getDeclaringClass().isAnnotationPresent(RemoteDestination.class))
137                    return m;
138            }
139            
140            // Then prefer method declared by the serviceClass (with EJBs, we have always 2 methods, one in the interface,
141            // the other in the proxy, and the @RemoteDestination annotation cannot be find on the proxy class even
142            // it is present on the original class).
143            List<MatchingMethod> serviceClassMethods = new ArrayList<MatchingMethod>();
144            for (MatchingMethod m : methods) {
145                if (m.serviceMethod.getDeclaringClass().equals(serviceClass))
146                    serviceClassMethods.add(m);
147            }
148            if (serviceClassMethods.size() == 1)
149                    return serviceClassMethods.get(0);
150            
151            log.warn("Ambiguous method match for " + methods.get(0).serviceMethod.getName() + ", selecting first found " + methods.get(0).serviceMethod);        
152            return methods.get(0);
153        }
154        
155        /**
156         * If there is only one TypeVariable in method's argument list, it will be replaced
157         * by the type of the superclass of the service.
158         */
159        protected boolean findAndChange(Type[] paramTypes, Type superType) {
160            int idx = -1;
161            boolean find = false;
162            for (int j = 0; j < paramTypes.length; j++) {
163                Type type = paramTypes[j];
164               
165                if (type instanceof TypeVariable<?>) {
166                    if (!find) {
167                        idx = j;
168                        find = true;
169                    } else {
170                        throw new RuntimeException("There's two variable types.");
171                    }
172                }
173            }
174           
175            if (find)
176                paramTypes[idx] = superType;
177           
178            return find;
179        }
180       
181        /**
182         * Returns actual type argument of a given class.
183         */
184        protected Type getGenericType(Class<?> clazz) {
185            try {
186                ParameterizedType genericSuperclass = (ParameterizedType)clazz.getGenericSuperclass();
187                Type[] actualTypeArguments = genericSuperclass.getActualTypeArguments();
188                if (actualTypeArguments != null && actualTypeArguments.length == 1)
189                    return actualTypeArguments[0];
190            } catch (Exception e) {
191                    // fallback...
192            }
193            return null;
194        }
195        
196        private static class MatchingMethod {
197            
198            public final Method serviceMethod;
199            public final Converter[] convertersArray;
200    
201            public MatchingMethod(Method serviceMethod, Converter[] convertersArray) {
202                            this.serviceMethod = serviceMethod;
203                            this.convertersArray = convertersArray;
204                    }
205    
206                    @Override
207                    public String toString() {
208                            return "MatchingMethod {serviceMethod=" + serviceMethod + ", convertersArray=" + (convertersArray != null ? Arrays.toString(convertersArray) : "[]") + "}";
209                    }
210        }
211    }