1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.shardingsphere.data.pipeline.cdc.client.util;
19
20 import com.google.protobuf.Any;
21 import com.google.protobuf.BoolValue;
22 import com.google.protobuf.BytesValue;
23 import com.google.protobuf.DoubleValue;
24 import com.google.protobuf.Empty;
25 import com.google.protobuf.FloatValue;
26 import com.google.protobuf.Int32Value;
27 import com.google.protobuf.Int64Value;
28 import com.google.protobuf.InvalidProtocolBufferException;
29 import com.google.protobuf.StringValue;
30 import com.google.protobuf.Struct;
31 import com.google.protobuf.UInt32Value;
32 import com.google.protobuf.UInt64Value;
33 import com.google.protobuf.util.JsonFormat;
34 import lombok.AccessLevel;
35 import lombok.NoArgsConstructor;
36 import lombok.extern.slf4j.Slf4j;
37
38 import java.sql.Timestamp;
39
40
41
42
43 @NoArgsConstructor(access = AccessLevel.PRIVATE)
44 @Slf4j
45 public final class ProtobufAnyValueConverter {
46
47
48
49
50
51
52
53
54
55 public static Object convertToObject(final Any any) throws InvalidProtocolBufferException {
56 if (null == any || any.is(Empty.class)) {
57 return null;
58 }
59 if (any.is(StringValue.class)) {
60 return any.unpack(StringValue.class).getValue();
61 }
62 if (any.is(Int32Value.class)) {
63 return any.unpack(Int32Value.class).getValue();
64 }
65 if (any.is(Int64Value.class)) {
66 return any.unpack(Int64Value.class).getValue();
67 }
68 if (any.is(Int64Value.class)) {
69 return any.unpack(Int64Value.class).getValue();
70 }
71 if (any.is(UInt32Value.class)) {
72 return any.unpack(UInt64Value.class).getValue();
73 }
74 if (any.is(UInt64Value.class)) {
75 return any.unpack(UInt64Value.class).getValue();
76 }
77 if (any.is(FloatValue.class)) {
78 return any.unpack(FloatValue.class).getValue();
79 }
80 if (any.is(DoubleValue.class)) {
81 return any.unpack(DoubleValue.class).getValue();
82 }
83 if (any.is(BoolValue.class)) {
84 return any.unpack(BoolValue.class).getValue();
85 }
86 if (any.is(BytesValue.class)) {
87 return any.unpack(BytesValue.class).getValue().toByteArray();
88 }
89 if (any.is(com.google.protobuf.Timestamp.class)) {
90 return converProtobufTimestamp(any.unpack(com.google.protobuf.Timestamp.class));
91 }
92 if (any.is(Struct.class)) {
93 return JsonFormat.printer().print(any.unpack(Struct.class));
94 }
95
96 log.error("not support unpack value={}", any);
97 throw new UnsupportedOperationException(String.format("not support unpack the type %s", any.getTypeUrl()));
98 }
99
100 private static Timestamp converProtobufTimestamp(final com.google.protobuf.Timestamp timestamp) {
101 Timestamp result = new Timestamp(timestamp.getSeconds() * 1000);
102 result.setNanos(timestamp.getNanos());
103 return result;
104 }
105 }