001/**
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  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 */
017package org.apache.activemq.transport.util;
018
019import java.io.DataInput;
020import java.io.DataInputStream;
021import java.io.DataOutput;
022import java.io.DataOutputStream;
023import java.io.IOException;
024import java.io.Reader;
025
026import org.apache.activemq.util.ByteArrayInputStream;
027import org.apache.activemq.util.ByteArrayOutputStream;
028import org.apache.activemq.util.ByteSequence;
029import org.apache.activemq.wireformat.WireFormat;
030
031/**
032 * Adds the extra methods available to text based wire format implementations
033 *
034 *
035 */
036public abstract class TextWireFormat implements WireFormat {
037
038    public abstract Object unmarshalText(String text) throws IOException;
039
040    public abstract Object unmarshalText(Reader reader) throws IOException;
041
042    public abstract String marshalText(Object command) throws IOException;
043
044    public void marshal(Object command, DataOutput out) throws IOException {
045        String text = marshalText(command);
046        byte[] utf8 = text.getBytes("UTF-8");
047        out.writeInt(utf8.length);
048        out.write(utf8);
049    }
050
051    public Object unmarshal(DataInput in) throws IOException {
052        int length = in.readInt();
053        byte[] utf8 = new byte[length];
054        in.readFully(utf8);
055        String text = new String(utf8, "UTF-8");
056        return unmarshalText(text);
057    }
058
059    public ByteSequence marshal(Object command) throws IOException {
060        ByteArrayOutputStream baos = new ByteArrayOutputStream();
061        DataOutputStream dos = new DataOutputStream(baos);
062        marshal(command, dos);
063        dos.close();
064        return baos.toByteSequence();
065    }
066
067    public Object unmarshal(ByteSequence packet) throws IOException {
068        ByteArrayInputStream stream = new ByteArrayInputStream(packet);
069        DataInputStream dis = new DataInputStream(stream);
070        return unmarshal(dis);
071    }
072
073    public boolean inReceive() {
074        // TODO Implement for inactivity monitor
075        return false;
076    }
077
078}