-
Notifications
You must be signed in to change notification settings - Fork 21
/
JSONCoderOption.java
315 lines (261 loc) · 11.4 KB
/
JSONCoderOption.java
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
/*************************************************************
Copyright 2018-2019 eBay Inc.
Author/Developer: Jianwu Chen
Use of this source code is governed by an MIT-style
license that can be found in the LICENSE file or at
https://opensource.org/licenses/MIT.
************************************************************/
package org.jsonex.jsoncoder;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;
import org.jsonex.core.factory.CacheThreadLocal;
import org.jsonex.core.factory.InjectableFactory;
import org.jsonex.core.type.Tuple;
import org.jsonex.core.type.Tuple.Pair;
import org.jsonex.core.util.ClassUtil;
import org.jsonex.jsoncoder.coder.*;
import org.jsonex.jsoncoder.fieldTransformer.FieldTransformer;
import org.jsonex.jsoncoder.fieldTransformer.FieldTransformer.FieldInfo;
import org.jsonex.treedoc.json.TDJSONOption;
import org.slf4j.Logger;
import java.text.Format;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import static org.jsonex.core.util.LangUtil.*;
import static org.jsonex.core.util.ListUtil.listOf;
import static org.jsonex.jsoncoder.fieldTransformer.FieldTransformer.exclude;
@SuppressWarnings("UnusedReturnValue")
@Accessors(chain=true) @Slf4j
public class JSONCoderOption {
@Getter final static JSONCoderOption global = new JSONCoderOption(null);
static {
global.addCoder(CoderDate.get(), CoderEnum.get(), CoderXMLGregorianCalendar.get(), CoderAtomicInteger.get(),
CoderBigInteger.get(), CoderClass.get(), CoderURI.get(), CoderURL.get());
global.addSkippedClasses(Format.class);
global.fallbackDateFormats.add("yyyy-MM-dd HH:mm:ss.SSS.Z"); //Just for backward compatibility.
global.fallbackDateFormats.add("yyyy/MM/dd HH:mm:ss.SSS.Z");
global.fallbackDateFormats.add("yyyy-MM-dd HH:mm:ss.SSS");
global.fallbackDateFormats.add("yyyy-MM-dd'T'HH:mm:ss'Z'");
global.fallbackDateFormats.add("yyyy-MM-dd HH:mm:ss");
global.fallbackDateFormats.add("yyyy-MM-dd");
global.fallbackDateFormats.add("HH:mm:ss");
global
.addDefaultFilter(exclude("copy")) // DAO class has a getCopy() method
.addFilterFor(AtomicReference.class, exclude("acquire", "opaque", "plain"));
}
private final JSONCoderOption parent;
@Getter @Setter int maxObjects = 10_000;
@Getter @Setter int maxDepth = 30;
@Getter @Setter int maxElementsPerNode = 2000;
/**
* If true, when convert from an java bean, the readonly field will be ignored
*/
@Getter @Setter boolean ignoreReadOnly;
/**
* If true, subclass field won't be encoded
*/
@Getter @Setter boolean ignoreSubClassFields;
/**
* If true, enum name will be encoded
*/
@Getter @Setter boolean showEnumName;
/**
* If true, class type will be encoded
*/
@Getter @Setter boolean showType;
/**
* If true, duplicated object will be serialized as a reference to existing object's hash
*/
@Getter @Setter boolean dedupWithRef;
/**
* If true, for java bean type, only field include private will be returned, no setter getter method will be returned.
*/
@Getter @Setter boolean showPrivateField;
@Getter @Setter String parsingDateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSX";
/**
* Used by {@link CoderDate}.encode()}, If Date format is null, date will be encoded as long with value of Date.getTime()
*/
@Getter @Setter String dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSX";
/** Used by {@link CoderDate}.encode, by default it will use default timezone, a custom timezone can be specified*/
@Getter @Setter TimeZone timeZone = null;
public TimeZone timeZoneOrParent() { return orElse(timeZone, safe(parent, JSONCoderOption::getTimeZone)); }
// For performance reason, we need to cache SimpleDateFormat in the same thread as SimpleDateFormat is not threadsafe
private static final InjectableFactory._2<String, TimeZone, SimpleDateFormat> dateFormatCache =
InjectableFactory._2.of(JSONCoderOption::buildDateFormat, CacheThreadLocal.get());
public SimpleDateFormat getCachedParsingDateFormat() { return getCachedDateFormat(parsingDateFormat); }
public SimpleDateFormat getCachedDateFormat() { return getCachedDateFormat(dateFormat); }
public SimpleDateFormat getCachedDateFormat(String format) { return dateFormatCache.get(format, timeZoneOrParent()); }
private static SimpleDateFormat buildDateFormat(String format, TimeZone timeZone) {
SimpleDateFormat result = new SimpleDateFormat(format);
if (timeZone != null)
result.setTimeZone(timeZone);
return result;
}
/** Internal use only */
@Getter private final List<String> fallbackDateFormats = new ArrayList<>();
@Getter @Setter boolean alwaysMapKeyAsString;
/**
* Used by de-serializer, indicate throw exception if there's unknown field.
*/
@Getter @Setter boolean errorOnUnknownProperty;
@Getter private final Set<Class<?>> skippedClasses = new HashSet<>();
@Getter private final Set<String> skippedPackages = new HashSet<>();
//The class in this list, subclass field will be ignored.
@Getter private final Set<Class<?>> ignoreSubClassFieldsClasses = new HashSet<>();
@Getter private final List<Pair<Class<?>, FieldTransformer>> filters = new ArrayList<>();
@Getter private final List<ICoder<?>> coderList = new ArrayList<>();
/**
* used to override equals and hashCode methods for certain object
* e.g. BO object as there are no proper implementation of equals and hashCode
* which could cause duplicated copy of Object to be output.
*
* The priority is based on the index of the wrapper. So if want to add highest priority
* need to use equalsWrapper.add(0, wrapper).
*
*/
@Getter private final List<EqualsWrapper<?>> equalsWrapper = new ArrayList<>();
// JSON coder config
@Getter @Setter private TDJSONOption jsonOption = new TDJSONOption();
public enum LogLevel {
OFF { public void log(Logger log, String msg, Throwable e) { /* Noop */ }},
DEBUG { public void log(Logger log, String msg, Throwable e) { log.debug(msg, e); }},
INFO { public void log(Logger log, String msg, Throwable e) { log.info(msg, e); }},
WARN { public void log(Logger log, String msg, Throwable e) { log.warn(msg, e); }},
ERROR { public void log(Logger log, String msg, Throwable e) { log.error(msg, e); }},
;
public abstract void log(Logger logger, String message, Throwable e);
}
@Getter @Setter private LogLevel warnLogLevel = LogLevel.INFO;
/**
* Accept specified sub-class using `$type` attribute. This feature is disabled by default for security reason
*/
@Getter @Setter private boolean allowPolymorphicClasses = false;
/**
* Merge array. By default, when decode to exiting object, array or collection will be override instead of merge.
* If this set true, it will merge the array (concatenation)
*/
@Getter @Setter private boolean mergeArray = false;
/**
* As Java Map and Set implementation, the order may not be strictly consistent cross JVM implementation
* set this to true, it will sort the keys in a predicated order
*/
@Getter @Setter private boolean strictOrder = false;
public JSONCoderOption() { this(global); }
private JSONCoderOption(JSONCoderOption parent) { this.parent = parent; }
public static JSONCoderOption of() { return new JSONCoderOption(); }
public static JSONCoderOption ofIndentFactor(int factor) {
return new JSONCoderOption().setJsonOption(TDJSONOption.ofIndentFactor(factor));
}
ICoder<?> findCoder(Class<?> cls){
for (ICoder<?> bc : coderList){
if(bc.getType().isAssignableFrom(cls))
return bc;
}
return parent == null ? null : parent.findCoder(cls);
}
public boolean isClassSkipped(Class<?> cls) {
for (Class<?> skip : skippedClasses) {
if (skip.isAssignableFrom(cls))
return true;
}
for (String pkg : skippedPackages) {
if (cls.getPackage() != null && cls.getPackage().getName().startsWith(pkg))
return true;
}
return parent != null && parent.isClassSkipped(cls);
}
public FieldInfo transformField(Class<?> cls, FieldInfo fieldInfo, BeanCoderContext ctx) {
for (Pair<Class<?>, FieldTransformer> filter : filters) {
if (!filter._1.isAssignableFrom(cls))
continue;
// TODO: Fix when to stop the filter chain strategy
fieldInfo = filter._2.apply(fieldInfo, ctx);
}
return parent == null ? fieldInfo : parent.transformField(cls, fieldInfo, ctx);
}
public boolean isExcluded(Class<?> cls, String name, BeanCoderContext ctx) {
for (Pair<Class<?>, FieldTransformer> filter : filters) {
if (!filter._1.isAssignableFrom(cls))
continue;
if (!filter._2.shouldInclude(name, ctx))
return true;
}
return parent == null ? false : parent.isExcluded(cls, name, ctx);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
Object getEqualsWrapper(Object obj) {
for(EqualsWrapper ew : equalsWrapper)
if(ew.getType().isAssignableFrom(obj.getClass()))
return ew.newWrapper(obj);
return parent == null ? obj : parent.getEqualsWrapper(obj);
}
public Date parseDateFullback(String dateStr) throws ParseException {
ParseException exp = null;
for(String fmt : fallbackDateFormats){
try {
return getCachedDateFormat(fmt).parse(dateStr);
} catch(ParseException e1) {
exp = e1;
}
}
if (parent == null)
throw exp == null ? new ParseException(dateStr, 0) : exp;
return parent.parseDateFullback(dateStr);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public boolean isIgnoreSubClassFields(Class<?> cls){
if(ignoreSubClassFields)
return true;
for(Class iCls : ignoreSubClassFieldsClasses)
if(iCls.isAssignableFrom(cls))
return true;
return parent != null && parent.isIgnoreSubClassFields(cls);
}
public JSONCoderOption addDefaultFilter(FieldTransformer filter) {
return addFilterFor(Object.class, filter, false);
}
public JSONCoderOption addFilterFor(Class<?> cls, FieldTransformer filter) {
return addFilterFor(cls, filter, false);
}
public JSONCoderOption addFilterFor(Class<?> cls, FieldTransformer filter, boolean last) {
Pair<Class<?>, FieldTransformer> clsToFilter = Tuple.of(cls, filter);
doIfElse(last, () -> filters.add(clsToFilter), () -> filters.add(0, clsToFilter));
return this;
}
public JSONCoderOption addSkippedClasses(Class<?>... cls) {
skippedClasses.addAll(Arrays.asList(cls));
return this;
}
public JSONCoderOption addSkippedClasses(String... cls) {
for (String c : cls) {
try {
skippedClasses.add(ClassUtil.forName(c));
} catch (Exception e) {
log.error("addSkippedClasses: Error load class: " + c);
}
}
return this;
}
public JSONCoderOption addSkippedPackages(String... pkgs) {
skippedPackages.addAll(listOf(pkgs));
return this;
}
public JSONCoderOption addIgnoreSubClassFieldsClasses(Class<?>... cls) {
Collections.addAll(ignoreSubClassFieldsClasses, cls);
return this;
}
public JSONCoderOption addCoder(ICoder<?>... codes) {
coderList.addAll(Arrays.asList(codes));
return this;
}
public JSONCoderOption setJsonOption(boolean alwaysQuoteName, char quoteChar, int indentFactor) {
jsonOption.setAlwaysQuoteName(alwaysQuoteName)
.setQuoteChar(quoteChar)
.setIndentFactor(indentFactor);
return this;
}
}