Skip to content

Package: JavaTransformer

JavaTransformer

nameinstructionbranchcomplexitylinemethod
JavaTransformer()
M: 0 C: 13
100%
M: 0 C: 0
100%
M: 0 C: 1
100%
M: 0 C: 3
100%
M: 0 C: 1
100%
_generateModel(OWLOntology, JCodeModel, ContextDefinition, String)
M: 30 C: 279
90%
M: 9 C: 27
75%
M: 9 C: 11
55%
M: 6 C: 65
92%
M: 0 C: 1
100%
addField(String, JDefinedClass, JType)
M: 13 C: 78
86%
M: 1 C: 1
50%
M: 1 C: 1
50%
M: 1 C: 11
92%
M: 0 C: 1
100%
ensureCreated(ContextDefinition, String, JCodeModel, OWLClass, OWLOntology)
M: 5 C: 163
97%
M: 0 C: 2
100%
M: 0 C: 2
100%
M: 2 C: 31
94%
M: 0 C: 1
100%
generateModel(OWLOntology, ContextDefinition, String, String, boolean)
M: 11 C: 47
81%
M: 0 C: 0
100%
M: 0 C: 1
100%
M: 4 C: 7
64%
M: 0 C: 1
100%
generateVocabulary(OWLOntology, ContextDefinition, String, String, boolean)
M: 11 C: 30
73%
M: 0 C: 0
100%
M: 0 C: 1
100%
M: 4 C: 6
60%
M: 0 C: 1
100%
generateVocabulary(OWLOntology, JCodeModel, ContextDefinition, boolean)
M: 18 C: 176
91%
M: 5 C: 15
75%
M: 4 C: 7
64%
M: 4 C: 32
89%
M: 0 C: 1
100%
isValidJavaClassName(OWLAnnotation, ContextDefinition)
M: 0 C: 7
100%
M: 0 C: 0
100%
M: 0 C: 1
100%
M: 0 C: 2
100%
M: 0 C: 1
100%
javaClassId(OWLOntology, OWLClass, ContextDefinition)
M: 9 C: 24
73%
M: 3 C: 3
50%
M: 2 C: 2
50%
M: 2 C: 5
71%
M: 0 C: 1
100%
static {...}
M: 0 C: 207
100%
M: 0 C: 0
100%
M: 0 C: 1
100%
M: 0 C: 2
100%
M: 0 C: 1
100%
validJavaID(String)
M: 9 C: 21
70%
M: 1 C: 1
50%
M: 1 C: 1
50%
M: 1 C: 3
75%
M: 0 C: 1
100%
validJavaIDForIRI(IRI)
M: 0 C: 20
100%
M: 0 C: 2
100%
M: 0 C: 2
100%
M: 0 C: 4
100%
M: 0 C: 1
100%
writeOutModel(JCodeModel, String)
M: 0 C: 12
100%
M: 0 C: 0
100%
M: 0 C: 1
100%
M: 0 C: 4
100%
M: 0 C: 1
100%

Coverage

1: /**
2: * Copyright (C) 2016 Czech Technical University in Prague
3: *
4: * This program is free software: you can redistribute it and/or modify it under
5: * the terms of the GNU General Public License as published by the Free Software
6: * Foundation, either version 3 of the License, or (at your option) any
7: * later version.
8: *
9: * This program is distributed in the hope that it will be useful, but WITHOUT
10: * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
11: * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
12: * details. You should have received a copy of the GNU General Public License
13: * along with this program. If not, see <http://www.gnu.org/licenses/>.
14: */
15: package cz.cvut.kbss.jopa.owl2java;
16:
17: import com.sun.codemodel.*;
18: import cz.cvut.kbss.jopa.CommonVocabulary;
19: import cz.cvut.kbss.jopa.model.annotations.*;
20: import cz.cvut.kbss.jopa.model.annotations.OWLAnnotationProperty;
21: import cz.cvut.kbss.jopa.model.annotations.OWLDataProperty;
22: import cz.cvut.kbss.jopa.model.annotations.OWLObjectProperty;
23: import cz.cvut.kbss.jopa.model.annotations.Properties;
24: import cz.cvut.kbss.jopa.model.ic.DataParticipationConstraint;
25: import cz.cvut.kbss.jopa.model.ic.ObjectParticipationConstraint;
26: import cz.cvut.kbss.jopa.owlapi.DatatypeTransformer;
27: import org.semanticweb.owlapi.model.*;
28: import org.semanticweb.owlapi.model.OWLClass;
29: import org.slf4j.Logger;
30: import org.slf4j.LoggerFactory;
31:
32: import java.io.File;
33: import java.io.IOException;
34: import java.util.*;
35:
36: import static cz.cvut.kbss.jopa.owl2java.Constants.*;
37:
38: public class JavaTransformer {
39:
40: private static final Logger LOG = LoggerFactory.getLogger(OWL2JavaTransformer.class);
41: private JDefinedClass voc;
42:
43: private Map<OWLEntity, JFieldRef> entities = new HashMap<>();
44: private Map<OWLClass, JDefinedClass> classes = new HashMap<>();
45:
46: private JFieldVar addField(final String name, final JDefinedClass cls,
47: final JType fieldType) {
48: String newName = name;
49:
50: int i = 0;
51:• while (cls.fields().containsKey(newName)) {
52: newName = name + "" + (++i);
53: }
54:
55: final JFieldVar fvId = cls.field(JMod.PROTECTED, fieldType, newName);
56: final String fieldName = fvId.name().substring(0, 1).toUpperCase() + fvId.name().substring(1);
57: final JMethod mSetId = cls.method(JMod.PUBLIC, void.class, "set" + fieldName);
58: final JVar v = mSetId.param(fieldType, fvId.name());
59: mSetId.body().assign(JExpr._this().ref(fvId), v);
60: final JMethod mGetId = cls.method(JMod.PUBLIC, fieldType, "get" + fieldName);
61: mGetId.body()._return(fvId);
62: return fvId;
63: }
64:
65: public void generateModel(final OWLOntology ontology,
66: final ContextDefinition context, final String pkg, String targetDir, boolean withOWLAPI) {
67:
68: try {
69: final JCodeModel cm = new JCodeModel();
70: voc = cm._class(pkg + PACKAGE_SEPARATOR + VOCABULARY_CLASS);
71: generateVocabulary(ontology, cm, context, withOWLAPI);
72: _generateModel(ontology, cm, context, pkg + PACKAGE_SEPARATOR + MODEL_PACKAGE + PACKAGE_SEPARATOR);
73: writeOutModel(cm, targetDir);
74: } catch (JClassAlreadyExistsException e1) {
75: LOG.error("Transformation FAILED.", e1);
76: } catch (IOException e) {
77: LOG.error("File generation FAILED.", e);
78: }
79: }
80:
81: /**
82: * Generates only vocabulary of the loaded ontology.
83: *
84: * @param context Integrity constraints context, if null is supplied, the whole ontology is interpreted as integrity constraints.
85: * @param targetDir Directory into which the vocabulary file will be generated
86: * @param pkg Package
87: * @param withOWLAPI Whether OWLAPI-based IRIs of the generated vocabulary items should be created as well
88: */
89: public void generateVocabulary(final OWLOntology ontology, ContextDefinition context, String pkg, String targetDir,
90: boolean withOWLAPI) {
91: try {
92: final JCodeModel cm = new JCodeModel();
93: this.voc = cm._class(pkg + PACKAGE_SEPARATOR + VOCABULARY_CLASS);
94: generateVocabulary(ontology, cm, context, withOWLAPI);
95: writeOutModel(cm, targetDir);
96: } catch (JClassAlreadyExistsException e) {
97: LOG.error("Vocabulary generation FAILED, because the Vocabulary class already exists.", e);
98: } catch (IOException e) {
99: LOG.error("Vocabulary file generation FAILED.", e);
100: }
101: }
102:
103: private void writeOutModel(JCodeModel cm, String targetDir) throws IOException {
104: final File file = new File(targetDir);
105: file.mkdirs();
106: cm.build(file);
107: }
108:
109: private void _generateModel(final OWLOntology ontology, final JCodeModel cm,
110: final ContextDefinition context, final String pkg) {
111: LOG.info("Generating model ...");
112:
113: context.classes.add(ontology.getOWLOntologyManager().getOWLDataFactory().getOWLThing());
114:
115:• for (final OWLClass clazz : context.classes) {
116: LOG.info(" Generating class '{}'.", clazz);
117: final JDefinedClass subj = ensureCreated(context, pkg, cm, clazz, ontology);
118:
119:• for (final org.semanticweb.owlapi.model.OWLObjectProperty prop : context.objectProperties) {
120:
121: final IntegrityConstraintParserImpl.ClassObjectPropertyComputer comp = context.parser.new ClassObjectPropertyComputer(
122: clazz, prop,
123: ontology);
124:
125:• if (OWL2JavaTransformer.Card.NO.equals(comp.getCard())) {
126: continue;
127: }
128:
129: JClass filler = ensureCreated(context, pkg, cm,
130: comp.getObject(), ontology);
131: final String fieldName = validJavaIDForIRI(prop.getIRI());
132:
133:• switch (comp.getCard()) {
134: case ONE:
135: break;
136: case MULTIPLE:
137: filler = cm.ref(java.util.Set.class).narrow(filler);
138: break;
139: case SIMPLELIST:
140: case LIST:
141: filler = cm.ref(java.util.List.class).narrow(filler);
142: break;
143: }
144:
145: final JFieldVar fv = addField(fieldName, subj, filler);
146:
147:• if (comp.getCard().equals(OWL2JavaTransformer.Card.SIMPLELIST)) {
148: fv.annotate(Sequence.class)
149: .param("type", SequenceType.simple);
150: }
151:
152:
153: fv.annotate(OWLObjectProperty.class).param("iri",
154: entities.get(prop));
155:
156: JAnnotationArrayMember use = null;
157:• for (ObjectParticipationConstraint ic : comp
158: .getParticipationConstraints()) {
159:• if (use == null) {
160: use = fv.annotate(ParticipationConstraints.class)
161: .paramArray("value");
162: }
163: JAnnotationUse u = use.annotate(
164: ParticipationConstraint.class).param(
165: // "owlClassIRI",
166: // ic.getSubject().getIRI().toString()).param(
167: // "owlPropertyIRI",
168: // ic.getPredicate().getIRI().toString()).param(
169: "owlObjectIRI", entities.get(ic.getObject()));
170:• if (ic.getMin() != 0) {
171: u.param("min", ic.getMin());
172: }
173:
174:• if (ic.getMax() != -1) {
175: u.param("max", ic.getMax());
176: }
177: }
178: }
179:
180:• for (org.semanticweb.owlapi.model.OWLDataProperty prop : context.dataProperties) {
181: final IntegrityConstraintParserImpl.ClassDataPropertyComputer comp = context.parser
182: .getClassDataPropertyComputer(clazz, prop, ontology);
183:
184:• if (OWL2JavaTransformer.Card.NO.equals(comp.getCard())) {
185: continue;
186: }
187:
188: final JType obj = cm._ref(DatatypeTransformer
189: .transformOWLType(comp.getFiller()));
190:
191: final String fieldName = validJavaIDForIRI(
192: prop.getIRI());
193:
194: JFieldVar fv;
195:
196:• if (OWL2JavaTransformer.Card.MULTIPLE.equals(comp.getCard())) {
197: fv = addField(fieldName, subj, cm.ref(java.util.Set.class)
198: .narrow(obj));
199:• } else if (OWL2JavaTransformer.Card.ONE.equals(comp.getCard())) {
200: fv = addField(fieldName, subj, obj);
201: } else {
202: assert false : "Unknown cardinality type";
203: continue;
204: }
205:
206: fv.annotate(OWLDataProperty.class).param("iri",
207: entities.get(prop));
208:
209: JAnnotationArrayMember use = null;
210:• for (DataParticipationConstraint ic : comp
211: .getParticipationConstraints()) {
212:• if (use == null) {
213: use = fv.annotate(ParticipationConstraints.class)
214: .paramArray("value");
215: }
216:
217: JAnnotationUse u = use.annotate(
218: ParticipationConstraint.class).param(
219: // "owlClassIRI",
220: // ic.getSubject().getIRI().toString()).param(
221: // "owlPropertyIRI",
222: // ic.getPredicate().getIRI().toString()).param(
223: "owlObjectIRI", obj);
224:
225:• if (ic.getMin() != 0) {
226: u = u.param("min", ic.getMin());
227: }
228:
229:• if (ic.getMax() != -1) {
230: u = u.param("max", ic.getMax());
231: }
232: }
233: }
234: }
235: }
236:
237: private void generateVocabulary(final OWLOntology o, final JCodeModel cm, ContextDefinition context,
238: boolean withOWLAPI) {
239: final Collection<OWLEntity> col = new HashSet<>();
240: col.add(o.getOWLOntologyManager().getOWLDataFactory().getOWLThing());
241: col.addAll(context.classes);
242: col.addAll(context.objectProperties);
243: col.addAll(context.dataProperties);
244: col.addAll(context.annotationProperties);
245: col.addAll(context.individuals);
246:
247:• for (final OWLOntology s : o.getOWLOntologyManager().getOntologies()) {
248: IRI iri = s.getOntologyID().getOntologyIRI();
249: voc.field(JMod.PUBLIC | JMod.STATIC
250: | JMod.FINAL, String.class, "ONTOLOGY_IRI_" + validJavaIDForIRI(iri),
251: JExpr.lit(iri.toString()));
252: }
253:
254:• for (final OWLEntity c : col) {
255: String prefix = "";
256:
257:• if (c.isOWLClass()) {
258: prefix = "c_";
259:• } else if (c.isOWLDatatype()) {
260: prefix = "d_";
261:• } else if (c.isOWLDataProperty() || c.isOWLObjectProperty()
262:• || c.isOWLAnnotationProperty()) {
263: prefix = "p_";
264:• } else if (c.isOWLNamedIndividual()) {
265: prefix = "i_";
266: }
267:
268: String id = prefix + validJavaIDForIRI(c.getIRI());
269:
270:• while (voc.fields().keySet().contains("s_" + id)) {
271: id += "_A";
272: }
273:
274: final String sFieldName = "s_" + id;
275:
276: final JFieldVar fv1 = voc.field(JMod.PUBLIC | JMod.STATIC
277: | JMod.FINAL, String.class, sFieldName,
278: JExpr.lit(c.getIRI().toString()));
279:• if (withOWLAPI) {
280: voc.field(JMod.PUBLIC | JMod.STATIC | JMod.FINAL, IRI.class, id, cm
281: .ref(IRI.class).staticInvoke("create").arg(fv1));
282: }
283:
284: entities.put(c, voc.staticRef(fv1));
285: }
286: }
287:
288: private static String validJavaIDForIRI(final IRI iri) {
289:• if (iri.getFragment() != null) {
290: return validJavaID(iri.getFragment());
291: } else {
292: int x = iri.toString().lastIndexOf("/");
293: return validJavaID(iri.toString().substring(x + 1));
294: }
295: }
296:
297: private static String validJavaID(final String s) {
298: String res = s.trim().replace("-", "_").replace("'", "_quote_").replace(".", "_dot_").replace(',', '_');
299:• if (Arrays.binarySearch(keywords, res) >= 0) {
300: res = "_" + res;
301: }
302: return res;
303: }
304:
305:
306: private static final String[] keywords = {"abstract",
307: "assert",
308: "boolean",
309: "break",
310: "byte",
311: "case",
312: "catch",
313: "char",
314: "class",
315: "const",
316: "continue",
317: "default",
318: "do",
319: "double",
320: "else",
321: "enum",
322: "extends",
323: "final",
324: "finally",
325: "float",
326: "for",
327: "goto",
328: "if",
329: "implements",
330: "import",
331: "instanceof",
332: "int",
333: "interface",
334: "long",
335: "native",
336: "new",
337: "package",
338: "private",
339: "protected",
340: "public",
341: "return",
342: "short",
343: "static",
344: "strictfp",
345: "super",
346: "switch",
347: "synchronized",
348: "this",
349: "throw",
350: "throws",
351: "transient",
352: "try",
353: "void",
354: "volatile",
355: "while"};
356:
357: private String javaClassId(OWLOntology ontology, OWLClass owlClass, ContextDefinition ctx) {
358: final Set<OWLAnnotation> annotations = owlClass.getAnnotations(ontology);
359:• for (OWLAnnotation a : annotations) {
360:• if (isValidJavaClassName(a, ctx)) {
361:• if (a.getValue() instanceof OWLLiteral) {
362: return ((OWLLiteral) a.getValue()).getLiteral();
363: }
364: }
365: }
366: return validJavaIDForIRI(owlClass.getIRI());
367: }
368:
369: private JDefinedClass ensureCreated(final ContextDefinition ctx,
370: final String pkg, final JCodeModel cm, final OWLClass clazz,
371: final OWLOntology ontology) {
372:• if (classes.containsKey(clazz)) {
373: return classes.get(clazz);
374: }
375:
376: JDefinedClass cls;
377:
378: String name = pkg + javaClassId(ontology, clazz, ctx);
379:
380: try {
381: cls = cm._class(name);
382:
383: cls.annotate(
384: cz.cvut.kbss.jopa.model.annotations.OWLClass.class)
385: .param("iri", entities.get(clazz));
386:
387: final JDocComment dc = cls.javadoc();
388: dc.add("This class was generated by the OWL2Java tool version " + VERSION);
389:
390: // if (clazz.equals(f.getOWLThing())) {
391: // RDFS label
392: final JClass ftLabel = cm.ref(String.class);
393: final JFieldVar fvLabel = addField("name", cls, ftLabel);
394: fvLabel.annotate(OWLAnnotationProperty.class).param("iri",
395: cm.ref(CommonVocabulary.class).staticRef("RDFS_LABEL"));
396:
397: // DC description
398: final JClass ftDescription = cm.ref(String.class);
399: final JFieldVar fvDescription = addField("description", cls, ftDescription);
400: fvDescription.annotate(OWLAnnotationProperty.class).param("iri",
401: cm.ref(CommonVocabulary.class).staticRef("DC_DESCRIPTION"));
402:
403: // @Types Set<String> types;
404: final JClass ftTypes = cm.ref(Set.class).narrow(String.class);
405: final JFieldVar fvTypes = addField("types", cls, ftTypes);
406: fvTypes.annotate(Types.class);
407:
408: // @Id public final String id;
409: final JClass ftId = cm.ref(String.class);
410: final JFieldVar fvId = addField("id", cls, ftId);
411: JAnnotationUse a = fvId.annotate(Id.class);
412:
413: a.param("generated", true);
414:
415: // @Properties public final Map<String,Set<String>> properties;
416: final JClass ftProperties = cm.ref(Map.class).narrow(
417: cm.ref(String.class),
418: cm.ref(Set.class).narrow(String.class));
419: final JFieldVar fvProperties = addField("properties", cls,
420: ftProperties);
421: fvProperties.annotate(Properties.class);
422: // }
423:
424: } catch (JClassAlreadyExistsException e) {
425: cls = cm._getClass(name);
426: }
427: classes.put(clazz, cls);
428:
429: return cls;
430: }
431:
432: private boolean isValidJavaClassName(OWLAnnotation a, ContextDefinition ctx) {
433: // TODO Replace this hardcoded stuff with a configurable solution
434: return a.getProperty().getIRI()
435: .equals(IRI.create("http://krizik.felk.cvut.cz/ontologies/2009/ic.owl#javaClassName"));
436: // Annotation of annotation is currently not supported
437: // for (OWLAnnotation ctxAnn : a.getAnnotations()) {
438: // ctxAnn.getValue().accept(v);
439: // final String icContextName = v.getName();
440: // System.out.println("Context: " + icContextName);
441: // if (icContextName != null && icContextName.equals(ctx.name)) {
442: // return true;
443: // }
444: // }
445: }
446:
447: }