-
Notifications
You must be signed in to change notification settings - Fork 86
Expand file tree
/
Copy pathMapStyleEventTemplate.java
More file actions
75 lines (70 loc) · 2.79 KB
/
MapStyleEventTemplate.java
File metadata and controls
75 lines (70 loc) · 2.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package org.fluentd.logger.sender;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.LinkedHashMap;
import java.util.Map;
import org.msgpack.MessageTypeException;
import org.msgpack.packer.Packer;
import org.msgpack.template.Templates;
public class MapStyleEventTemplate extends EventTemplate {
@Override
protected void doWriteData(Packer pk, Object data, boolean required) throws IOException {
if(data instanceof Map){
writeMap(pk, (Map<?, ?>)data, required);
} else{
try{
pk.write(data);
} catch (MessageTypeException e) {
writeObj(pk, data, required);
}
}
}
private <K, V> void writeMap(Packer pk, Map<K, V> map, boolean required) throws IOException {
pk.writeMapBegin(map.size());
{
for (Map.Entry<?, ?> entry : map.entrySet()) {
Templates.TString.write(pk, entry.getKey().toString(), required);
Object value = entry.getValue();
if(value instanceof Map<?, ?>){
writeMap(pk, (Map<?, ?>)value, required);
} else{
try {
pk.write(entry.getValue());
} catch (MessageTypeException e) {
writeObj(pk, entry.getValue(), required);
}
}
}
}
pk.writeMapEnd();
}
private void writeObj(Packer pk, Object data, boolean required) throws IOException {
Map<String, Object> map = new LinkedHashMap<String, Object>();
Class<?> clazz = data.getClass();
while(!clazz.equals(Object.class)){
for(Method m : clazz.getDeclaredMethods()){
if(m.getDeclaringClass().equals(Object.class)) continue;
if(m.getParameterTypes().length != 0) continue;
String name = null;
if(m.getName().startsWith("get")){
name = m.getName().substring(3);
} else if(m.getName().startsWith("is") && m.getReturnType().equals(boolean.class)){
name = m.getName().substring(2);
} else{
continue;
}
if(name.length() == 0) continue;
name = name.substring(0, 1).toLowerCase() + (name.length() == 1 ? "" : name.substring(1));
try {
map.put(name, m.invoke(data));
} catch (IllegalArgumentException e) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
}
}
clazz = clazz.getSuperclass();
}
writeMap(pk, map, required);
}
}