Skip to content

Package: OWL2JavaTransformer$ValidContextAnnotationValueVisitor

OWL2JavaTransformer$ValidContextAnnotationValueVisitor

nameinstructionbranchcomplexitylinemethod
OWL2JavaTransformer.ValidContextAnnotationValueVisitor(OWL2JavaTransformer)
M: 0 C: 9
100%
M: 0 C: 0
100%
M: 0 C: 1
100%
M: 0 C: 2
100%
M: 0 C: 1
100%
getName()
M: 0 C: 3
100%
M: 0 C: 0
100%
M: 0 C: 1
100%
M: 0 C: 1
100%
M: 0 C: 1
100%
visit(IRI)
M: 1 C: 0
0%
M: 0 C: 0
100%
M: 1 C: 0
0%
M: 1 C: 0
0%
M: 1 C: 0
0%
visit(OWLAnonymousIndividual)
M: 1 C: 0
0%
M: 0 C: 0
100%
M: 1 C: 0
0%
M: 1 C: 0
0%
M: 1 C: 0
0%
visit(OWLLiteral)
M: 0 C: 5
100%
M: 0 C: 0
100%
M: 0 C: 1
100%
M: 0 C: 2
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.SequencesVocabulary;
20: import cz.cvut.kbss.jopa.model.annotations.*;
21: import cz.cvut.kbss.jopa.model.annotations.OWLAnnotationProperty;
22: import cz.cvut.kbss.jopa.model.annotations.OWLDataProperty;
23: import cz.cvut.kbss.jopa.model.annotations.OWLObjectProperty;
24: import cz.cvut.kbss.jopa.model.annotations.Properties;
25: import cz.cvut.kbss.jopa.model.ic.DataParticipationConstraint;
26: import cz.cvut.kbss.jopa.model.ic.ObjectParticipationConstraint;
27: import cz.cvut.kbss.jopa.owl2java.IntegrityConstraintParserImpl.ClassDataPropertyComputer;
28: import cz.cvut.kbss.jopa.owl2java.IntegrityConstraintParserImpl.ClassObjectPropertyComputer;
29: import cz.cvut.kbss.jopa.owlapi.DatatypeTransformer;
30: import cz.cvut.kbss.jopa.util.MappingFileParser;
31: import org.semanticweb.owlapi.apibinding.OWLManager;
32: import org.semanticweb.owlapi.model.*;
33: import org.semanticweb.owlapi.model.OWLClass;
34: import org.semanticweb.owlapi.util.OWLOntologyMerger;
35: import org.slf4j.Logger;
36: import org.slf4j.LoggerFactory;
37:
38: import java.io.File;
39: import java.io.IOException;
40: import java.net.URI;
41: import java.util.*;
42:
43: import static cz.cvut.kbss.jopa.owl2java.Constants.*;
44:
45: class ContextDefinition {
46: private final String name;
47: final Set<OWLClass> classes = new HashSet<>();
48: final Set<org.semanticweb.owlapi.model.OWLObjectProperty> objectProperties = new HashSet<>();
49: final Set<org.semanticweb.owlapi.model.OWLDataProperty> dataProperties = new HashSet<>();
50: final Set<org.semanticweb.owlapi.model.OWLAnnotationProperty> annotationProperties = new HashSet<>();
51:
52: ContextDefinition(String name) {
53: this.name = name;
54: }
55:
56: final Set<OWLAxiom> axioms = new HashSet<>();
57:
58: final IntegrityConstraintParserImpl parser = new IntegrityConstraintParserImpl(
59: OWLManager.getOWLDataFactory(), this);
60: }
61:
62: public class OWL2JavaTransformer {
63:
64: private static final Logger LOG = LoggerFactory.getLogger(OWL2JavaTransformer.class);
65:
66: private static final List<IRI> skipped = Arrays
67: .asList(IRI.create(SequencesVocabulary.c_Collection), IRI.create(SequencesVocabulary.c_List),
68: IRI.create(SequencesVocabulary.c_OWLSimpleList),
69: IRI.create(SequencesVocabulary.c_OWLReferencedList));
70:
71: private OWLDataFactory f;
72:
73: private OWLOntology merged;
74:
75: private Set<OWLOntology> imports;
76:
77: private Map<OWLClass, JDefinedClass> classes = new HashMap<>();
78:
79: private Map<OWLEntity, JFieldRef> entities = new HashMap<>();
80:
81: // private Map<JFieldRef, JAnnotationArrayMember> constraints = new
82: // HashMap<JFieldRef, JAnnotationArrayMember>();
83:
84: private JDefinedClass voc;
85:
86: private Map<String, ContextDefinition> contexts = new HashMap<>();
87:
88: public Collection<String> listContexts() {
89: return contexts.keySet();
90: }
91:
92: private class ValidContextAnnotationValueVisitor implements OWLAnnotationValueVisitor {
93: private String name = null;
94:
95: String getName() {
96: return name;
97: }
98:
99: public void visit(IRI iri) {
100: }
101:
102: public void visit(OWLAnonymousIndividual individual) {
103: }
104:
105: public void visit(OWLLiteral literal) {
106: name = literal.getLiteral();
107: }
108: }
109:
110: private final ValidContextAnnotationValueVisitor v = new ValidContextAnnotationValueVisitor();
111:
112: public void setOntology(final OWLOntology merged, final Set<OWLOntology> imports, boolean includeImports) {
113:
114: f = merged.getOWLOntologyManager().getOWLDataFactory();
115:
116: this.imports = imports;
117:
118: LOG.info("Parsing integrity constraints");
119: // final IntegrityConstraintParserImpl icp = new
120: // IntegrityConstraintParserImpl();
121:
122: // final Set<OWLAxiom> ics = new HashSet<OWLAxiom>();
123:
124: for (final OWLAxiom a : merged.getAxioms()) {
125: for (final OWLAnnotation p : a.getAnnotations()) {
126: p.getValue().accept(v);
127: final String icContextName = v.getName();
128: if (icContextName == null) {
129: continue;
130: }
131:
132: ContextDefinition ctx = contexts.get(icContextName);
133:
134: if (ctx == null) {
135: ctx = new ContextDefinition(icContextName);
136: contexts.put(icContextName, ctx);
137: }
138:
139: LOG.debug("Found IC {} for context {}", a, icContextName);
140:
141: for (final OWLEntity e : a.getSignature()) {
142: if (e.isOWLClass() && !skipped.contains(e.getIRI())) {
143: ctx.classes.add(e.asOWLClass());
144: }
145: if (e.isOWLObjectProperty() && !skipped.contains(e.getIRI())) {
146: ctx.objectProperties.add(e.asOWLObjectProperty());
147: }
148: if (e.isOWLDataProperty() && !skipped.contains(e.getIRI())) {
149: ctx.dataProperties.add(e.asOWLDataProperty());
150: }
151: if (e.isOWLAnnotationProperty() && !skipped.contains(e.getIRI())) {
152: ctx.annotationProperties.add(e.asOWLAnnotationProperty());
153: }
154: }
155: ctx.axioms.add(a);
156: // ics.add(a);
157: }
158: }
159:
160: for (final ContextDefinition ctx : contexts.values()) {
161: ctx.parser.parse();
162: }
163:
164: LOG.info("Integrity constraints successfully parsed.");
165: }
166:
167: public void setOntology(final String owlOntologyName,
168: final String mappingFile, boolean includeImports) {
169: // reader
170: final OWLOntologyManager m = OWLManager.createOWLOntologyManager();
171:
172: if (mappingFile != null) {
173: LOG.info("Using mapping file '{}'.", mappingFile);
174:
175: final Map<URI, URI> map = MappingFileParser.getMappings(new File(mappingFile));
176: m.addIRIMapper(ontologyIRI -> {
177: final URI value = map.get(ontologyIRI.toURI());
178:
179: if (value == null) {
180: return null;
181: } else {
182: return IRI.create(value);
183: }
184: });
185: LOG.info("Mapping file successfully parsed.");
186: }
187:
188: LOG.info("Loading ontology {} ... ", owlOntologyName);
189: m.setSilentMissingImportsHandling(false);
190:
191: try {
192: m.loadOntology(org.semanticweb.owlapi.model.IRI.create(owlOntologyName));
193: merged = new OWLOntologyMerger(m)
194: .createMergedOntology(m, org.semanticweb.owlapi.model.IRI.create(owlOntologyName + "-generated"));
195: } catch (OWLOntologyCreationException e) {
196: LOG.error(e.getMessage(), e);
197: throw new IllegalArgumentException("Unable to load ontology " + owlOntologyName, e);
198: }
199:
200: setOntology(merged, m.getOntologies(), includeImports);
201: }
202:
203: private JFieldVar addField(final String name, final JDefinedClass cls,
204: final JType fieldType) {
205: String newName = name;
206:
207: int i = 0;
208: while (cls.fields().containsKey(newName)) {
209: newName = name + "" + (++i);
210: }
211:
212: final JFieldVar fvId = cls.field(JMod.PROTECTED, fieldType, newName);
213: final String fieldName = fvId.name().substring(0, 1).toUpperCase() + fvId.name().substring(1);
214: final JMethod mSetId = cls.method(JMod.PUBLIC, void.class, "set" + fieldName);
215: final JVar v = mSetId.param(fieldType, fvId.name());
216: mSetId.body().assign(JExpr._this().ref(fvId), v);
217: final JMethod mGetId = cls.method(JMod.PUBLIC, fieldType, "get" + fieldName);
218: mGetId.body()._return(fvId);
219: return fvId;
220: }
221:
222: private JDefinedClass ensureCreated(final ContextDefinition ctx,
223: final String pkg, final JCodeModel cm, final OWLClass clazz) {
224: if (classes.containsKey(clazz)) {
225: return classes.get(clazz);
226: }
227:
228: JDefinedClass cls;
229:
230: String name = pkg + javaClassId(clazz, ctx);
231:
232: try {
233: cls = cm._class(name);
234:
235: cls.annotate(
236: cz.cvut.kbss.jopa.model.annotations.OWLClass.class)
237: .param("iri", entities.get(clazz));
238:
239: final JDocComment dc = cls.javadoc();
240: dc.add("This class was generated by the OWL2Java tool version " + VERSION);
241:
242: // if (clazz.equals(f.getOWLThing())) {
243: // RDFS label
244: final JClass ftLabel = cm.ref(String.class);
245: final JFieldVar fvLabel = addField("name", cls, ftLabel);
246: fvLabel.annotate(OWLAnnotationProperty.class).param("iri",
247: cm.ref(CommonVocabulary.class).staticRef("RDFS_LABEL"));
248:
249: // DC description
250: final JClass ftDescription = cm.ref(String.class);
251: final JFieldVar fvDescription = addField("description", cls, ftDescription);
252: fvDescription.annotate(OWLAnnotationProperty.class).param("iri",
253: cm.ref(CommonVocabulary.class).staticRef("DC_DESCRIPTION"));
254:
255: // @Types Set<String> types;
256: final JClass ftTypes = cm.ref(Set.class).narrow(String.class);
257: final JFieldVar fvTypes = addField("types", cls, ftTypes);
258: fvTypes.annotate(Types.class);
259:
260: // @Id public final String id;
261: final JClass ftId = cm.ref(String.class);
262: final JFieldVar fvId = addField("id", cls, ftId);
263: JAnnotationUse a = fvId.annotate(Id.class);
264:
265: a.param("generated", true);
266:
267: // @Properties public final Map<String,Set<String>> properties;
268: final JClass ftProperties = cm.ref(Map.class).narrow(
269: cm.ref(String.class),
270: cm.ref(Set.class).narrow(String.class));
271: final JFieldVar fvProperties = addField("properties", cls,
272: ftProperties);
273: fvProperties.annotate(Properties.class);
274: // }
275:
276: // // public final Map<Object,Set<Object>> other;
277: // final JClass cSetN = cm.ref(Set.class).narrow(Object.class);
278: // final JClass cMapN =
279: // cm.ref(Map.class).narrow(cm.ref(Object.class),
280: // cSetN);
281: // final JFieldVar fv = cls.field(JMod.PRIVATE, cMapN, "others");
282: //
283: // // getOther()
284: // final JMethod m = cls.method(JMod.PUBLIC, cSetN, "findOther");
285: // final JVar p = m.param(Object.class, "property");
286: // m.body()._return(fv.invoke("get").arg(p));
287:
288: // for (OWLClass cx : classes.keySet()) {
289: // JDefinedClass cxc = classes.get(cx);
290: // if (r.isEntailed(OWLManager.getOWLDataFactory()
291: // .getOWLSubClassOfAxiom(cx, c))) {
292: // cxc = cxc._extends(cls);
293: // } else if (r.isEntailed(OWLManager.getOWLDataFactory()
294: // .getOWLSubClassOfAxiom(c, cx))) {
295: // cls = cls._extends(cxc);
296: // }
297: // }
298:
299: // TODO superClasses
300: // final OWLClass superClass = ctx.parser.getSuperClass(c);
301: // if ( superClass != null ) {
302: // ensureCreated(ctx, pkg, cm, superClass);
303: // cls._extends(classes.get(superClass));
304: // }
305: } catch (JClassAlreadyExistsException e) {
306: cls = cm._getClass(name);
307: }
308: classes.put(clazz, cls);
309:
310: return cls;
311: }
312:
313: private void generateVocabulary(final JCodeModel cm, boolean withOWLAPI) {
314: LOG.debug("Generating vocabulary...");
315:
316: final Collection<OWLEntity> col = new HashSet<>();
317: col.add(f.getOWLThing());
318: col.addAll(merged.getSignature());
319:
320: for (final OWLOntology s : imports) {
321: IRI iri = s.getOntologyID().getOntologyIRI();
322: voc.field(JMod.PUBLIC | JMod.STATIC
323: | JMod.FINAL, String.class, "ONTOLOGY_IRI_" + validJavaIDForIRI(iri),
324: JExpr.lit(iri.toString()));
325: }
326:
327: for (final OWLEntity c : col) {
328: String prefix = "";
329:
330: if (c.isOWLClass()) {
331: prefix = "c_";
332: } else if (c.isOWLDatatype()) {
333: prefix = "d_";
334: } else if (c.isOWLDataProperty() || c.isOWLObjectProperty()
335: || c.isOWLAnnotationProperty()) {
336: prefix = "p_";
337: } else if (c.isOWLNamedIndividual()) {
338: prefix = "i_";
339: }
340:
341: String id = prefix + validJavaIDForIRI(c.getIRI());
342:
343: while (voc.fields().keySet().contains("s_" + id)) {
344: id += "_A";
345: }
346:
347: final String sFieldName = "s_" + id;
348:
349: final JFieldVar fv1 = voc.field(JMod.PUBLIC | JMod.STATIC
350: | JMod.FINAL, String.class, sFieldName,
351: JExpr.lit(c.getIRI().toString()));
352: if (withOWLAPI) {
353: voc.field(JMod.PUBLIC | JMod.STATIC | JMod.FINAL, IRI.class, id, cm
354: .ref(IRI.class).staticInvoke("create").arg(fv1));
355: }
356:
357: entities.put(c, voc.staticRef(fv1));
358: }
359: }
360:
361: private static String validJavaIDForIRI(final IRI iri) {
362: if (iri.getFragment() != null) {
363: return validJavaID(iri.getFragment());
364: } else {
365: int x = iri.toString().lastIndexOf("/");
366: return validJavaID(iri.toString().substring(x + 1));
367: }
368: }
369:
370: private String javaClassId(OWLClass owlClass, ContextDefinition ctx) {
371: final Set<OWLAnnotation> annotations = owlClass.getAnnotations(merged);
372: for (OWLAnnotation a : annotations) {
373: if (isValidJavaClassName(a, ctx)) {
374: if (a.getValue() instanceof OWLLiteral) {
375: return ((OWLLiteral) a.getValue()).getLiteral();
376: }
377: }
378: }
379: return validJavaIDForIRI(owlClass.getIRI());
380: }
381:
382: private boolean isValidJavaClassName(OWLAnnotation a, ContextDefinition ctx) {
383: // TODO Replace this hardcoded stuff with a configurable solution
384: return a.getProperty().getIRI()
385: .equals(IRI.create("http://krizik.felk.cvut.cz/ontologies/2009/ic.owl#javaClassName"));
386: // Annotation of annotation is currently not supported
387: // for (OWLAnnotation ctxAnn : a.getAnnotations()) {
388: // ctxAnn.getValue().accept(v);
389: // final String icContextName = v.getName();
390: // System.out.println("Context: " + icContextName);
391: // if (icContextName != null && icContextName.equals(ctx.name)) {
392: // return true;
393: // }
394: // }
395: }
396:
397: private static final String[] keywords = {"abstract",
398: "assert",
399: "boolean",
400: "break",
401: "byte",
402: "case",
403: "catch",
404: "char",
405: "class",
406: "const",
407: "continue",
408: "default",
409: "do",
410: "double",
411: "else",
412: "enum",
413: "extends",
414: "final",
415: "finally",
416: "float",
417: "for",
418: "goto",
419: "if",
420: "implements",
421: "import",
422: "instanceof",
423: "int",
424: "interface",
425: "long",
426: "native",
427: "new",
428: "package",
429: "private",
430: "protected",
431: "public",
432: "return",
433: "short",
434: "static",
435: "strictfp",
436: "super",
437: "switch",
438: "synchronized",
439: "this",
440: "throw",
441: "throws",
442: "transient",
443: "try",
444: "void",
445: "volatile",
446: "while"};
447:
448: private static String validJavaID(final String s) {
449: String res = s.trim().replace("-", "_").replace("'", "_quote_").replace(".", "_dot_");
450: if (Arrays.binarySearch(keywords, res) >= 0) {
451: res = "_" + res;
452: }
453: return res;
454: }
455:
456: // class MaxICRestrictor implements IntegrityConstraintVisitor {
457: //
458: // final OWLClass s;
459: // final OWLProperty<?, ?> p;
460: // final OWLObject o;
461: // int max;
462: // boolean valid = false;
463: // String pkg;
464: //
465: // MaxICRestrictor(final OWLClass s, final OWLProperty<?, ?> po,
466: // final OWLObject oc, int max) {
467: // this.s = s;
468: // this.p = po;
469: // this.o = oc;
470: // this.max = max;
471: // }
472: //
473: //
474: // public void visit(ObjectParticipationConstraint cpc) {
475: // // if (!r.isEntailed(f.getOWLSubClassOfAxiom(s, cpc.getSubject()))
476: // // || !r.isEntailed(f.getOWLSubObjectPropertyOfAxiom(po, cpc
477: // // .getPredicate()))
478: // // || !r.isEntailed(f.getOWLSubClassOfAxiom(oc, cpc
479: // // .getObject()))) {
480: // // return;
481: // // }
482: // if (!s.equals(cpc.getSubject()) || !p.equals(cpc.getPredicate())
483: // || !o.equals(cpc.getObject())) {
484: // return;
485: // }
486: //
487: // valid = true;
488: //
489: // if (cpc.getMax() >= 0) {
490: // max = Math.min(cpc.getMax(), max);
491: // }
492: // }
493: //
494: //
495: // public void visit(DataParticipationConstraint cpc) {
496: // // if (!r.isEntailed(f.getOWLSubClassOfAxiom(s, cpc.getSubject()))
497: // // || !r.isEntailed(f.getOWLSubDataPropertyOfAxiom(pd, cpc
498: // // .getPredicate())) || !od.equals(cpc.getObject())) {
499: // // return;
500: // // }
501: // if (!s.equals(cpc.getSubject()) || !p.equals(cpc.getPredicate())
502: // || !o.equals(cpc.getObject())) {
503: // return;
504: // }
505: //
506: // valid = true;
507: //
508: // if (cpc.getMax() >= 0) {
509: // max = Math.min(cpc.getMax(), max);
510: // }
511: // }
512: // }
513: //
514: // private void generateAttribute(final String pkg, final OWLClass s,
515: // final org.semanticweb.owlapi.model.OWLObjectProperty p,
516: // final OWLClass o, final Collection<IntegrityConstraint> ics,
517: // final JCodeModel cm) {
518: // final JDefinedClass subj = ensureCreated(pkg, cm, s);
519: // final JDefinedClass obj = ensureCreated(pkg, cm, o);
520: //
521: // Set<ObjectParticipationConstraint> annotations = new
522: // HashSet<ObjectParticipationConstraint>();
523: //
524: // int max = Integer.MAX_VALUE;
525: //
526: // for (final IntegrityConstraint c : ics) {
527: // final MaxICRestrictor r = new MaxICRestrictor(s, p, o, max);
528: // c.accept(r);
529: // max = Math.min(max, r.max);
530: // if (r.valid)
531: // annotations.add((ObjectParticipationConstraint) c);
532: // }
533: //
534: // final String fieldName = validJavaID(p.getIRI().getFragment());
535: //
536: // if (r.isEntailed(f.getOWLSubClassOfAxiom(s, f
537: // .getOWLObjectMaxCardinality(1, p)))) {
538: // max = Math.min(max, 1);
539: // }
540: //
541: // final JFieldVar fv;
542: //
543: // if (max > 1) {
544: // fv = addField(fieldName, subj, cm.ref(java.util.Set.class).narrow(
545: // obj));
546: // } else {
547: // fv = addField(fieldName, subj, obj);
548: // }
549: //
550: // fv.annotate(OWLObjectProperty.class)
551: // .param("iri", entities.get(p)).param("fillerIri",
552: // entities.get(o));
553: //
554: // if (!annotations.isEmpty()) {
555: // JAnnotationArrayMember use = constraints.get(subj);
556: //
557: // if (use == null) {
558: // use = subj.annotate(ParticipationConstraints.class).paramArray("value");
559: // constraints.put(subj, use);
560: // }
561: //
562: // for (ObjectParticipationConstraint ic : annotations) {
563: // use.annotate(ParticipationConstraint.class).param(
564: // "owlClassIRI", ic.getSubject().getIRI().toString())
565: // .param("owlPropertyIRI",
566: // ic.getPredicate().getIRI().toString()).param(
567: // "owlObjectIRI",
568: // ic.getObject().getIRI().toString()).param(
569: // "min", ic.getMin()).param("max", ic.getMax());
570: // }
571: // }
572: // }
573: //
574: // private void generateAttribute(final String pkg, final OWLClass s,
575: // final org.semanticweb.owlapi.model.OWLDataProperty p,
576: // final OWLDatatype o, final Collection<IntegrityConstraint> ics,
577: // final JCodeModel cm) {
578: // final JDefinedClass subj = ensureCreated(pkg, cm, s);
579: // final JType obj = cm._ref(DatatypeTransformer.transformOWLType(o
580: // .asOWLDatatype()));
581: //
582: // Set<DataParticipationConstraint> annotations = new
583: // HashSet<DataParticipationConstraint>();
584: //
585: // int max = Integer.MAX_VALUE;
586: //
587: // for (final IntegrityConstraint c : ics) {
588: // final MaxICRestrictor r = new MaxICRestrictor(s, p, o, max);
589: // c.accept(r);
590: // max = Math.min(max, r.max);
591: // if (r.valid)
592: // annotations.add((DataParticipationConstraint) c);
593: // }
594: //
595: // final String fieldName = validJavaID(p.getIRI().getFragment());
596: //
597: // if (r.isEntailed(f.getOWLSubClassOfAxiom(s, f.getOWLDataMaxCardinality(
598: // 1, p)))) {
599: // max = Math.min(max, 1);
600: // }
601: //
602: // JFieldVar fv;
603: //
604: // if (max > 1) {
605: // fv = addField(fieldName, subj, cm.ref(java.util.Set.class).narrow(
606: // obj));
607: // } else {
608: // fv = addField(fieldName, subj, obj);
609: // }
610: //
611: // fv.annotate(OWLDataProperty.class).param("iri", p.getIRI().toString())
612: // .param("fillerIri", o.getIRI().toString());
613: //
614: // if (!annotations.isEmpty()) {
615: // JAnnotationArrayMember use = constraints.get(subj);
616: //
617: // if (use == null) {
618: // use = subj.annotate(ParticipationConstraints.class).paramArray("value");
619: // constraints.put(subj, use);
620: // }
621: //
622: // for (DataParticipationConstraint ic : annotations) {
623: // use.annotate(ParticipationConstraint.class).param(
624: // "owlClassIRI", ic.getSubject().getIRI().toString())
625: // .param("owlPropertyIRI",
626: // ic.getPredicate().getIRI().toString()).param(
627: // "owlObjectIRI",
628: // ic.getObject().getIRI().toString()).param(
629: // "min", ic.getMin()).param("max", ic.getMax());
630: // }
631: // }
632: //
633: // }
634:
635: private void generateModel(final JCodeModel cm,
636: final ContextDefinition context, final String pkg) {
637: LOG.info("Generating model ...");
638:
639: context.classes.add(f.getOWLThing());
640:
641: for (final OWLClass clazz : context.classes) {
642: LOG.info(" Generating class '{}'.", clazz);
643: final JDefinedClass subj = ensureCreated(context, pkg, cm, clazz);
644:
645: for (final org.semanticweb.owlapi.model.OWLObjectProperty prop : context.objectProperties) {
646:
647: final ClassObjectPropertyComputer comp = context.parser.new ClassObjectPropertyComputer(clazz, prop,
648: merged);
649:
650: if (Card.NO.equals(comp.getCard())) {
651: continue;
652: }
653:
654: JClass filler = ensureCreated(context, pkg, cm,
655: comp.getObject());
656: final String fieldName = validJavaIDForIRI(prop.getIRI());
657:
658: switch (comp.getCard()) {
659: case ONE:
660: break;
661: case MULTIPLE:
662: filler = cm.ref(java.util.Set.class).narrow(filler);
663: break;
664: case SIMPLELIST:
665: case LIST:
666: filler = cm.ref(java.util.List.class).narrow(filler);
667: break;
668: }
669:
670: final JFieldVar fv = addField(fieldName, subj, filler);
671:
672: if (comp.getCard().equals(Card.SIMPLELIST)) {
673: fv.annotate(Sequence.class)
674: .param("type", SequenceType.simple);
675: }
676:
677:
678: fv.annotate(OWLObjectProperty.class).param("iri",
679: entities.get(prop));
680:
681: JAnnotationArrayMember use = null;
682: for (ObjectParticipationConstraint ic : comp
683: .getParticipationConstraints()) {
684: if (use == null) {
685: use = fv.annotate(ParticipationConstraints.class)
686: .paramArray("value");
687: }
688: JAnnotationUse u = use.annotate(
689: ParticipationConstraint.class).param(
690: // "owlClassIRI",
691: // ic.getSubject().getIRI().toString()).param(
692: // "owlPropertyIRI",
693: // ic.getPredicate().getIRI().toString()).param(
694: "owlObjectIRI", entities.get(ic.getObject()));
695: if (ic.getMin() != 0) {
696: u.param("min", ic.getMin());
697: }
698:
699: if (ic.getMax() != -1) {
700: u.param("max", ic.getMax());
701: }
702: }
703: }
704:
705: for (org.semanticweb.owlapi.model.OWLDataProperty prop : context.dataProperties) {
706: final ClassDataPropertyComputer comp = context.parser
707: .getClassDataPropertyComputer(clazz, prop, merged);
708:
709: if (Card.NO.equals(comp.getCard())) {
710: continue;
711: }
712:
713: final JType obj = cm._ref(DatatypeTransformer
714: .transformOWLType(comp.getFiller()));
715:
716: final String fieldName = validJavaIDForIRI(
717: prop.getIRI());
718:
719: JFieldVar fv;
720:
721: if (Card.MULTIPLE.equals(comp.getCard())) {
722: fv = addField(fieldName, subj, cm.ref(java.util.Set.class)
723: .narrow(obj));
724: } else if (Card.ONE.equals(comp.getCard())) {
725: fv = addField(fieldName, subj, obj);
726: } else {
727: assert false : "Unknown cardinality type";
728: continue;
729: }
730:
731: fv.annotate(OWLDataProperty.class).param("iri",
732: entities.get(prop));
733:
734: JAnnotationArrayMember use = null;
735: for (DataParticipationConstraint ic : comp
736: .getParticipationConstraints()) {
737: if (use == null) {
738: use = fv.annotate(ParticipationConstraints.class)
739: .paramArray("value");
740: }
741: JAnnotationUse u = use.annotate(
742: ParticipationConstraint.class).param(
743: // "owlClassIRI",
744: // ic.getSubject().getIRI().toString()).param(
745: // "owlPropertyIRI",
746: // ic.getPredicate().getIRI().toString()).param(
747: "owlObjectIRI", entities.get(ic.getObject()));
748: if (ic.getMin() != 0) {
749: u = u.param("min", ic.getMin());
750: }
751:
752: if (ic.getMax() != -1) {
753: u = u.param("max", ic.getMax());
754: }
755: }
756: }
757: }
758: }
759:
760: enum Card {
761: NO, ONE, MULTIPLE, LIST, SIMPLELIST, REFERENCEDLIST
762: }
763:
764: public void transform(String context, String p, String dir, boolean withOWLAPI) {
765: LOG.info("Transforming context '{}'.", context);
766:
767: verifyContextExistence(context);
768:
769: final JCodeModel cm = new JCodeModel();
770:
771: try {
772: voc = cm._class(p + PACKAGE_SEPARATOR + VOCABULARY_CLASS);
773:
774: generateVocabulary(cm, withOWLAPI);
775: generateModel(cm, contexts.get(context), p + PACKAGE_SEPARATOR + MODEL_PACKAGE + PACKAGE_SEPARATOR);
776:
777: writeOutModel(cm, dir);
778: LOG.info("Transformation SUCCESSFUL.");
779: } catch (JClassAlreadyExistsException e1) {
780: LOG.error("Transformation FAILED.", e1);
781: } catch (IOException e) {
782: LOG.error("File generation FAILED.", e);
783: }
784: }
785:
786: private void verifyContextExistence(String context) {
787: if (!contexts.containsKey(context)) {
788: throw new IllegalArgumentException(
789: "Context " + context + " not found. Existing contexts: " + listContexts());
790: }
791: }
792:
793: private void writeOutModel(JCodeModel cm, String targetDir) throws IOException {
794: final File file = new File(targetDir);
795: file.mkdirs();
796: cm.build(file);
797: }
798:
799: /**
800: * Generates only vocabulary of the loaded ontology.
801: *
802: * @param context Integrity constraints context
803: * @param targetDir Directory into which the vocabulary file will be generated
804: * @param withOwlapi Whether OWLAPI-based IRIs of the generated vocabulary items should be created as well
805: */
806: public void generateVocabulary(String context, String targetDir, boolean withOwlapi) {
807: LOG.info("Generating vocabulary for context '{}'.", context);
808:
809: verifyContextExistence(context);
810:
811: final JCodeModel cm = new JCodeModel();
812: try {
813: this.voc = cm._class(VOCABULARY_CLASS);
814: generateVocabulary(cm, withOwlapi);
815: writeOutModel(cm, targetDir);
816: } catch (JClassAlreadyExistsException e) {
817: LOG.error("Vocabulary generation FAILED, because the Vocabulary class already exists.", e);
818: } catch (IOException e) {
819: LOG.error("Vocabulary file generation FAILED.", e);
820: }
821: }
822: }