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.eclipselink;
022    
023    import java.io.IOException;
024    import java.io.ObjectInput;
025    import java.io.ObjectOutput;
026    import java.lang.reflect.Field;
027    import java.lang.reflect.InvocationTargetException;
028    import java.lang.reflect.Type;
029    import java.util.ArrayList;
030    import java.util.HashMap;
031    import java.util.List;
032    import java.util.Map;
033    import java.util.Set;
034    
035    import javax.persistence.Embeddable;
036    import javax.persistence.Entity;
037    import javax.persistence.IdClass;
038    import javax.persistence.MappedSuperclass;
039    
040    import org.eclipse.persistence.indirection.IndirectContainer;
041    import org.eclipse.persistence.indirection.IndirectList;
042    import org.eclipse.persistence.indirection.IndirectMap;
043    import org.eclipse.persistence.indirection.IndirectSet;
044    import org.eclipse.persistence.indirection.ValueHolderInterface;
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 EclipseLinkExternalizer extends DefaultExternalizer {
065    
066            private static final Logger log = Logger.getLogger(EclipseLinkExternalizer.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 EclipseLink pseudo-proxy should be null or IdClass (" + type + ")");
093            
094            return new EclipseLinkValueHolder();
095        }
096    
097        @Override
098        public void readExternal(Object o, ObjectInput in) throws IOException, ClassNotFoundException, IllegalAccessException {
099            // Ignore EclipseLink proxies
100            if (o instanceof EclipseLinkValueHolder)
101                    return;
102    
103            // @Embeddable or others...
104            if (!isRegularEntity(o.getClass()) && !isEmbeddable(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("_persistence_" + field.getName() + "_vh").setProperty(o, value, false);
128                        }
129                        else if (!(field instanceof MethodProperty && field.isAnnotationPresent(ExternalizedProperty.class, true))) { 
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        @Override
143            protected boolean isPropertyIgnored(Field field) {
144                    return field.getName().equals("_persistence_fetchGroup");
145            }
146        
147        
148        protected IndirectContainer newIndirectCollection(AbstractExternalizablePersistentCollection value, Type target) {
149            final boolean initialized = value.isInitialized();
150                    final Object[] content = value.getContent();
151            
152                    IndirectContainer coll = null;
153                    if (value instanceof ExternalizablePersistentSet) {
154                if (initialized) {
155                    if (content != null) {
156                                    Set<?> set = ((ExternalizablePersistentSet)value).getContentAsSet(target);
157                        coll = new IndirectSet(set);
158                    }
159                } 
160                else
161                    coll = new IndirectSet();
162            }
163                    else if (value instanceof ExternalizablePersistentList) {
164                    if (initialized) {
165                        if (content != null) {
166                            List<?> list = ((ExternalizablePersistentList)value).getContentAsList(target);
167                            coll = new IndirectList(list);
168                        }
169                    }
170                    else
171                        coll = new IndirectList();
172                    }
173                    else if (value instanceof ExternalizablePersistentMap) {
174                    if (initialized) {
175                        if (content != null) {
176                            Map<?, ?> map = ((ExternalizablePersistentMap)value).getContentAsMap(target);
177                            coll = new IndirectMap(map);
178                        }
179                    }
180                    else
181                        coll = new IndirectMap();
182                    }
183                    else {
184                            throw new RuntimeException("Illegal externalizable persitent class: " + value);
185                    }
186            
187            return coll;
188        }
189    
190        
191        @Override
192        public void writeExternal(Object o, ObjectOutput out) throws IOException, IllegalAccessException {
193    
194            ClassGetter classGetter = GraniteContext.getCurrentInstance().getGraniteConfig().getClassGetter();
195            Class<?> oClass = classGetter.getClass(o);
196    
197            if (o instanceof EclipseLinkProxy) {            
198                EclipseLinkProxy proxy = (EclipseLinkProxy)o;
199    
200                // Only write initialized flag, null detachedState & null id if proxy is uninitialized.
201                    String description = proxy.getProxiedClass().getName();
202                    log.debug("Writing uninitialized EclipseLink ValueHolder %s", description);
203                    
204                    // Write initialized flag.
205                    out.writeObject(Boolean.FALSE);
206                    // Write detachedState.
207                out.writeObject(null);
208                    // Write id.
209                out.writeObject(null);
210    
211                return;
212            }
213    
214            if (!isRegularEntity(o.getClass()) && !isEmbeddable(o.getClass())) { // @Embeddable or others...
215                    log.debug("Delegating non regular entity writing to DefaultExternalizer...");
216                super.writeExternal(o, out);
217            }
218            else {
219                    if (isRegularEntity(o.getClass())) {
220                            // Write initialized flag.
221                            out.writeObject(Boolean.TRUE);
222                            // Write detachedState.
223                        out.writeObject(null);
224                    }
225                       
226                // Externalize entity fields.
227                List<Property> fields = findOrderedFields(oClass);
228                List<String> lazyFieldNames = new ArrayList<String>();
229                
230                log.debug("Writing entity %s with fields %s", o.getClass().getName(), fields);
231                for (Property field : fields) {
232                    if (!(field.getType() instanceof Class<?> && ValueHolderInterface.class.isAssignableFrom((Class<?>)field.getType()))) {
233                        if (lazyFieldNames.contains(field.getName())) {
234                            EclipseLinkProxy proxy = new EclipseLinkProxy((Class<?>)field.getType());
235                            out.writeObject(proxy);
236                        }
237                        else {
238                            Object value = field.getProperty(o);
239            
240                            // Persistent collections & maps.
241                            if (value instanceof IndirectContainer)
242                                    value = newExternalizableCollection((IndirectContainer)value);
243                            // Transient maps.
244                            else if (value instanceof Map<?, ?>)
245                                    value = BasicMap.newInstance((Map<?, ?>)value);
246                            
247                            out.writeObject(value);
248                        }
249                    }
250                    else {
251                        ValueHolderInterface vh = (ValueHolderInterface)field.getProperty(o);
252                        if (vh != null && !vh.isInstantiated())
253                            lazyFieldNames.add(field.getName().substring("_persistence_".length(), field.getName().length()-3));
254                    }
255                }
256            }
257        }
258        
259        protected AbstractExternalizablePersistentCollection newExternalizableCollection(IndirectContainer value) {
260            AbstractExternalizablePersistentCollection coll = null;
261            boolean initialized = value.isInstantiated();
262            
263            if (value instanceof IndirectSet) {
264                coll = new ExternalizablePersistentSet(initialized ? ((IndirectSet)value).toArray() : null, initialized, false);
265            }
266            else if (value instanceof IndirectList) {
267                coll = new ExternalizablePersistentList(initialized ? ((IndirectList)value).toArray() : null, initialized, false);
268            }
269            else if (value instanceof IndirectMap) {
270                Object[] content = null;
271                
272                if (initialized) {
273                    content = new Object[((IndirectMap)value).size()];
274                    int index = 0;
275                    @SuppressWarnings("unchecked")
276                    Set<Map.Entry<?, ?>> entries = ((IndirectMap)value).entrySet();
277                    for (Map.Entry<?, ?> entry : entries)
278                        content[index++] = new Object[]{entry.getKey(), entry.getValue()};
279                }
280                
281                coll = new ExternalizablePersistentMap(content, initialized, false);
282            }
283            else {
284                throw new UnsupportedOperationException("Unsupported EclipseLink collection type: " + value);
285            }
286            
287            return coll;
288        }
289    
290        
291        @Override
292        public int accept(Class<?> clazz) {
293            return (
294                clazz.isAnnotationPresent(Entity.class) ||
295                clazz.isAnnotationPresent(MappedSuperclass.class) ||
296                clazz.isAnnotationPresent(Embeddable.class)
297            ) ? 1 : -1;
298        }
299    
300        protected boolean isRegularEntity(Class<?> clazz) {
301            return clazz.isAnnotationPresent(Entity.class) || clazz.isAnnotationPresent(MappedSuperclass.class);
302        }
303    
304        protected boolean isEmbeddable(Class<?> clazz) {
305            return clazz.isAnnotationPresent(Embeddable.class);
306        }
307    }