1 package cn.home1.oss.lib.webmvc.api;
2
3 import static org.apache.commons.lang3.StringUtils.isNotBlank;
4
5 import cn.home1.oss.lib.common.Jackson2Utils;
6
7 import com.fasterxml.jackson.databind.ObjectMapper;
8
9 import lombok.extern.slf4j.Slf4j;
10
11 import java.util.function.Function;
12
13
14
15
16 @Slf4j
17 public class JsonToken<T> implements TypeSafeToken<T> {
18
19 private final Function<String, T> fromToken;
20 private final Function<T, String> toToken;
21
22 public JsonToken(
23 final Class<T> type,
24 final ObjectMapper objectMapper
25 ) {
26 this.toToken = Jackson2Utils.toJson(objectMapper);
27 this.fromToken = Jackson2Utils.fromJson(objectMapper, type);
28 }
29
30 @Override
31 public String toToken(final T obj) {
32 return this.toToken != null && obj != null ?
33 this.toToken.apply(obj) :
34 (obj != null) ? obj.toString() : null;
35 }
36
37 @Override
38 public T fromToken(final String token) {
39 T result;
40 try {
41 result = isNotBlank(token) ? this.fromToken.apply(token) : null;
42 } catch (final Exception ex) {
43 log.warn("error reading token: {}", token, ex);
44 result = null;
45 }
46 return result;
47 }
48 }