-
Notifications
You must be signed in to change notification settings - Fork 14
/
JavaTransformer.java
548 lines (476 loc) · 22.2 KB
/
JavaTransformer.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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
/**
* Copyright (C) 2016 Czech Technical University in Prague
* <p>
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later
* version.
* <p>
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details. You should have received a copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
package cz.cvut.kbss.jopa.owl2java;
import com.sun.codemodel.*;
import cz.cvut.kbss.jopa.CommonVocabulary;
import cz.cvut.kbss.jopa.ic.api.AtomicSubClassConstraint;
import cz.cvut.kbss.jopa.ic.api.DataParticipationConstraint;
import cz.cvut.kbss.jopa.ic.api.ObjectParticipationConstraint;
import cz.cvut.kbss.jopa.model.annotations.*;
import cz.cvut.kbss.jopa.model.annotations.OWLAnnotationProperty;
import cz.cvut.kbss.jopa.model.annotations.OWLDataProperty;
import cz.cvut.kbss.jopa.model.annotations.OWLObjectProperty;
import cz.cvut.kbss.jopa.model.annotations.Properties;
import cz.cvut.kbss.jopa.owl2java.cli.Option;
import cz.cvut.kbss.jopa.owl2java.cli.PropertiesType;
import cz.cvut.kbss.jopa.owl2java.config.TransformationConfiguration;
import cz.cvut.kbss.jopa.owlapi.DatatypeTransformer;
import cz.cvut.kbss.jopa.vocabulary.RDFS;
import org.semanticweb.owlapi.model.*;
import org.semanticweb.owlapi.model.OWLClass;
import org.semanticweb.owlapi.search.EntitySearcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.*;
import static cz.cvut.kbss.jopa.owl2java.Constants.*;
public class JavaTransformer {
private static final Logger LOG = LoggerFactory.getLogger(OWL2JavaTransformer.class);
private static final String[] KEYWORDS = {"abstract",
"assert",
"boolean",
"break",
"byte",
"case",
"catch",
"char",
"class",
"const",
"continue",
"default",
"do",
"double",
"else",
"enum",
"extends",
"final",
"finally",
"float",
"for",
"goto",
"if",
"implements",
"import",
"instanceof",
"int",
"interface",
"long",
"native",
"new",
"package",
"private",
"protected",
"public",
"return",
"short",
"static",
"strictfp",
"super",
"switch",
"synchronized",
"this",
"throw",
"throws",
"transient",
"try",
"void",
"volatile",
"while"};
private static final String PREFIX_STRING = "s_";
private static final String PREFIX_CLASS = "c_";
private static final String PREFIX_PROPERTY = "p_";
private static final String PREFIX_INDIVIDUAL = "i_";
private static final String PREFIX_DATATYPE = "d_";
private JDefinedClass voc;
private Map<OWLEntity, JFieldRef> entities = new HashMap<>();
private Map<OWLClass, JDefinedClass> classes = new HashMap<>();
private final TransformationConfiguration configuration;
JavaTransformer(TransformationConfiguration configuration) {
this.configuration = configuration;
}
private static String validJavaIDForIRI(final IRI iri) {
if (iri.getFragment() != null) {
return validJavaID(iri.getFragment());
} else {
int x = iri.toString().lastIndexOf("/");
return validJavaID(iri.toString().substring(x + 1));
}
}
private static String validJavaID(final String s) {
String res = s.trim().replace("-", "_").replace("'", "_quote_").replace(".", "_dot_").replace(',', '_');
if (Arrays.binarySearch(KEYWORDS, res) >= 0) {
res = "_" + res;
}
return res;
}
private JFieldVar addField(final String name, final JDefinedClass cls,
final JType fieldType) {
String newName = name;
int i = 0;
while (cls.fields().containsKey(newName)) {
newName = name + "" + (++i);
}
final JFieldVar fvId = cls.field(JMod.PROTECTED, fieldType, newName);
final String fieldName = fvId.name().substring(0, 1).toUpperCase() + fvId.name().substring(1);
final JMethod mSetId = cls.method(JMod.PUBLIC, void.class, "set" + fieldName);
final JVar v = mSetId.param(fieldType, fvId.name());
mSetId.body().assign(JExpr._this().ref(fvId), v);
final JMethod mGetId = cls.method(JMod.PUBLIC, fieldType, "get" + fieldName);
mGetId.body()._return(fvId);
return fvId;
}
/**
* Generates an object model consisting of JOPA entity classes and a vocabulary file from the specified ontology and
* context definition.
*
* @param ontology Ontology from which the model is generated
* @param context Context information
*/
public void generateModel(final OWLOntology ontology, final ContextDefinition context) {
try {
final JCodeModel cm = new JCodeModel();
voc = createVocabularyClass(cm);
generateVocabulary(ontology, cm, context);
_generateModel(ontology, cm, context, modelPackageName());
writeOutModel(cm);
} catch (JClassAlreadyExistsException e1) {
LOG.error("Transformation FAILED.", e1);
} catch (IOException e) {
LOG.error("File generation FAILED.", e);
}
}
private String modelPackageName() {
final String packageConfig = configuration.getPackageName();
final StringBuilder sb = new StringBuilder(packageConfig);
if (!packageConfig.isEmpty()) {
sb.append(PACKAGE_SEPARATOR);
}
sb.append(MODEL_PACKAGE);
return sb.toString();
}
private JDefinedClass createVocabularyClass(JCodeModel codeModel)
throws JClassAlreadyExistsException {
final String packageName = configuration.getPackageName();
final String className =
packageName.isEmpty() ? VOCABULARY_CLASS : packageName + PACKAGE_SEPARATOR + VOCABULARY_CLASS;
final JDefinedClass cls = codeModel._class(className);
generateAuthorshipDoc(cls);
return cls;
}
private void generateAuthorshipDoc(JDocCommentable javaElem) {
javaElem.javadoc().add("This class was generated by OWL2Java " + VERSION);
}
/**
* Generates only vocabulary of the loaded ontology.
*
* @param ontology Ontology from which the vocabulary should be generated
* @param context Integrity constraints context, if null is supplied, the whole ontology is interpreted as
* integrity constraints.
*/
public void generateVocabulary(final OWLOntology ontology, ContextDefinition context) {
try {
final JCodeModel cm = new JCodeModel();
this.voc = createVocabularyClass(cm);
generateVocabulary(ontology, cm, context);
writeOutModel(cm);
} catch (JClassAlreadyExistsException e) {
LOG.error("Vocabulary generation FAILED, because the Vocabulary class already exists.", e);
} catch (IOException e) {
LOG.error("Vocabulary file generation FAILED.", e);
}
}
private void writeOutModel(JCodeModel cm) throws IOException {
final File file = new File(configuration.getTargetDir());
file.mkdirs();
cm.build(file);
}
private void _generateObjectProperty(final OWLOntology ontology,
final JCodeModel cm,
final ContextDefinition context,
final String pkg,
final OWLClass clazz,
final JDefinedClass subj,
final org.semanticweb.owlapi.model.OWLObjectProperty prop,
final PropertiesType propertiesType) {
final ClassObjectPropertyComputer comp = new ClassObjectPropertyComputer(
clazz,
prop,
context.set,
ontology
);
if (Card.NO != comp.getCard()) {
JClass filler = ensureCreated(pkg, cm, comp.getFiller(), ontology, propertiesType);
final String fieldName = validJavaIDForIRI(prop.getIRI());
switch (comp.getCard()) {
case ONE:
break;
case MULTIPLE:
filler = cm.ref(java.util.Set.class).narrow(filler);
break;
case SIMPLELIST:
case LIST:
filler = cm.ref(java.util.List.class).narrow(filler);
break;
}
final JFieldVar fv = addField(fieldName, subj, filler);
generateJavadoc(ontology, prop, fv);
if (comp.getCard().equals(Card.SIMPLELIST)) {
fv.annotate(Sequence.class)
.param("type", SequenceType.simple);
}
fv.annotate(OWLObjectProperty.class).param("iri",
entities.get(prop));
JAnnotationArrayMember use = null;
for (ObjectParticipationConstraint ic : comp.getParticipationConstraints()) {
if (use == null) {
use = fv.annotate(ParticipationConstraints.class).paramArray("value");
}
JAnnotationUse u = use.annotate(
ParticipationConstraint.class).param(
// "owlClassIRI",
// ic.getSubject().getIRI().toString()).param(
// "owlPropertyIRI",
// ic.getPredicate().getIRI().toString()).param(
"owlObjectIRI", entities.get(ic.getObject()));
setParticipationConstraintCardinality(u, ic);
}
}
}
private void setParticipationConstraintCardinality(JAnnotationUse u,
cz.cvut.kbss.jopa.ic.api.ParticipationConstraint ic) {
if (ic.getMin() != 0) {
u.param("min", ic.getMin());
}
if (ic.getMin() != -1) {
u.param("max", ic.getMax());
}
}
private void _generateDataProperty(final OWLOntology ontology,
final JCodeModel cm,
final ContextDefinition context,
final OWLClass clazz,
final JDefinedClass subj,
final org.semanticweb.owlapi.model.OWLDataProperty prop) {
final ClassDataPropertyComputer comp = new ClassDataPropertyComputer(
clazz,
prop,
context.set,
ontology
);
if (!Card.NO.equals(comp.getCard())) {
final JType obj = cm._ref(DatatypeTransformer.transformOWLType(comp.getFiller()));
final String fieldName = validJavaIDForIRI(prop.getIRI());
JFieldVar fv;
if (Card.MULTIPLE.equals(comp.getCard())) {
fv = addField(fieldName, subj, cm.ref(java.util.Set.class)
.narrow(obj));
} else if (Card.ONE.equals(comp.getCard())) {
fv = addField(fieldName, subj, obj);
} else {
assert false : "Unknown cardinality type";
return;
}
generateJavadoc(ontology, prop, fv);
fv.annotate(OWLDataProperty.class).param("iri", entities.get(prop));
JAnnotationArrayMember use = null;
for (DataParticipationConstraint ic : comp.getParticipationConstraints()) {
if (use == null) {
use = fv.annotate(ParticipationConstraints.class).paramArray("value");
}
JAnnotationUse u = use.annotate(ParticipationConstraint.class)
.param("owlObjectIRI", comp.getFiller().getIRI().toString());
setParticipationConstraintCardinality(u, ic);
}
}
}
private void _generateModel(final OWLOntology ontology, final JCodeModel cm,
final ContextDefinition context, final String pkg) {
LOG.info("Generating model ...");
final PropertiesType propertiesType = configuration.getPropertiesType();
context.classes.add(ontology.getOWLOntologyManager().getOWLDataFactory().getOWLThing());
for (final OWLClass clazz : context.classes) {
LOG.info(" Generating class '{}'.", clazz);
final JDefinedClass subj = ensureCreated(pkg, cm, clazz, ontology, propertiesType);
context.set.getClassIntegrityConstraints(clazz).forEach((ic) -> {
if (ic instanceof AtomicSubClassConstraint) {
final AtomicSubClassConstraint icc = (AtomicSubClassConstraint) ic;
subj._extends(ensureCreated(pkg, cm, icc.getSupClass(), ontology,
propertiesType));
}
});
for (final org.semanticweb.owlapi.model.OWLObjectProperty prop : context
.objectProperties) {
_generateObjectProperty(ontology, cm, context, pkg, clazz, subj, prop,
propertiesType);
}
for (org.semanticweb.owlapi.model.OWLDataProperty prop : context.dataProperties) {
_generateDataProperty(ontology, cm, context, clazz, subj, prop);
}
}
}
private void generateVocabulary(final OWLOntology o, final JCodeModel cm, ContextDefinition context) {
final Collection<OWLEntity> col = new LinkedHashSet<>();
col.add(o.getOWLOntologyManager().getOWLDataFactory().getOWLThing());
col.addAll(context.classes);
col.addAll(context.objectProperties);
col.addAll(context.dataProperties);
col.addAll(context.annotationProperties);
col.addAll(context.individuals);
o.getOWLOntologyManager().ontologies().forEach(onto -> onto.getOntologyID().getOntologyIRI().ifPresent(iri -> {
final String fieldName = ensureUniqueIdentifier("ONTOLOGY_IRI_" + validJavaIDForIRI(iri));
voc.field(JMod.PUBLIC | JMod.STATIC | JMod.FINAL, String.class, fieldName, JExpr.lit(iri.toString()));
}));
final Set<IRI> visitedProperties = new HashSet<>(col.size());
for (final OWLEntity c : col) {
final Optional<String> prefix = resolveFieldPrefix(c, visitedProperties);
if (!prefix.isPresent()) {
continue;
}
final String sFieldName = ensureUniqueIdentifier(
PREFIX_STRING + prefix.get() + validJavaIDForIRI(c.getIRI()));
final JFieldVar fv1 = voc.field(JMod.PUBLIC | JMod.STATIC
| JMod.FINAL, String.class, sFieldName, JExpr.lit(c.getIRI().toString()));
if (configuration.shouldGenerateOwlapiIris()) {
voc.field(JMod.PUBLIC | JMod.STATIC | JMod.FINAL, IRI.class,
sFieldName.substring(PREFIX_STRING.length()),
cm.ref(IRI.class).staticInvoke("create").arg(fv1));
}
generateJavadoc(o, c, fv1);
entities.put(c, voc.staticRef(fv1));
}
}
private Optional<String> resolveFieldPrefix(OWLEntity c, Set<IRI> visitedProperties) {
if (c.isOWLClass()) {
return Optional.of(PREFIX_CLASS);
} else if (c.isOWLDatatype()) {
return Optional.of(PREFIX_DATATYPE);
} else if (c.isOWLDataProperty() || c.isOWLObjectProperty() || c.isOWLAnnotationProperty()) {
if (visitedProperties.contains(c.getIRI())) {
LOG.debug("Property with IRI {} already processed. Skipping.", c.getIRI());
return Optional.empty();
}
visitedProperties.add(c.getIRI());
return Optional.of(PREFIX_PROPERTY);
} else if (c.isOWLNamedIndividual()) {
return Optional.of(PREFIX_INDIVIDUAL);
}
return Optional.of("");
}
private String ensureUniqueIdentifier(String id) {
final StringBuilder sb = new StringBuilder(id);
while (voc.fields().keySet().contains(sb.toString())) {
sb.append("_A");
}
return sb.toString();
}
/**
* Generates Javadoc from rdfs:comment annotation (if present).
*
* @param ontology Ontology from which the model/vocabulary is being generated
* @param owlEntity Annotated entity
* @param javaElem Element to document with Javadoc
*/
private boolean generateJavadoc(OWLOntology ontology, OWLEntity owlEntity, JDocCommentable javaElem) {
if (!configuration.shouldGenerateJavadoc()) {
return false;
}
final Optional<OWLAnnotation> ann = EntitySearcher.getAnnotations(owlEntity, ontology)
.filter(a -> a.getProperty().isComment()).findFirst();
ann.ifPresent(a -> a.getValue().asLiteral().ifPresent(lit -> javaElem.javadoc().add(lit.getLiteral())));
return ann.isPresent() && ann.get().getValue().isLiteral();
}
private JDefinedClass create(final String pkg, final JCodeModel cm, final OWLClass clazz,
final OWLOntology ontology, final PropertiesType propertiesType) {
JDefinedClass cls;
String name = pkg + PACKAGE_SEPARATOR + javaClassId(ontology, clazz);
try {
cls = cm._class(name);
cls.annotate(cz.cvut.kbss.jopa.model.annotations.OWLClass.class).param("iri", entities.get(clazz));
cls._implements(Serializable.class);
generateClassJavadoc(ontology, clazz, cls);
// RDFS label
final JClass ftLabel = cm.ref(String.class);
final JFieldVar fvLabel = addField("name", cls, ftLabel);
fvLabel.annotate(OWLAnnotationProperty.class).param("iri", cm.ref(RDFS.class).staticRef("LABEL"));
// DC description
final JClass ftDescription = cm.ref(String.class);
final JFieldVar fvDescription = addField("description", cls, ftDescription);
fvDescription.annotate(OWLAnnotationProperty.class)
.param("iri", cm.ref(CommonVocabulary.class).staticRef("DC_DESCRIPTION"));
// @Types Set<String> types;
final JClass ftTypes = cm.ref(Set.class).narrow(String.class);
final JFieldVar fvTypes = addField("types", cls, ftTypes);
fvTypes.annotate(Types.class);
// @Id(generated = true) protected String id;
final JClass ftId = cm.ref(String.class);
final JFieldVar fvId = addField("id", cls, ftId);
JAnnotationUse a = fvId.annotate(Id.class);
a.param("generated", true);
// @Properties public final Map<String,Set<String>> properties;
final Class propertiesTypeC = (propertiesType == PropertiesType.object ? Object.class : String.class);
final JClass ftProperties = cm.ref(Map.class)
.narrow(cm.ref(String.class), cm.ref(Set.class).narrow(propertiesTypeC));
final JFieldVar fvProperties = addField("properties", cls, ftProperties);
fvProperties.annotate(Properties.class);
} catch (JClassAlreadyExistsException e) {
LOG.trace("Class already exists. Using the existing version. {}", e.getMessage());
cls = cm._getClass(name);
}
return cls;
}
private String javaClassId(OWLOntology ontology, OWLClass owlClass) {
final Optional<OWLAnnotation> res = EntitySearcher.getAnnotations(owlClass, ontology)
.filter(a -> isJavaClassNameAnnotation(a) &&
a.getValue().isLiteral()).findFirst();
if (res.isPresent()) {
return res.get().getValue().asLiteral().get().getLiteral();
} else {
return toJavaNotation(validJavaIDForIRI(owlClass.getIRI()));
}
}
private void generateClassJavadoc(OWLOntology ontology, OWLEntity owlEntity, JDocCommentable javaElem) {
final boolean generated = generateJavadoc(ontology, owlEntity, javaElem);
if (generated) {
javaElem.javadoc().add("\n\n");
}
generateAuthorshipDoc(javaElem);
}
private JDefinedClass ensureCreated(final String pkg, final JCodeModel cm, final OWLClass clazz,
final OWLOntology ontology, final PropertiesType propertiesType) {
if (!classes.containsKey(clazz)) {
classes.put(clazz, create(pkg, cm, clazz, ontology, propertiesType));
}
return classes.get(clazz);
}
private boolean isJavaClassNameAnnotation(OWLAnnotation a) {
final String classNameProperty = (String) configuration.getCliParams()
.valueOf(Option.JAVA_CLASSNAME_ANNOTATION.arg);
return a.getProperty().getIRI()
.equals(IRI.create(classNameProperty != null ? classNameProperty : Constants.P_CLASS_NAME));
}
/**
* Converts a class name to the Java camel case notation
*
* @param className Generated class name
* @return Converted class name
*/
private String toJavaNotation(String className) {
StringBuilder result = new StringBuilder();
for (String w : className.split("_"))
if (!w.isEmpty())
result.append(w.substring(0, 1).toUpperCase()).append(w.substring(1));
return result.toString();
}
}