blob: f2a1ac28a84faa5ac81b5e7b9ac08c627e0ce6c8 [file] [log] [blame]
David Reissd2a3e562008-03-02 06:29:16 +00001// 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
7package com.facebook.thrift;
8
9import java.io.ByteArrayInputStream;
10import java.io.UnsupportedEncodingException;
11
12import com.facebook.thrift.protocol.TBinaryProtocol;
13import com.facebook.thrift.protocol.TProtocol;
14import com.facebook.thrift.protocol.TProtocolFactory;
15import com.facebook.thrift.transport.TIOStreamTransport;
16import com.facebook.thrift.transport.TTransport;
17
18/**
19 * Generic utility for easily deserializing objects from a byte array or Java
20 * String.
21 *
22 * @author David Reiss <dreiss@facebook.com>
23 */
24public class TDeserializer {
25 private final TProtocolFactory protocolFactory_;
26
27 /**
28 * Create a new TDeserializer that uses the TBinaryProtocol by default.
29 */
30 public TDeserializer() {
31 this(new TBinaryProtocol.Factory());
32 }
33
34 /**
35 * Create a new TDeserializer. It will use the TProtocol specified by the
36 * factory that is passed in.
37 *
38 * @param protocolFactory Factory to create a protocol
39 */
40 public TDeserializer(TProtocolFactory protocolFactory) {
41 protocolFactory_ = protocolFactory;
42 }
43
44 /**
45 * Deserialize the Thrift object from a byte array.
46 *
47 * @param base The object to read into
48 * @param bytes The array to read from
49 */
50 public void deserialize(TBase base, byte[] bytes) throws TException {
51 base.read(
52 protocolFactory_.getProtocol(
53 new TIOStreamTransport(
54 new ByteArrayInputStream(bytes))));
55 }
56
57 /**
58 * Deserialize the Thrift object from a Java string, using a specified
59 * character set for decoding.
60 *
61 * @param base The object to read into
62 * @param data The string to read from
63 * @param charset Valid JVM charset
64 */
65 public void deserialize(TBase base, String data, String charset) throws TException {
66 try {
67 deserialize(base, data.getBytes(charset));
68 } catch (UnsupportedEncodingException uex) {
69 throw new TException("JVM DOES NOT SUPPORT ENCODING: " + charset);
70 }
71 }
72
73 /**
74 * Deerialize the Thrift object from a Java string, using the default JVM
75 * charset encoding.
76 *
77 * @param base The object to read into
78 * @param data The string to read from
79 * @return Serialized object as a String
80 */
81 public void toString(TBase base, String data) throws TException {
82 deserialize(base, data.getBytes());
83 }
84}
85