-
Notifications
You must be signed in to change notification settings - Fork 2
/
JsonLdSerializerTestBase.java
352 lines (301 loc) · 14.8 KB
/
JsonLdSerializerTestBase.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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
package cz.cvut.kbss.jsonld.serialization;
import com.github.jsonldjava.utils.JsonUtils;
import cz.cvut.kbss.jopa.model.annotations.Id;
import cz.cvut.kbss.jopa.model.annotations.OWLClass;
import cz.cvut.kbss.jopa.model.annotations.OWLDataProperty;
import cz.cvut.kbss.jsonld.ConfigParam;
import cz.cvut.kbss.jsonld.JsonLd;
import cz.cvut.kbss.jsonld.common.IdentifierUtil;
import cz.cvut.kbss.jsonld.environment.Generator;
import cz.cvut.kbss.jsonld.environment.TestUtil;
import cz.cvut.kbss.jsonld.environment.Vocabulary;
import cz.cvut.kbss.jsonld.environment.model.*;
import cz.cvut.kbss.jsonld.exception.MissingIdentifierException;
import cz.cvut.kbss.jsonld.serialization.util.BufferedJsonGenerator;
import org.eclipse.rdf4j.model.Model;
import org.eclipse.rdf4j.model.ValueFactory;
import org.eclipse.rdf4j.model.impl.LinkedHashModel;
import org.eclipse.rdf4j.model.vocabulary.RDF;
import org.eclipse.rdf4j.rio.RDFFormat;
import org.eclipse.rdf4j.rio.RDFParser;
import org.eclipse.rdf4j.rio.Rio;
import org.eclipse.rdf4j.rio.helpers.StatementCollector;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.StringReader;
import java.net.URI;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import static cz.cvut.kbss.jsonld.environment.IsIsomorphic.isIsomorphic;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.startsWith;
import static org.junit.jupiter.api.Assertions.*;
/**
* Contains tests common to all {@link JsonLdSerializer} implementations.
*/
public abstract class JsonLdSerializerTestBase {
protected BufferedJsonGenerator jsonWriter = new BufferedJsonGenerator();
protected JsonLdSerializer sut;
protected static ValueFactory vf() {
return TestUtil.VALUE_FACTORY;
}
protected Model toRdf(GeneratesRdf instance) {
final Model model = new LinkedHashModel();
final Set<URI> visited = new HashSet<>();
instance.toRdf(model, TestUtil.VALUE_FACTORY, visited);
return model;
}
protected Model readJson(String json) throws IOException {
final Model model = new LinkedHashModel();
final RDFParser rdfParser = Rio.createParser(RDFFormat.JSONLD);
rdfParser.setRDFHandler(new StatementCollector(model));
rdfParser.parse(new StringReader(json));
return model;
}
protected Map<String, ?> serializeAndRead(Object value) throws IOException {
sut.serialize(value);
Object jsonObject = JsonUtils.fromString(jsonWriter.getResult());
assertInstanceOf(Map.class, jsonObject);
return (Map<String, ?>) jsonObject;
}
@Test
void testSerializeObjectWithSingularReference() throws Exception {
final Employee employee = Generator.generateEmployee();
sut.serialize(employee);
final Model expected = toRdf(employee);
final Model actual = readJson(jsonWriter.getResult());
assertThat(actual, isIsomorphic(expected));
}
@Test
void testSerializeObjectWithPluralReference() throws Exception {
final Organization org = Generator.generateOrganization();
generateEmployees(org, false); // No backward references for this test
sut.serialize(org);
final Model expected = toRdf(org);
final Model actual = readJson(jsonWriter.getResult());
assertThat(actual, isIsomorphic(expected));
}
protected void generateEmployees(Organization org, boolean withBackwardReference) {
for (int i = 0; i < Generator.randomCount(5, 10); i++) {
final Employee emp = Generator.generateEmployee();
emp.setEmployer(withBackwardReference ? org : null);
org.addEmployee(emp);
}
}
@Test
void testSerializeObjectWithBackwardReferences() throws Exception {
final Organization org = Generator.generateOrganization();
generateEmployees(org, true);
sut.serialize(org);
final Model expected = toRdf(org);
final Model actual = readJson(jsonWriter.getResult());
assertThat(actual, isIsomorphic(expected));
}
@Test
void testSerializeObjectWithPluralReferences() throws Exception {
final Organization org = Generator.generateOrganization();
generateEmployees(org, true);
org.getEmployees().stream().filter(emp -> Generator.randomBoolean()).forEach(org::addAdmin);
if (org.getAdmins() == null || org.getAdmins().isEmpty()) {
org.setAdmins(new HashSet<>(Collections.singletonList(org.getEmployees().iterator().next())));
}
sut.serialize(org);
final Model expected = toRdf(org);
final Model actual = readJson(jsonWriter.getResult());
assertThat(actual, isIsomorphic(expected));
}
@Test
void testSerializationOfObjectWithStringBasedUnmappedProperties() throws Exception {
final Person person = Generator.generatePerson();
sut.serialize(person);
final Model expected = toRdf(person);
final Model actual = readJson(jsonWriter.getResult());
assertThat(actual, isIsomorphic(expected));
}
@Test
void serializationPutsOwlClassAndTypesContentIntoOneTypeProperty() throws Exception {
final User user = Generator.generateUser();
final String type = Generator.URI_BASE + "TypeOne";
user.setTypes(Collections.singleton(type));
sut.serialize(user);
final Model expected = toRdf(user);
final Model actual = readJson(jsonWriter.getResult());
final Model expectedTypes = expected.filter(vf().createIRI(user.getUri().toString()), RDF.TYPE, null);
final Model actualTypes = actual.filter(vf().createIRI(user.getUri().toString()), RDF.TYPE, null);
assertEquals(expectedTypes, actualTypes);
}
@Test
void serializationSerializesIndividualsInTypedUnmappedPropertiesAsObjects() throws Exception {
final PersonWithTypedProperties instance = new PersonWithTypedProperties();
instance.setUri(Generator.generateUri());
instance.setFirstName("Sarah");
instance.setLastName("Palmer");
instance.setProperties(new HashMap<>());
final URI someProperty = Generator.generateUri();
final String simpleValue = "Simple string value";
instance.getProperties().put(someProperty, Collections.singleton(simpleValue));
final Person friend = Generator.generatePerson();
instance.getProperties().put(URI.create(Vocabulary.KNOWS), Collections.singleton(friend));
sut.serialize(instance);
final Model expected = toRdf(instance);
final Model actual = readJson(jsonWriter.getResult());
assertThat(actual, isIsomorphic(expected));
}
@Test
void serializationSerializesIdentifierInTypedUnmappedPropertiesAsObjectsWithId() throws Exception {
final PersonWithTypedProperties instance = new PersonWithTypedProperties();
instance.setUri(Generator.generateUri());
instance.setFirstName("Sarah");
instance.setLastName("Palmer");
instance.setProperties(new HashMap<>());
final URI someProperty = Generator.generateUri();
final Integer simpleValue = 4;
instance.getProperties().put(someProperty, Collections.singleton(simpleValue));
final URI friendId = Generator.generateUri();
instance.getProperties().put(URI.create(Vocabulary.KNOWS), Collections.singleton(friendId));
sut.serialize(instance);
final Model expected = toRdf(instance);
final Model actual = readJson(jsonWriter.getResult());
assertThat(actual, isIsomorphic(expected));
}
@Test
void testSerializeObjectWithDataProperties() throws Exception {
final User user = Generator.generateUser();
sut.serialize(user);
final Model expected = toRdf(user);
final Model actual = readJson(jsonWriter.getResult());
assertThat(actual, isIsomorphic(expected));
}
@Test
void serializationSerializesPlainIdentifierObjectPropertyValue() throws Exception {
final Organization company = Generator.generateOrganization();
company.setCountry(URI.create("http://dbpedia.org/resource/Czech_Republic"));
sut.serialize(company);
final Model result = readJson(jsonWriter.getResult());
assertThat(result, hasItem(vf().createStatement(vf().createIRI(company.getUri().toString()),
vf().createIRI(Vocabulary.ORIGIN),
vf().createIRI(company.getCountry().toString()))));
}
@Test
void serializationGeneratesBlankNodeIdentifierForInstanceOfClassWithoutIdentifierField() throws Exception {
final PersonWithoutIdentifier person = new PersonWithoutIdentifier();
person.firstName = "Thomas";
person.lastName = "Lasky";
final Map<String, ?> json = serializeAndRead(person);
final String id = (String) json.get(JsonLd.ID);
assertNotNull(id);
assertThat(id, startsWith(IdentifierUtil.B_NODE_PREFIX));
}
@OWLClass(iri = Vocabulary.PERSON)
protected static class PersonWithoutIdentifier {
@OWLDataProperty(iri = Vocabulary.FIRST_NAME)
protected String firstName;
@OWLDataProperty(iri = Vocabulary.LAST_NAME)
protected String lastName;
}
@Test
void serializationThrowsMissingIdentifierExceptionWhenNoIdentifierFieldIsFoundAndRequiredIdIsConfigured() {
sut.configuration().set(ConfigParam.REQUIRE_ID, Boolean.TRUE.toString());
final PersonWithoutIdentifier person = new PersonWithoutIdentifier();
person.firstName = "Thomas";
person.lastName = "Lasky";
assertThrows(MissingIdentifierException.class, () -> sut.serialize(person));
}
@Test
void serializationSkipsPropertiesWithWriteOnlyAccess() throws Exception {
final User user = Generator.generateUser();
user.setPassword("test-117");
sut.serialize(user);
final Model result = readJson(jsonWriter.getResult());
assertFalse(result.contains(vf().createIRI(user.getUri().toString()),
vf().createIRI(Vocabulary.PASSWORD), null));
}
@Test
void serializationSerializesPropertyWithReadOnlyAccess() throws Exception {
final Study study = new Study();
study.setUri(Generator.generateUri());
study.setName("Test study");
study.setParticipants(Collections.singleton(Generator.generateEmployee()));
study.setMembers(Collections.singleton(Generator.generateEmployee()));
sut.serialize(study);
final Model expected = toRdf(study);
final Model actual = readJson(jsonWriter.getResult());
assertThat(actual, isIsomorphic(expected));
}
@Test
void serializationSerializesAnnotationPropertyStringValueAsString() throws Exception {
final ObjectWithAnnotationProperties toSerialize = new ObjectWithAnnotationProperties(Generator.generateUri());
toSerialize.setChangedValue(Generator.generateUri().toString());
sut.serialize(toSerialize);
final Model expected = toRdf(toSerialize);
final Model actual = readJson(jsonWriter.getResult());
assertThat(actual, isIsomorphic(expected));
}
@Test
void serializationSerializesUrisOfAnnotationPropertyAttributeAsObjectsWithId() throws Exception {
final ObjectWithAnnotationProperties toSerialize = new ObjectWithAnnotationProperties(Generator.generateUri());
toSerialize
.setOrigins(IntStream.range(0, 5).mapToObj(i -> Generator.generateUri()).collect(Collectors.toSet()));
sut.serialize(toSerialize);
final Model expected = toRdf(toSerialize);
final Model actual = readJson(jsonWriter.getResult());
assertThat(actual, isIsomorphic(expected));
}
@Test
void serializationSerializesEnumDataPropertyAsStringValueOfEnumConstant() throws Exception {
final User user = Generator.generateUser();
user.setRole(Role.ADMIN);
sut.serialize(user);
final Model result = readJson(jsonWriter.getResult());
assertTrue(result.contains(vf().createIRI(user.getUri().toString()), vf().createIRI(Vocabulary.ROLE),
vf().createLiteral(Role.ADMIN.toString())));
}
@Test
void serializationSerializesConcreteValueOfFieldOfTypeObject() throws Exception {
final GenericMember instance = new GenericMember();
instance.setUri(Generator.generateUri());
instance.setMemberOf(Generator.generateOrganization());
sut.serialize(instance);
final Model expected = toRdf(instance);
final Model actual = readJson(jsonWriter.getResult());
assertThat(actual, isIsomorphic(expected));
}
@Test
void serializationSupportsRegistrationAndUsageOfCustomSerializers() throws Exception {
sut.registerSerializer(LocalDate.class, ((value, ctx) -> JsonNodeFactory.createLiteralNode(ctx.getAttributeId(),
value.toString())));
final CompactedJsonLdSerializerTest.OrganizationWithLocalDate
organization = new CompactedJsonLdSerializerTest.OrganizationWithLocalDate();
organization.uri = Generator.generateUri();
organization.created = LocalDate.now();
sut.serialize(organization);
final Model result = readJson(jsonWriter.getResult());
assertThat(result, hasItem(vf().createStatement(vf().createIRI(organization.uri.toString()),
vf().createIRI(Vocabulary.DATE_CREATED),
vf().createLiteral(organization.created.toString()))));
}
@SuppressWarnings("unused")
@OWLClass(iri = Vocabulary.ORGANIZATION)
public static class OrganizationWithLocalDate {
@Id
private URI uri;
@OWLDataProperty(iri = Vocabulary.DATE_CREATED)
private LocalDate created;
}
@Test
void serializationSupportsRegistrationAndUsageOfCustomObjectPropertyValueSerializers() throws Exception {
// TODO Fix
final ValueSerializer<Organization> serializer =
(value, ctx) -> JsonNodeFactory.createObjectIdNode(ctx.getAttributeId(), value.getUri());
sut.registerSerializer(Organization.class, serializer);
final Employee employee = Generator.generateEmployee();
sut.serialize(employee);
final Model result = readJson(jsonWriter.getResult());
assertThat(result, hasItem(vf().createStatement(vf().createIRI(employee.getUri().toString()),
vf().createIRI(Vocabulary.IS_MEMBER_OF),
vf().createIRI(employee.getEmployer().getUri().toString()))));
}
}