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.hibernate4;
022    
023    import java.io.Serializable;
024    import java.lang.reflect.Field;
025    import java.lang.reflect.Method;
026    import java.lang.reflect.Type;
027    import java.util.concurrent.ConcurrentHashMap;
028    
029    import javax.persistence.EmbeddedId;
030    import javax.persistence.Id;
031    
032    import org.granite.config.GraniteConfig;
033    import org.granite.context.GraniteContext;
034    import org.granite.messaging.service.ServiceException;
035    import org.granite.util.TypeUtil;
036    import org.granite.util.Introspector;
037    import org.granite.util.PropertyDescriptor;
038    import org.hibernate.engine.spi.SessionImplementor;
039    import org.hibernate.proxy.HibernateProxy;
040    import org.hibernate.type.CompositeType;
041    
042    /**
043     * @author Franck WOLFF
044     */
045    public class ProxyFactory {
046    
047        private static final Class<?>[] INTERFACES = new Class<?>[]{HibernateProxy.class};
048        private static final Class<?>[] SINGLE_OBJECT_PARAMS = new Class<?>[]{Object.class};
049        private static final Method OBJECT_EQUALS;
050        static {
051            try {
052                    OBJECT_EQUALS = Object.class.getMethod("equals", SINGLE_OBJECT_PARAMS);
053            }
054            catch (Exception e) {
055                    throw new ExceptionInInitializerError(e);
056            }
057        }
058    
059        protected final ConcurrentHashMap<Class<?>, Object[]> identifierInfos = new ConcurrentHashMap<Class<?>, Object[]>();
060    
061        private final Method getProxyFactory;
062        private final Method getProxy;
063        private final boolean classOverridesEqualsParameter;
064    
065        public ProxyFactory(String initializerClassName) {
066            try {
067                // Get proxy methods: even if CGLIB/Javassist LazyInitializer implementations share a common
068                    // superclass, getProxyFactory/getProxy methods are declared as static in each inherited
069                    // class with the same signature.
070                Class<?> initializerClass = TypeUtil.forName(initializerClassName);
071                getProxyFactory = initializerClass.getMethod("getProxyFactory", new Class[] { Class.class, Class[].class });
072                
073                // Hibernate 4.0.1 has an extra boolean parameter in last position: classOverridesEquals.
074                Method getProxy = null;
075                boolean classOverridesEqualsParameter = false;
076                try {
077                        getProxy = initializerClass.getMethod("getProxy", new Class[]{
078                            Class.class, String.class, Class.class, Class[].class, Method.class, Method.class,
079                            CompositeType.class, Serializable.class, SessionImplementor.class
080                        });
081                }
082                catch (NoSuchMethodException e) {
083                    getProxy = initializerClass.getMethod("getProxy", new Class[]{
084                            Class.class, String.class, Class.class, Class[].class, Method.class, Method.class,
085                        CompositeType.class, Serializable.class, SessionImplementor.class, Boolean.TYPE
086                    });
087                    classOverridesEqualsParameter = true;
088                }
089                this.getProxy = getProxy;
090                this.classOverridesEqualsParameter = classOverridesEqualsParameter;
091            } 
092            catch (Exception e) {
093                throw new ServiceException("Could not introspect initializer class: " + initializerClassName, e);
094            }
095        }
096    
097        public HibernateProxy getProxyInstance(String persistentClassName, String entityName, Serializable id) {
098            try {
099                // Get ProxyFactory.
100                Class<?> persistentClass = TypeUtil.forName(persistentClassName);
101                Class<?> factory = (Class<?>)getProxyFactory.invoke(null, new Object[] { persistentClass, INTERFACES });
102    
103                // Convert id (if necessary).
104                Object[] identifierInfo = getIdentifierInfo(persistentClass);
105                Type identifierType = (Type)identifierInfo[0];
106                Method identifierGetter = (Method)identifierInfo[1];
107                if (id == null || !identifierType.equals(id.getClass())) {
108                    GraniteConfig config = GraniteContext.getCurrentInstance().getGraniteConfig();
109                    id = (Serializable)config.getConverters().convert(id, identifierType);
110                }
111    
112                // Get Proxy (with or without the extra parameter classOverridesEquals)
113                if (classOverridesEqualsParameter) {
114                    return (HibernateProxy)getProxy.invoke(null, new Object[]{
115                            factory, entityName, persistentClass, INTERFACES, identifierGetter, null, null, id, null, overridesEquals(persistentClass)});
116                }
117                return (HibernateProxy)getProxy.invoke(null, new Object[] { factory, entityName, persistentClass, INTERFACES, identifierGetter, null, null, id, null });
118            } 
119            catch (Exception e) {
120                throw new ServiceException("Error with proxy description: " + persistentClassName + '/' + entityName + " and id: " + id, e);
121            }
122        }
123        
124        protected boolean overridesEquals(Class<?> persistentClass) {
125            try {
126                    return !OBJECT_EQUALS.equals(persistentClass.getMethod("equals", SINGLE_OBJECT_PARAMS));
127            }
128            catch (Exception e) {
129                    return false; // should never happen unless persistentClass is an interface...
130            }
131        }
132    
133        protected Object[] getIdentifierInfo(Class<?> persistentClass) {
134    
135            Object[] info = identifierInfos.get(persistentClass);
136            if (info != null)
137                return info;
138    
139            Type type = null;
140            Method getter = null;
141            for (Class<?> clazz = persistentClass; clazz != Object.class && clazz != null; clazz = clazz.getSuperclass()) {
142                for (Field field : clazz.getDeclaredFields()) {
143                    if (field.isAnnotationPresent(Id.class) || field.isAnnotationPresent(EmbeddedId.class)) {
144                        type = field.getGenericType();
145                        break;
146                    }
147                }
148            }
149    
150            if (type == null) {
151                PropertyDescriptor[] propertyDescriptors = Introspector.getPropertyDescriptors(persistentClass);
152    
153                for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
154                    Method method = propertyDescriptor.getReadMethod();
155                    if (method != null && (
156                            method.isAnnotationPresent(Id.class) ||
157                            method.isAnnotationPresent(EmbeddedId.class))) {
158                        type = method.getGenericReturnType();
159                        getter = method;
160                        break;
161                    }
162                    method = propertyDescriptor.getWriteMethod();
163                    if (method != null && (
164                            method.isAnnotationPresent(Id.class) ||
165                            method.isAnnotationPresent(EmbeddedId.class))) {
166                        type = method.getGenericParameterTypes()[0];
167                        break;
168                    }
169                }
170            }
171    
172            if (type != null) {
173                    info = new Object[] { type, getter };
174                Object[] previousInfo = identifierInfos.putIfAbsent(persistentClass, info);
175                if (previousInfo != null)
176                    info = previousInfo; // should be the same...
177                return info;
178            }
179    
180            throw new IllegalArgumentException("Could not find id in: " + persistentClass);
181        }
182    }