001/*
002  GRANITE DATA SERVICES
003  Copyright (C) 2013 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
021package org.granite.messaging.jmf.codec.std.impl;
022
023import java.io.Externalizable;
024import java.io.IOException;
025import java.io.NotSerializableException;
026import java.io.OutputStream;
027import java.io.Serializable;
028import java.lang.reflect.Field;
029import java.lang.reflect.InvocationTargetException;
030import java.lang.reflect.Proxy;
031import java.util.List;
032
033import org.granite.messaging.jmf.CodecRegistry;
034import org.granite.messaging.jmf.DumpContext;
035import org.granite.messaging.jmf.InputContext;
036import org.granite.messaging.jmf.JMFEncodingException;
037import org.granite.messaging.jmf.OutputContext;
038import org.granite.messaging.jmf.codec.ExtendedObjectCodec;
039import org.granite.messaging.jmf.codec.StandardCodec;
040import org.granite.messaging.jmf.codec.std.ObjectCodec;
041
042/**
043 * @author Franck WOLFF
044 */
045public class ObjectCodecImpl extends AbstractIntegerStringCodec<Object> implements ObjectCodec {
046
047        protected static final StringTypeHandler TYPE_HANDLER = new StringTypeHandler() {
048
049                public int type(IntegerComponents ics, boolean reference) {
050                        if (reference)
051                                return 0x40 | (ics.length << 4) | JMF_OBJECT;
052                        return (ics.length << 4) | JMF_OBJECT;
053                }
054
055                public int indexOrLengthBytesCount(int parameterizedJmfType) {
056                        return (parameterizedJmfType >> 4) & 0x03;
057                }
058
059                public boolean isReference(int parameterizedJmfType) {
060                        return (parameterizedJmfType & 0x40) != 0;
061                }
062        };
063
064        public int getObjectType() {
065                return JMF_OBJECT;
066        }
067
068        public boolean canEncode(Object v) {
069                Class<?> cls = v.getClass();
070                return !cls.isArray() && !cls.isEnum() && !(v instanceof Class);
071        }
072
073        public void encode(OutputContext ctx, Object v) throws IOException, IllegalAccessException {
074                final OutputStream os = ctx.getOutputStream();
075                
076                int indexOfStoredObject = ctx.indexOfStoredObjects(v);
077                if (indexOfStoredObject >= 0) {
078                        IntegerComponents ics = intComponents(indexOfStoredObject);
079                        os.write(0x80 | (ics.length << 4) | JMF_OBJECT);
080                        writeIntData(ctx, ics);
081                }
082                else {                  
083                        if (!(v instanceof Serializable))
084                                throw new NotSerializableException(v.getClass().getName());
085                        
086                        ctx.addToStoredObjects(v);
087                        
088                        ExtendedObjectCodec extendedCodec = ctx.getSharedContext().getCodecRegistry().findExtendedEncoder(ctx, v);
089                        
090                        String className = (
091                                extendedCodec != null ?
092                                extendedCodec.getEncodedClassName(ctx, v) :
093                                ctx.getAlias(v.getClass().getName())
094                        );
095                        
096                        writeString(ctx, className, TYPE_HANDLER);
097                        
098                        if (extendedCodec != null)
099                                extendedCodec.encode(ctx, v);
100                        else if (v instanceof Externalizable && !Proxy.isProxyClass(v.getClass()))
101                                ((Externalizable)v).writeExternal(ctx);
102                        else
103                                encodeSerializable(ctx, (Serializable)v);
104
105                        os.write(JMF_OBJECT_END);
106                }
107        }
108        
109        protected void encodeSerializable(OutputContext ctx, Serializable v) throws IOException, IllegalAccessException {
110                List<Field> fields = ctx.getReflection().findSerializableFields(v.getClass());
111                for (Field field : fields)
112                        ctx.getAndWriteField(v, field);
113        }
114        
115        public Object decode(InputContext ctx, int parameterizedJmfType)
116                throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException,
117                InvocationTargetException, SecurityException, NoSuchMethodException {
118                
119                final CodecRegistry codecRegistry = ctx.getSharedContext().getCodecRegistry();
120                
121                int jmfType = codecRegistry.extractJmfType(parameterizedJmfType);
122                if (jmfType != JMF_OBJECT)
123                        throw newBadTypeJMFEncodingException(jmfType, parameterizedJmfType);
124
125                Object v = null;
126
127                int indexOrLength = readIntData(ctx, (parameterizedJmfType >> 4) & 0x03, false);
128                if ((parameterizedJmfType & 0x80) != 0)
129                        v = ctx.getSharedObject(indexOrLength);
130                else {
131                        String className = readString(ctx, parameterizedJmfType, indexOrLength, TYPE_HANDLER);
132                        
133                        ExtendedObjectCodec extendedCodec = codecRegistry.findExtendedDecoder(ctx, className);
134                        if (extendedCodec != null) {
135                                className = extendedCodec.getDecodedClassName(ctx, className);
136                                int index = ctx.addUnresolvedSharedObject(className);
137                                v = extendedCodec.newInstance(ctx, className);
138                                ctx.setUnresolvedSharedObject(index, v);
139                                extendedCodec.decode(ctx, v);
140                        }
141                        else {
142                                className = ctx.getAlias(className);
143                                Class<?> cls = ctx.getSharedContext().getReflection().loadClass(className);
144                                
145                                if (!Serializable.class.isAssignableFrom(cls))
146                                        throw new NotSerializableException(cls.getName());
147                                
148                                if (Externalizable.class.isAssignableFrom(cls)) {
149                                        v = ctx.getReflection().newInstance(cls);
150                                        ctx.addSharedObject(v);
151                                        ((Externalizable)v).readExternal(ctx);
152                                }
153                                else {
154                                        v = ctx.getReflection().newInstance(cls);
155                                        ctx.addSharedObject(v);
156                                        decodeSerializable(ctx, (Serializable)v);
157                                }
158                        }
159                        
160                        int mark = ctx.safeRead();
161                        if (mark != JMF_OBJECT_END)
162                                throw new JMFEncodingException("Not a Object end marker: " + mark);
163                }
164                
165                return v;
166        }
167        
168        protected void decodeSerializable(InputContext ctx, Serializable v)
169                throws IOException, ClassNotFoundException, IllegalAccessException {
170
171                List<Field> fields = ctx.getReflection().findSerializableFields(v.getClass());
172                for (Field field : fields)
173                        ctx.readAndSetField(v, field);
174        }
175
176        public void dump(DumpContext ctx, int parameterizedJmfType) throws IOException {
177                final CodecRegistry codecRegistry = ctx.getSharedContext().getCodecRegistry();
178
179                int jmfType = codecRegistry.extractJmfType(parameterizedJmfType);
180                
181                if (jmfType != JMF_OBJECT)
182                        throw newBadTypeJMFEncodingException(jmfType, parameterizedJmfType);
183
184                int indexOrLength = readIntData(ctx, (parameterizedJmfType >> 4) & 0x03, false);
185                
186                if ((parameterizedJmfType & 0x80) != 0) {
187                        String className = (String)ctx.getSharedObject(indexOrLength);
188                        ctx.indentPrintLn("<" + className + "@" + indexOrLength + ">");
189                }
190                else {
191                        String className = readString(ctx, parameterizedJmfType, indexOrLength, TYPE_HANDLER);
192                        int indexOfStoredObject = ctx.addSharedObject(className);
193                        ctx.indentPrintLn(className + "@" + indexOfStoredObject + " {");
194                        ctx.incrIndent(1);
195                        
196                        while ((parameterizedJmfType = ctx.safeRead()) != JMF_OBJECT_END) {
197                                jmfType = codecRegistry.extractJmfType(parameterizedJmfType);
198                                StandardCodec<?> codec = codecRegistry.getCodec(jmfType);
199                                
200                                if (codec == null)
201                                        throw new JMFEncodingException("No codec for JMF type: " + jmfType);
202                                
203                                codec.dump(ctx, parameterizedJmfType);
204                        }
205                        
206                        ctx.incrIndent(-1);
207                        ctx.indentPrintLn("}");
208                }
209        }
210}