001 /*
002 GRANITE DATA SERVICES
003 Copyright (C) 2012 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.client.messaging.codec;
022
023 import java.io.ByteArrayInputStream;
024 import java.io.IOException;
025 import java.io.InputStream;
026 import java.io.OutputStream;
027
028 import org.granite.client.configuration.Configuration;
029 import org.granite.client.messaging.channel.Channel;
030 import org.granite.client.messaging.jmf.ClientSharedContextFactory;
031 import org.granite.messaging.jmf.JMFDeserializer;
032 import org.granite.messaging.jmf.JMFSerializer;
033 import org.granite.util.ContentType;
034
035 import flex.messaging.messages.Message;
036
037 /**
038 * @author Franck WOLFF
039 */
040 public class JMFAMF3MessagingCodec implements MessagingCodec<Message[]> {
041
042 public JMFAMF3MessagingCodec(Configuration config) {
043 }
044
045 @Override
046 public String getContentType() {
047 return ContentType.JMF_AMF.mimeType();
048 }
049
050 @Override
051 public void encode(Message[] messages, OutputStream output) throws IOException {
052 JMFSerializer serializer = new JMFSerializer(output, ClientSharedContextFactory.getInstance());
053 serializer.writeObject(messages);
054 }
055
056 @Override
057 public Message[] decode(InputStream input) throws IOException {
058 JMFDeserializer deserializer = new JMFDeserializer(input, ClientSharedContextFactory.getInstance());
059
060 Message[] messages = null;
061 try {
062 messages = (Message[])deserializer.readObject();
063 if (messages != null) {
064 for (Message message : messages) {
065 if (message != null && Boolean.TRUE.equals(message.getHeader(Channel.BYTEARRAY_BODY_HEADER))) {
066 byte[] body = (byte[])message.getBody();
067 deserializer = new JMFDeserializer(new ByteArrayInputStream(body), ClientSharedContextFactory.getInstance());
068 message.setBody(deserializer.readObject());
069 }
070 }
071 }
072 }
073 catch (ClassNotFoundException e) {
074 throw new IOException(e);
075 }
076
077 return (messages != null ? messages : new Message[0]);
078 }
079 }