001 /**
002 *
003 * Copyright 2004 Protique Ltd
004 *
005 * Licensed under the Apache License, Version 2.0 (the "License");
006 * you may not use this file except in compliance with the License.
007 * You may obtain a copy of the License at
008 *
009 * http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 *
017 **/
018 package org.activemq.transport.xstream;
019
020 import com.thoughtworks.xstream.XStream;
021 import org.activemq.io.TextWireFormat;
022 import org.activemq.io.WireFormat;
023 import org.activemq.message.Packet;
024
025 import javax.jms.JMSException;
026 import java.io.DataInput;
027 import java.io.DataOutput;
028 import java.io.IOException;
029
030 /**
031 * A {@link WireFormat} implementation which uses the
032 * <a href="http://xstream.codehaus.org/>XStream</a> library to marshall
033 * commands onto the wire
034 *
035 * @version $Revision$
036 */
037 public class XStreamWireFormat extends TextWireFormat {
038 private XStream xStream;
039
040 public Packet readPacket(DataInput in) throws IOException {
041 String text = in.readUTF();
042 return (Packet) getXStream().fromXML(text);
043 }
044
045 public Packet readPacket(int firstByte, DataInput in) throws IOException {
046 String text = in.readUTF();
047 return (Packet) getXStream().fromXML(text);
048 }
049
050 public Packet writePacket(Packet packet, DataOutput out) throws IOException, JMSException {
051 String text = getXStream().toXML(packet);
052 out.writeUTF(text);
053 return null;
054 }
055
056 public WireFormat copy() {
057 return new XStreamWireFormat();
058 }
059
060 public String toString(Packet packet) {
061 return getXStream().toXML(packet);
062 }
063
064 public Packet fromString(String xml) {
065 return (Packet) getXStream().fromXML(xml);
066 }
067
068 /**
069 * Can this wireformat process packets of this version
070 * @param version the version number to test
071 * @return true if can accept the version
072 */
073 public boolean canProcessWireFormatVersion(int version){
074 return true;
075 }
076
077 /**
078 * @return the current version of this wire format
079 */
080 public int getCurrentWireFormatVersion(){
081 return 1;
082 }
083
084 // Properties
085 //-------------------------------------------------------------------------
086 public XStream getXStream() {
087 if (xStream == null) {
088 xStream = createXStream();
089 }
090 return xStream;
091 }
092
093 public void setXStream(XStream xStream) {
094 this.xStream = xStream;
095 }
096
097 // Implementation methods
098 //-------------------------------------------------------------------------
099 protected XStream createXStream() {
100 return new XStream();
101 }
102 }