Skip to content

Method: lambda$getContexts$4(OWLAnnotation)

1: /**
2: * Copyright (C) 2020 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 cz.cvut.kbss.jopa.owl2java.config.TransformationConfiguration;
18: import cz.cvut.kbss.jopa.owl2java.exception.OWL2JavaException;
19: import cz.cvut.kbss.jopa.util.MappingFileParser;
20: import org.semanticweb.owlapi.apibinding.OWLManager;
21: import org.semanticweb.owlapi.model.*;
22: import org.semanticweb.owlapi.search.EntitySearcher;
23: import org.semanticweb.owlapi.util.OWLOntologyMerger;
24: import org.slf4j.Logger;
25: import org.slf4j.LoggerFactory;
26:
27: import javax.annotation.Nonnull;
28: import java.io.File;
29: import java.net.URI;
30: import java.util.*;
31: import java.util.function.Consumer;
32: import java.util.stream.Stream;
33:
34: public class OWL2JavaTransformer {
35:
36: private static final Logger LOG = LoggerFactory.getLogger(OWL2JavaTransformer.class);
37:
38: private OWLOntology ontology;
39:
40: private final ValidContextAnnotationValueVisitor v = new ValidContextAnnotationValueVisitor();
41:
42: private final ContextDefinition defaultContext = new ContextDefinition();
43: private Map<String, ContextDefinition> contexts = new HashMap<>();
44:
45: private boolean ignoreMissingImports;
46:
47: public Collection<String> listContexts() {
48: return contexts.keySet();
49: }
50:
51: public void ignoreMissingImports(boolean ignore) {
52: this.ignoreMissingImports = ignore;
53: }
54:
55: private OWLOntology getWholeOntology(final String owlOntologyName, final String mappingFile) {
56: // reader
57: final OWLOntologyManager m = OWLManager.createOWLOntologyManager();
58:
59: if (mappingFile != null) {
60: LOG.info("Using mapping file '{}'.", mappingFile);
61:
62: final Map<URI, URI> map = MappingFileParser.getMappings(new File(mappingFile));
63: m.getIRIMappers().add(ontologyIRI -> {
64: final URI value = map.get(ontologyIRI.toURI());
65:
66: if (value == null) {
67: return null;
68: } else {
69: return IRI.create(value);
70: }
71: });
72: LOG.info("Mapping file successfully parsed.");
73: }
74:
75: LOG.info("Loading ontology {}... ", owlOntologyName);
76: if (ignoreMissingImports) {
77: m.getOntologyConfigurator().setMissingImportHandlingStrategy(MissingImportHandlingStrategy.SILENT);
78: m.addMissingImportListener(e -> {
79: LOG.warn("Unable to import ontology {}.", e.getImportedOntologyURI());
80: LOG.debug("Error: {}", e.getCreationException().getMessage());
81: });
82: }
83:
84: try {
85: m.loadOntology(IRI.create(owlOntologyName));
86: return new OWLOntologyMerger(m).createMergedOntology(m, IRI.create(owlOntologyName + "-generated"));
87: } catch (OWLException | OWLRuntimeException e) {
88: LOG.error(e.getMessage(), e);
89: throw new OWL2JavaException("Unable to load ontology " + owlOntologyName, e);
90: }
91: }
92:
93: public void setOntology(final String owlOntologyName, final String mappingFile) {
94: this.ontology = getWholeOntology(owlOntologyName, mappingFile);
95:
96: LOG.debug("Parsing integrity constraints");
97:
98: ontology.axioms().forEach(a -> {
99: defaultContext.addAxiom(a);
100: for (final String icContextName : getContexts(a)) {
101: ContextDefinition ctx = getContextDefinition(icContextName);
102: ctx.addAxiom(a);
103: }
104: });
105: registerEntitiesInContexts();
106:
107: defaultContext.parse();
108: for (final ContextDefinition ctx : contexts.values()) {
109: ctx.parse();
110: }
111:
112: LOG.debug("Integrity constraints successfully parsed.");
113: }
114:
115: private void registerEntitiesInContexts() {
116: final Consumer<Stream<? extends OWLEntity>> consumer = stream -> stream.forEach(e -> {
117: defaultContext.add(e);
118: for (final String context : getContexts(e)) {
119: getContextDefinition(context).add(e);
120: }
121: });
122: consumer.accept(ontology.classesInSignature());
123: consumer.accept(ontology.objectPropertiesInSignature());
124: consumer.accept(ontology.dataPropertiesInSignature());
125: consumer.accept(ontology.annotationPropertiesInSignature());
126: }
127:
128: private ContextDefinition getContextDefinition(String icContextName) {
129: return contexts.computeIfAbsent(icContextName, name -> new ContextDefinition());
130: }
131:
132: private List<String> getContexts(final OWLAxiom a) {
133: final List<String> icContexts = new ArrayList<>();
134: a.annotations().filter(p -> p.getProperty().getIRI().toString().equals(Constants.P_IS_INTEGRITY_CONSTRAINT_FOR))
135: .forEach(p -> {
136: LOG.trace("Processing annotation : " + p);
137: p.getValue().accept(v);
138: final String icContextName = v.getName();
139: LOG.trace("CONTEXT:" + icContextName);
140: if (icContextName == null) {
141: return;
142: }
143: LOG.debug("Found IC {} for context {}", a, icContextName);
144: icContexts.add(icContextName);
145: });
146: return icContexts;
147: }
148:
149: private List<String> getContexts(final OWLEntity entity) {
150: final List<String> icContexts = new ArrayList<>();
151: EntitySearcher.getAnnotations(entity, ontology)
152: .filter(p -> p.getProperty().getIRI().toString().equals(Constants.P_IS_INTEGRITY_CONSTRAINT_FOR))
153: .forEach(p -> {
154: LOG.trace("Processing annotation : " + p);
155: p.getValue().accept(v);
156: final String icContextName = v.getName();
157: LOG.trace("CONTEXT:" + icContextName);
158: if (icContextName == null) {
159: return;
160: }
161: LOG.debug("Found OWLEntity declaration {} for context {}", entity, icContextName);
162: icContexts.add(icContextName);
163: });
164: return icContexts;
165: }
166:
167: private void verifyContextExistence(String context) {
168: if (!contexts.containsKey(context)) {
169: throw new IllegalArgumentException(
170: "Context " + context + " not found. Existing contexts: " + listContexts());
171: }
172: }
173:
174: public void transform(TransformationConfiguration transformConfig) {
175: final ContextDefinition def = getValidContext(transformConfig);
176: LOG.info("Transforming context ...");
177: final ObjectModel result = new JavaTransformer(transformConfig).generateModel(ontology, def);
178: result.writeModel(transformConfig.getTargetDir());
179: LOG.info("Transformation SUCCESSFUL.");
180: }
181:
182: private ContextDefinition getValidContext(TransformationConfiguration configuration) {
183: if (configuration.areAllAxiomsIntegrityConstraints()) {
184: LOG.info(" - for all axioms");
185: return defaultContext;
186: }
187: final String context = configuration.getContext();
188: verifyContextExistence(context);
189: LOG.info(" - for context '{}'.", context);
190: return contexts.get(context);
191: }
192:
193: /**
194: * Generates only vocabulary of the loaded ontology.
195: *
196: * @param transformConfig Configuration of the generation process
197: */
198: public void generateVocabulary(TransformationConfiguration transformConfig) {
199: LOG.info("Generating vocabulary ...");
200:
201: ContextDefinition def = getValidContext(transformConfig);
202: final ObjectModel result = new JavaTransformer(transformConfig).generateVocabulary(ontology, def);
203: result.writeModel(transformConfig.getTargetDir());
204: }
205:
206: private class ValidContextAnnotationValueVisitor implements OWLAnnotationValueVisitor {
207:
208: private String name;
209:
210: String getName() {
211: return name;
212: }
213:
214: @Override
215: public void visit(@Nonnull IRI iri) {
216: }
217:
218: @Override
219: public void visit(@Nonnull OWLAnonymousIndividual individual) {
220: }
221:
222: @Override
223: public void visit(@Nonnull OWLLiteral literal) {
224: this.name = literal.getLiteral();
225: }
226: }
227: }