-
Notifications
You must be signed in to change notification settings - Fork 225
/
JsonEncoder.java
277 lines (249 loc) · 10.6 KB
/
JsonEncoder.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
/**
*
* Copyright (c) 2006-2016, Speedment, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); You may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.speedment.plugins.json;
import static com.speedment.common.logger.internal.util.NullUtil.requireNonNullElements;
import static com.speedment.common.logger.internal.util.NullUtil.requireNonNulls;
import com.speedment.runtime.config.Project;
import com.speedment.runtime.config.identifier.FieldIdentifier;
import com.speedment.runtime.exception.SpeedmentException;
import com.speedment.runtime.field.trait.FieldTrait;
import com.speedment.runtime.field.trait.ReferenceFieldTrait;
import com.speedment.runtime.field.trait.ReferenceForeignKeyFieldTrait;
import static com.speedment.runtime.internal.util.document.DocumentDbUtil.referencedColumn;
import com.speedment.runtime.internal.util.document.DocumentUtil;
import com.speedment.runtime.manager.Manager;
import java.util.LinkedHashMap;
import java.util.Map;
import static java.util.Objects.requireNonNull;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toSet;
import java.util.stream.Stream;
/**
* An encoder that can transform Speedment entities to JSON.
* <p>
* Example usage:
* <code>
* Manager<Address> addresses = app.managerOf(Address.class);
* Manager<Employee> employees = app.managerOf(Employee.class);
* Manager<Employee> departments = app.managerOf(Department.class);
*
* // Include street, zip-code and city only.
* JconEncoder<Address> addrEncoder = JsonEncoder.noneOf(addresses)
* .add(Address.STREET)
* .add(Address.ZIPCODE)
* .add(Address.CITY);
*
* // Do not expose SSN but do inline the home address.
* JconEncoder<Employee> empEncoder = JsonEncoder.allOf(employees)
* .remove(Employee.SSN)
* .remove(Employee.DEPARTMENT); // Go the other way around.
* .add(Employee.HOME_ADDRESS, addrEncoder); // Foreign key
*
* // Inline every employee in the department.
* JconEncoder<Department> depEncoder = JsonEncoder.allOf(departments)
* .putStreamer("employees", Department::employees, empEncoder);
*
* String json = depEncoder.apply(departments.findAny().get());
* </code>
*
* @author Emil Forslund
* @param <ENTITY> entity type
*/
public final class JsonEncoder<ENTITY> {
private final Map<String, Function<ENTITY, String>> getters;
private final Project project;
/**
* Constructs an empty JsonEncoder with no fields added to the output
* renderer.
*/
private JsonEncoder(Project project) {
this.getters = new LinkedHashMap<>();
this.project = requireNonNull(project);
}
// Fields
public <D, T, I extends FieldTrait & ReferenceFieldTrait<ENTITY, D, T>> JsonEncoder<ENTITY> put(I field) {
requireNonNull(field);
final String columnName = jsonField(project, field.getIdentifier());
final Function<ENTITY, T> getter = ((ReferenceFieldTrait<ENTITY, D, T>) field).getter(); // Workaround bugg
return put(columnName, getter);
}
// Foreign key fields.
public <D, T, FK_ENTITY, I extends FieldTrait & ReferenceFieldTrait<ENTITY, D, T> & ReferenceForeignKeyFieldTrait<ENTITY, D, FK_ENTITY>>
JsonEncoder<ENTITY> put(I field, JsonEncoder<FK_ENTITY> builder) {
requireNonNulls(field, builder);
final String columnName = jsonField(project, field.getIdentifier());
final ReferenceForeignKeyFieldTrait<ENTITY, D, FK_ENTITY> fkField = (ReferenceForeignKeyFieldTrait< ENTITY, D, FK_ENTITY>) field; // Workaround bugg
return put(columnName, fkField::findFrom, builder);
}
// Label-and-getter pairs
public <T> JsonEncoder<ENTITY> put(String label, Function<ENTITY, T> getter) {
requireNonNull(label);
requireNonNull(getter);
getters.put(label, e -> "\"" + label + "\":" + jsonValue(getter.apply(e)));
return this;
}
// Label-and-getter with custom formatter
public <FK_ENTITY> JsonEncoder<ENTITY> put(String label, Function<ENTITY, FK_ENTITY> getter, JsonEncoder<FK_ENTITY> builder) {
requireNonNull(label);
requireNonNull(getter);
requireNonNull(builder);
getters.put(label, e -> "\"" + label + "\":" + builder.apply(getter.apply(e)));
return this;
}
// Label-and-streamer with custom formatter.
public <FK_ENTITY> JsonEncoder<ENTITY> putStreamer(String label, Function<ENTITY, Stream<FK_ENTITY>> streamer, JsonEncoder<FK_ENTITY> builder) {
requireNonNull(label);
requireNonNull(streamer);
requireNonNull(builder);
getters.put(label, e -> "\"" + label + "\":[" + streamer.apply(e).map(builder::apply).collect(joining(",")) + "]");
return this;
}
public <FK_ENTITY> JsonEncoder<ENTITY> putStreamer(String label, Function<ENTITY, Stream<FK_ENTITY>> streamer, Function<FK_ENTITY, String> encoder) {
requireNonNull(label);
requireNonNull(streamer);
requireNonNull(encoder);
getters.put(label, e -> "\"" + label + "\":[" + streamer.apply(e).map(encoder).collect(joining(",")) + "]");
return this;
}
// Removers by label
public JsonEncoder<ENTITY> remove(String label) {
requireNonNull(label);
getters.remove(label);
return this;
}
public JsonEncoder<ENTITY> remove(FieldTrait field) {
requireNonNull(field);
getters.remove(jsonField(project, field.getIdentifier()));
return this;
}
public String apply(ENTITY entity) {
return entity == null ? "null" : "{"
+ getters.values().stream()
.map(g -> g.apply(entity))
.collect(joining(","))
+ "}";
}
protected static String jsonField(Project project, FieldIdentifier<?> identifier) {
requireNonNulls(project, identifier);
return referencedColumn(project, identifier).getJavaName();
}
public static String jsonValue(Object in) {
// in is nullable, a field can certainly be null
final String value;
if (in instanceof Optional<?>) {
final Optional<?> o = (Optional<?>) in;
return o.map(JsonEncoder::jsonValue).orElse("null");
} else if (in == null) {
value = "null";
} else if (in instanceof Byte
|| in instanceof Short
|| in instanceof Integer
|| in instanceof Long
|| in instanceof Boolean
|| in instanceof Float
|| in instanceof Double) {
value = String.valueOf(in);
} else {
value = "\"" + String.valueOf(in).replace("\"", "\\\"") + "\"";
}
return value;
}
/**
* Creates and return a new JsonEncoder with no fields added to the
* renderer.
*
* @param <ENTITY> the Entity type
* @param manager of the entity
* @return a new JsonEncoder with no fields added to the renderer
*/
public static <ENTITY> JsonEncoder<ENTITY> noneOf(Manager<ENTITY> manager) {
return new JsonEncoder<>(projectOf(manager));
}
/**
* Creates and return a new JsonEncoder with all the Entity fields added to
* the renderer. The field(s) will be rendered using their default class
* renderer.
*
* @param <ENTITY> the Entity type
* @param manager of the entity
* @return a new JsonEncoder with all the Entity fields added to the
* renderer
*/
public static <ENTITY> JsonEncoder<ENTITY> allOf(Manager<ENTITY> manager) {
requireNonNull(manager);
final JsonEncoder<ENTITY> formatter = noneOf(manager);
manager.fields()
.filter(ReferenceFieldTrait.class::isInstance)
.map(f -> castReferenceFieldTrait(manager, f))
.map(ReferenceFieldTrait::getIdentifier)
.forEachOrdered(fi -> {
formatter.put(
jsonField(projectOf(manager), fi),
entity -> manager.get(entity, fi)
);
});
return formatter;
}
/**
* Creates and return a new JsonEncoder with the provided Entity field(s)
* added to the renderer. The field(s) will be rendered using their default
* class renderer.
*
* @param <ENTITY> the Entity type
* @param manager of the ENTITY
* @param fields to add to the output renderer
* @return a new JsonEncoder with the specified fields added to the renderer
*/
@SafeVarargs
@SuppressWarnings("varargs") // Using the array in a Stream.of() is safe
public static <ENTITY> JsonEncoder<ENTITY> of(Manager<ENTITY> manager, FieldTrait... fields) {
requireNonNull(manager);
requireNonNullElements(fields);
final JsonEncoder<ENTITY> formatter = noneOf(manager);
final Set<String> fieldNames = Stream.of(fields)
.map(FieldTrait::getIdentifier)
.map(FieldIdentifier::columnName)
.collect(toSet());
manager.fields()
.filter(ReferenceFieldTrait.class::isInstance)
.map(f -> castReferenceFieldTrait(manager, f))
.filter(f -> fieldNames.contains(f.getIdentifier().columnName()))
.map(ReferenceFieldTrait::getIdentifier)
.forEachOrdered(fi
-> formatter.put(
jsonField(projectOf(manager), fi),
entity -> manager.get(entity, fi)
)
);
return formatter;
}
private static <ENTITY> ReferenceFieldTrait<ENTITY, ?, ?> castReferenceFieldTrait(Manager<ENTITY> mgr, FieldTrait f) {
@SuppressWarnings("unchecked")
final ReferenceFieldTrait<ENTITY, ?, ?> result = (ReferenceFieldTrait<ENTITY, ?, ?>) f;
return result;
}
private static <ENTITY> Project projectOf(Manager<ENTITY> manager) {
return DocumentUtil.ancestor(manager.getTable(), Project.class)
.orElseThrow(() -> new SpeedmentException(
"Could not find a project root to table '" +
manager.getTable().toString() + "'."
));
}
}