1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package com.linecorp.centraldogma.internal.thrift;
18
19 import javax.annotation.Nullable;
20
21 import com.fasterxml.jackson.core.JsonProcessingException;
22 import com.google.common.base.Converter;
23
24 import com.linecorp.centraldogma.common.ChangeFormatException;
25 import com.linecorp.centraldogma.internal.Jackson;
26
27
28
29
30
31 public final class ChangeConverter extends Converter<com.linecorp.centraldogma.common.Change<?>, Change> {
32 public static final Converter<com.linecorp.centraldogma.common.Change<?>, Change> TO_DATA =
33 new ChangeConverter();
34
35 public static final Converter<Change, com.linecorp.centraldogma.common.Change<?>> TO_MODEL =
36 TO_DATA.reverse();
37
38 private ChangeConverter() {}
39
40 @Override
41 protected Change doForward(com.linecorp.centraldogma.common.Change<?> value) {
42 final Change change = new Change(value.path(), convertChangeType(value.type()));
43 switch (change.getType()) {
44 case UPSERT_JSON:
45 case APPLY_JSON_PATCH:
46 try {
47 change.setContent(Jackson.writeValueAsString(value.content()));
48 } catch (JsonProcessingException e) {
49 throw new ChangeFormatException("failed to read a JSON tree", e);
50 }
51 break;
52 case UPSERT_TEXT:
53 case APPLY_TEXT_PATCH:
54 case RENAME:
55 change.setContent((String) value.content());
56 break;
57 case REMOVE:
58 break;
59 }
60 return change;
61 }
62
63 @Override
64 protected com.linecorp.centraldogma.common.Change<?> doBackward(Change c) {
65 switch (c.getType()) {
66 case UPSERT_JSON:
67 return com.linecorp.centraldogma.common.Change.ofJsonUpsert(c.getPath(),
68 c.getContent());
69 case UPSERT_TEXT:
70 return com.linecorp.centraldogma.common.Change.ofTextUpsert(c.getPath(),
71 c.getContent());
72 case REMOVE:
73 return com.linecorp.centraldogma.common.Change.ofRemoval(c.getPath());
74 case RENAME:
75 return com.linecorp.centraldogma.common.Change.ofRename(c.getPath(), c.getContent());
76 case APPLY_JSON_PATCH:
77 return com.linecorp.centraldogma.common.Change.ofJsonPatch(c.getPath(), c.getContent());
78 case APPLY_TEXT_PATCH:
79 return com.linecorp.centraldogma.common.Change.ofTextPatch(c.getPath(),
80 c.getContent());
81 }
82
83 throw new Error();
84 }
85
86 @Nullable
87 private static ChangeType convertChangeType(com.linecorp.centraldogma.common.ChangeType type) {
88 if (type == null) {
89 return null;
90 }
91
92 return ChangeType.valueOf(type.name());
93 }
94 }