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.toplink;
022    
023    import java.io.IOException;
024    import java.io.ObjectInput;
025    import java.io.ObjectOutput;
026    import java.lang.reflect.InvocationTargetException;
027    import java.lang.reflect.Type;
028    import java.util.ArrayList;
029    import java.util.HashMap;
030    import java.util.List;
031    import java.util.Map;
032    import java.util.Set;
033    
034    import javax.persistence.Embeddable;
035    import javax.persistence.Entity;
036    import javax.persistence.IdClass;
037    import javax.persistence.MappedSuperclass;
038    
039    import oracle.toplink.essentials.indirection.IndirectContainer;
040    import oracle.toplink.essentials.indirection.IndirectList;
041    import oracle.toplink.essentials.indirection.IndirectMap;
042    import oracle.toplink.essentials.indirection.IndirectSet;
043    import oracle.toplink.essentials.indirection.ValueHolderInterface;
044    
045    import org.granite.collections.BasicMap;
046    import org.granite.config.GraniteConfig;
047    import org.granite.context.GraniteContext;
048    import org.granite.logging.Logger;
049    import org.granite.messaging.amf.io.convert.Converters;
050    import org.granite.messaging.amf.io.util.ClassGetter;
051    import org.granite.messaging.amf.io.util.MethodProperty;
052    import org.granite.messaging.amf.io.util.Property;
053    import org.granite.messaging.amf.io.util.externalizer.DefaultExternalizer;
054    import org.granite.messaging.amf.io.util.externalizer.annotation.ExternalizedProperty;
055    import org.granite.messaging.persistence.AbstractExternalizablePersistentCollection;
056    import org.granite.messaging.persistence.ExternalizablePersistentList;
057    import org.granite.messaging.persistence.ExternalizablePersistentMap;
058    import org.granite.messaging.persistence.ExternalizablePersistentSet;
059    import org.granite.util.ClassUtil;
060    
061    /**
062     * @author William DRAI
063     */
064    public class TopLinkExternalizer extends DefaultExternalizer {
065    
066            private static final Logger log = Logger.getLogger(TopLinkExternalizer.class);
067    
068        @Override
069        public Object newInstance(String type, ObjectInput in)
070            throws IOException, ClassNotFoundException, InstantiationException, InvocationTargetException, IllegalAccessException {
071    
072            // If type is not an entity (@Embeddable for example), we don't read initialized/detachedState
073            // and we fall back to DefaultExternalizer behavior.
074            Class<?> clazz = ClassUtil.forName(type);
075            if (!isRegularEntity(clazz))
076                return super.newInstance(type, in);
077    
078            // Read initialized flag.
079            boolean initialized = ((Boolean)in.readObject()).booleanValue();
080            
081            // Read detached state.
082            @SuppressWarnings("unused")
083                    String detachedState = (String)in.readObject();
084            
085            // New or initialized entity.
086            if (initialized)
087                    return super.newInstance(type, in);
088            
089            // Pseudo-proxy (uninitialized entity).
090            Object id = in.readObject();
091            if (id != null && (!clazz.isAnnotationPresent(IdClass.class) || !clazz.getAnnotation(IdClass.class).value().equals(id.getClass())))
092                    throw new RuntimeException("Id for TopLink pseudo-proxy should be null or IdClass (" + type + ")");
093            
094            return new TopLinkValueHolder();
095        }
096    
097        @Override
098        public void readExternal(Object o, ObjectInput in) throws IOException, ClassNotFoundException, IllegalAccessException {
099            // Ignore TopLink proxies
100            if (o instanceof TopLinkValueHolder)
101                    return;
102            
103            // @Embeddable or others...
104            if (!isRegularEntity(o.getClass())) {
105                    log.debug("Delegating non regular entity reading to DefaultExternalizer...");
106                super.readExternal(o, in);
107            }
108            // Regural @Entity or @MappedSuperclass
109            else {
110                GraniteConfig config = GraniteContext.getCurrentInstance().getGraniteConfig();
111    
112                Converters converters = config.getConverters();
113                ClassGetter classGetter = config.getClassGetter();
114                Class<?> oClass = classGetter.getClass(o);
115    
116                List<Property> fields = findOrderedFields(oClass);
117                log.debug("Reading entity %s with fields %s", oClass.getName(), fields);
118                Map<String, Property> topLinkFields = new HashMap<String, Property>();
119                for (Property field : fields) {
120                    if (field.getType() instanceof Class<?> && ValueHolderInterface.class.isAssignableFrom((Class<?>)field.getType())) {
121                        topLinkFields.put(field.getName(), field);
122                    }
123                    else {
124                        Object value = in.readObject();
125    
126                        if (value instanceof ValueHolderInterface) {
127                            topLinkFields.get("_toplink_" + field.getName() + "_vh").setProperty(o, value, false);
128                        }
129                        else if (!(field instanceof MethodProperty && field.isAnnotationPresent(ExternalizedProperty.class))) { 
130                            if (value instanceof AbstractExternalizablePersistentCollection)
131                                value = newIndirectCollection((AbstractExternalizablePersistentCollection)value, field.getType());
132                            else
133                                value = converters.convert(value, field.getType());
134                            
135                            field.setProperty(o, value, false);
136                        }
137                    }
138                }
139            }
140        }
141        
142        protected IndirectContainer newIndirectCollection(AbstractExternalizablePersistentCollection value, Type target) {
143            final boolean initialized = value.isInitialized();
144                    final Object[] content = value.getContent();
145            
146                    IndirectContainer coll = null;
147                    if (value instanceof ExternalizablePersistentSet) {
148                if (initialized) {
149                    if (content != null) {
150                        Set<?> set = ((ExternalizablePersistentSet)value).getContentAsSet(target);
151                        coll = new IndirectSet(set);
152                    }
153                } 
154                else
155                    coll = new IndirectSet();
156            }
157                    else if (value instanceof ExternalizablePersistentList) {
158                    if (initialized) {
159                        if (content != null) {
160                        List<?> list = ((ExternalizablePersistentList)value).getContentAsList(target);
161                            coll = new IndirectList(list);
162                        }
163                    }
164                    else
165                        coll = new IndirectList();
166                    }
167                    else if (value instanceof ExternalizablePersistentMap) {
168                    if (initialized) {
169                        if (content != null) {
170                        Map<?, ?> map = ((ExternalizablePersistentMap)value).getContentAsMap(target);
171                            coll = new IndirectMap(map);
172                        }
173                    }
174                    else
175                        coll = new IndirectMap();
176                    }
177                    else {
178                            throw new RuntimeException("Illegal externalizable persitent class: " + value);
179                    }
180            
181            return coll;
182        }
183        
184    
185        @Override
186        public void writeExternal(Object o, ObjectOutput out) throws IOException, IllegalAccessException {
187    
188            ClassGetter classGetter = GraniteContext.getCurrentInstance().getGraniteConfig().getClassGetter();
189            Class<?> oClass = classGetter.getClass(o);
190    
191            if (o instanceof TopLinkProxy) {                
192                TopLinkProxy proxy = (TopLinkProxy)o;
193    
194                // Only write initialized flag, null detachedState & null id if proxy is uninitialized.
195                    log.debug("Writing uninitialized TopLink ValueHolder %s", proxy.getProxiedClass().getName());
196                    
197                    // Write initialized flag.
198                    out.writeObject(Boolean.FALSE);
199                    // Write detachedState.
200                out.writeObject(null);
201                    // Write id.
202                out.writeObject(null);
203    
204                return;
205            }
206    
207            if (!isRegularEntity(o.getClass())) { // @Embeddable or others...
208                    log.debug("Delegating non regular entity writing to DefaultExternalizer...");
209                super.writeExternal(o, out);
210            }
211            else {
212                    // Write initialized flag.
213                    out.writeObject(Boolean.TRUE);
214                    // Write detachedState.
215                out.writeObject(null);
216    
217                // Externalize entity fields.
218                List<Property> fields = findOrderedFields(oClass);
219                List<String> lazyFieldNames = new ArrayList<String>();
220                
221                log.debug("Writing entity %s with fields %s", o.getClass().getName(), fields);
222                for (Property field : fields) {
223                    if (!(field.getType() instanceof Class<?> && ValueHolderInterface.class.isAssignableFrom((Class<?>)field.getType()))) {
224                        if (lazyFieldNames.contains(field.getName())) {
225                            TopLinkProxy proxy = new TopLinkProxy((Class<?>)field.getType());
226                            out.writeObject(proxy);
227                        }
228                        else {
229                            Object value = field.getProperty(o);
230            
231                            // Persistent collections & maps.
232                            if (value instanceof IndirectContainer)
233                                    value = newExternalizableCollection((IndirectContainer)value);
234                            // Transient maps.
235                            else if (value instanceof Map<?, ?>)
236                                    value = BasicMap.newInstance((Map<?, ?>)value);
237                            
238                            out.writeObject(value);
239                        }
240                    }
241                    else {
242                        ValueHolderInterface vh = (ValueHolderInterface)field.getProperty(o);
243                        if (!vh.isInstantiated())
244                            lazyFieldNames.add(field.getName().substring("_toplink_".length(), field.getName().length()-3));
245                    }
246                }
247            }
248        }
249        
250        protected AbstractExternalizablePersistentCollection newExternalizableCollection(IndirectContainer value) {
251            AbstractExternalizablePersistentCollection coll = null;
252            boolean initialized = value.isInstantiated();
253            
254            if (value instanceof IndirectSet) {
255                coll = new ExternalizablePersistentSet(initialized ? ((IndirectSet)value).toArray() : null, initialized, false);
256            }
257            else if (value instanceof IndirectList) {
258                coll = new ExternalizablePersistentList(initialized ? ((IndirectList)value).toArray() : null, initialized, false);
259            }
260            else if (value instanceof IndirectMap) {
261                Object[] content = null;
262                
263                if (initialized) {
264                    content = new Object[((IndirectMap)value).size()];
265                    int index = 0;
266                    @SuppressWarnings("unchecked")
267                    Set<Map.Entry<?, ?>> entries = ((IndirectMap)value).entrySet();
268                    for (Map.Entry<?, ?> entry : entries)
269                        content[index++] = new Object[]{entry.getKey(), entry.getValue()};
270                }
271                
272                coll = new ExternalizablePersistentMap(content, initialized, false);
273            }
274            else {
275                throw new UnsupportedOperationException("Unsupported TopLink collection type: " + value);
276            }
277            
278            return coll;
279        }
280    
281        
282        @Override
283        public int accept(Class<?> clazz) {
284            return (
285                clazz.isAnnotationPresent(Entity.class) ||
286                clazz.isAnnotationPresent(MappedSuperclass.class) ||
287                clazz.isAnnotationPresent(Embeddable.class)
288            ) ? 1 : -1;
289        }
290    
291        protected boolean isRegularEntity(Class<?> clazz) {
292            return clazz.isAnnotationPresent(Entity.class) || clazz.isAnnotationPresent(MappedSuperclass.class);
293        }
294    }