Mark Slee | 844ac12 | 2007-11-27 08:38:52 +0000 | [diff] [blame] | 1 | // Copyright (c) 2006- Facebook |
| 2 | // Distributed under the Thrift Software License |
| 3 | // |
| 4 | // See accompanying file LICENSE or visit the Thrift site at: |
| 5 | // http://developers.facebook.com/thrift/ |
| 6 | |
| 7 | package com.facebook.thrift; |
| 8 | |
| 9 | import java.io.ByteArrayOutputStream; |
| 10 | import java.io.UnsupportedEncodingException; |
| 11 | |
| 12 | import com.facebook.thrift.protocol.TBinaryProtocol; |
| 13 | import com.facebook.thrift.protocol.TProtocol; |
| 14 | import com.facebook.thrift.protocol.TProtocolFactory; |
| 15 | import com.facebook.thrift.transport.TIOStreamTransport; |
| 16 | import com.facebook.thrift.transport.TTransport; |
| 17 | |
| 18 | /** |
| 19 | * Generic utility for easily serializing objects into a byte array. |
| 20 | * |
| 21 | * @author Mark Slee <mcslee@facebook.com> |
| 22 | */ |
| 23 | public class TSerializer { |
| 24 | |
| 25 | private static class TByteArrayTransport extends TIOStreamTransport { |
| 26 | |
| 27 | private final ByteArrayOutputStream baos_ = new ByteArrayOutputStream(); |
| 28 | |
| 29 | public TByteArrayTransport() { |
| 30 | outputStream_ = baos_; |
| 31 | } |
| 32 | |
| 33 | public byte[] get() { |
| 34 | return baos_.toByteArray(); |
| 35 | } |
| 36 | |
| 37 | public void reset() { |
| 38 | baos_.reset(); |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | private TProtocol protocol_; |
| 43 | |
| 44 | private final TByteArrayTransport transport_ = new TByteArrayTransport(); |
| 45 | |
| 46 | public TSerializer() { |
| 47 | this(new TBinaryProtocol.Factory()); |
| 48 | } |
| 49 | |
| 50 | public TSerializer(TProtocolFactory protocolFactory) { |
| 51 | protocol_ = protocolFactory.getProtocol(transport_); |
| 52 | } |
| 53 | |
| 54 | public byte[] serialize(TBase base) throws TException { |
| 55 | transport_.reset(); |
| 56 | base.write(protocol_); |
| 57 | byte[] data = transport_.get(); |
| 58 | return data; |
| 59 | } |
| 60 | |
| 61 | public String toString(TBase base, String charset) throws TException { |
| 62 | try { |
| 63 | return new String(serialize(base), charset); |
| 64 | } catch (UnsupportedEncodingException uex) { |
| 65 | throw new TException("JVM DOES NOT SUPPORT ENCODING"); |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | public String toString(TBase base) throws TException { |
| 70 | return new String(serialize(base)); |
| 71 | } |
| 72 | } |
| 73 | |