38
38
import java .util .function .Function ;
39
39
import java .util .regex .Matcher ;
40
40
import java .util .regex .Pattern ;
41
+ import org .apache .thrift .TBase ;
42
+ import org .apache .thrift .TDeserializer ;
43
+ import org .apache .thrift .TSerializer ;
44
+ import org .apache .thrift .protocol .TJSONProtocol ;
41
45
import org .slf4j .Logger ;
42
46
import org .slf4j .LoggerFactory ;
43
47
44
48
/**
45
49
* Implements conversion through GSON JSON processor. To extend use {@link
46
- * JsonDataConverter(Function)} constructor.
50
+ * JsonDataConverter(Function)} constructor. Thrift structures are converted using {@link
51
+ * TJSONProtocol}. When using thrift only one argument of a method is expected.
47
52
*
48
53
* @author fateev
49
54
*/
@@ -113,7 +118,12 @@ public byte[] toData(Object... values) throws DataConverterException {
113
118
}
114
119
try {
115
120
if (values .length == 1 ) {
116
- String json = gson .toJson (values [0 ]);
121
+ Object value = values [0 ];
122
+ // Serialize thrift objects using Thrift serializer
123
+ if (value instanceof TBase ) {
124
+ return newThriftSerializer ().toString ((TBase ) value ).getBytes (StandardCharsets .UTF_8 );
125
+ }
126
+ String json = gson .toJson (value );
117
127
return json .getBytes (StandardCharsets .UTF_8 );
118
128
}
119
129
String json = gson .toJson (values );
@@ -129,6 +139,12 @@ public <T> T fromData(byte[] content, Class<T> valueType) throws DataConverterEx
129
139
return null ;
130
140
}
131
141
try {
142
+ // Deserialize thrift values.
143
+ if (TBase .class .isAssignableFrom (valueType )) {
144
+ T instance = valueType .getConstructor ().newInstance ();
145
+ newThriftDeserializer ().deserialize ((TBase ) instance , content );
146
+ return instance ;
147
+ }
132
148
return gson .fromJson (new String (content , StandardCharsets .UTF_8 ), valueType );
133
149
} catch (Exception e ) {
134
150
throw new DataConverterException (content , e );
@@ -165,6 +181,7 @@ public Object[] fromDataArray(byte[] content, Class<?>... valueType)
165
181
* <p>Implementation idea is based on https://github.com/google/gson/issues/43
166
182
*/
167
183
private static class ThrowableTypeAdapterFactory implements TypeAdapterFactory {
184
+
168
185
@ Override
169
186
public <T > TypeAdapter <T > create (Gson gson , TypeToken <T > typeToken ) {
170
187
// Special handling of fields of DataConverter type.
@@ -307,4 +324,12 @@ private static StackTraceElement parseStackTraceElement(String line) {
307
324
}
308
325
return new StackTraceElement (declaringClass , methodName , fileName , lineNumber );
309
326
}
327
+
328
+ private static TSerializer newThriftSerializer () {
329
+ return new TSerializer (new TJSONProtocol .Factory ());
330
+ }
331
+
332
+ private static TDeserializer newThriftDeserializer () {
333
+ return new TDeserializer (new TJSONProtocol .Factory ());
334
+ }
310
335
}
0 commit comments