Download this file

OWLExport.java    405 lines (342 with data), 20.2 kB

  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
/**
* Copyright (c) 2013/2014 Verein zur Foerderung der IT-Sicherheit in Oesterreich (SBA).
* The work has been developed in the TIMBUS Project and the above-mentioned are Members of the TIMBUS Consortium.
* TIMBUS is supported by the European Union under the 7th Framework Programme for research and technological
* development and demonstration activities (FP7/2007-2013) under grant agreement no. 269940.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including without
* limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTIBITLY, or FITNESS FOR A PARTICULAR
* PURPOSE. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise,
* unless required by applicable law or agreed to in writing, shall any Contributor be liable for damages, including
* any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this
* License or out of the use or inability to use the Work.
* See the License for the specific language governing permissions and limitation under the License.
*/
package net.timbusproject.context.converter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EObject;
import org.semanticweb.owlapi.apibinding.OWLManager;
import org.semanticweb.owlapi.io.FileDocumentTarget;
import org.semanticweb.owlapi.io.OWLXMLOntologyFormat;
import org.semanticweb.owlapi.model.AddAxiom;
import org.semanticweb.owlapi.model.AddImport;
import org.semanticweb.owlapi.model.IRI;
import org.semanticweb.owlapi.model.OWLAnnotation;
import org.semanticweb.owlapi.model.OWLAnnotationAssertionAxiom;
import org.semanticweb.owlapi.model.OWLClass;
import org.semanticweb.owlapi.model.OWLClassAssertionAxiom;
import org.semanticweb.owlapi.model.OWLDataFactory;
import org.semanticweb.owlapi.model.OWLDataProperty;
import org.semanticweb.owlapi.model.OWLDataPropertyAssertionAxiom;
import org.semanticweb.owlapi.model.OWLDeclarationAxiom;
import org.semanticweb.owlapi.model.OWLImportsDeclaration;
import org.semanticweb.owlapi.model.OWLLiteral;
import org.semanticweb.owlapi.model.OWLNamedIndividual;
import org.semanticweb.owlapi.model.OWLObjectProperty;
import org.semanticweb.owlapi.model.OWLObjectPropertyAssertionAxiom;
import org.semanticweb.owlapi.model.OWLOntology;
import org.semanticweb.owlapi.model.OWLOntologyCreationException;
import org.semanticweb.owlapi.model.OWLOntologyManager;
import org.semanticweb.owlapi.model.OWLOntologyStorageException;
import org.semanticweb.owlapi.vocab.OWL2Datatype;
import uk.ac.manchester.cs.owl.owlapi.OWL2DatatypeImpl;
import com.archimatetool.editor.model.viewpoints.IViewpoint;
import com.archimatetool.model.FolderType;
import com.archimatetool.model.IAccessRelationship;
import com.archimatetool.model.IArchimateElement;
import com.archimatetool.model.IArchimateModel;
import com.archimatetool.model.IDiagramModelObject;
import com.archimatetool.model.IFolder;
import com.archimatetool.model.IProperty;
import com.archimatetool.model.IRelationship;
import com.archimatetool.model.impl.ArchimateDiagramModel;
import com.archimatetool.model.impl.DiagramModelArchimateObject;
import com.archimatetool.model.impl.DiagramModelGroup;
/**
* Methods to export an Archimate Model to OWL (Web Ontology Language)
*
* @author Rudolf Mayer (rmayer@sba-research.org)
*/
public class OWLExport {
public static final String KEY_SCENARIOS_URL = "ScenariosURL";
private static final String KEY_DIOURL = "DIOURL";
public static final Properties owlExportProperties = new Properties();
static {
String propertiesFileName = "owlExport.properties";
URL resource = OWLExportPlugin.class.getResource(propertiesFileName);
try {
owlExportProperties.load(resource.openStream());
System.out.println();
System.out.println("\nLoaded OWL Export properties from " + resource);
System.out.println("Properties:");
System.out.println(owlExportProperties);
System.out.println("------------------------------\n");
} catch (Exception e) {
System.err.println("\nCould not load OWL Export properties, tried file with name '" + propertiesFileName + "'.");
e.printStackTrace();
// default: using the TIMBUS scenarios URL
owlExportProperties.put(KEY_SCENARIOS_URL, "http://timbus.teco.edu/ontologies/examples/");
owlExportProperties.put(KEY_DIOURL, "http://timbus.teco.edu/ontologies/DIO.owl");
System.out.println("==> Using default properties:");
System.out.println("\t" + owlExportProperties);
System.out.println();
}
}
/** a mapping of some Archimate relation names to the OWL names */
public static final HashMap<String, String> propertyNamesMap = new HashMap<String, String>();
static {
propertyNamesMap.put("access", "accesses");
propertyNamesMap.put("aggregation", "aggregates");
propertyNamesMap.put("assignment", "assignment");
propertyNamesMap.put("composition", "composedOf");
propertyNamesMap.put("flow", "flowTo");
propertyNamesMap.put("influence", "influencedBy");
propertyNamesMap.put("realisation", "realizes");
propertyNamesMap.put("specialisation", "specialization");
propertyNamesMap.put("triggering", "triggers");
propertyNamesMap.put("usedby", "usedBy");
}
/** subtypes of the relation "access" */
public static final String[] relationAccessTypes = { "hasAccessTypeWrite", "hasAccessTypeRead", "hasAccessTypeAccess",
"hasAccessTypeRead_Write" };
/** the default property names */
public static final String DEFAULT_PROPERTY = "association";
/** The URL of the TIMBUS DIO */
public static final String TIMBUS_DIO_URL = owlExportProperties.getProperty(KEY_DIOURL);
/** The IRI for the TIMBUS DIO, see {@link #TIMBUS_DIO_URL} */
public static final IRI TIMBUS_DIO_IRI = IRI.create(TIMBUS_DIO_URL);
/** Prefix on the OWL name */
public static final String SCENARIOS_PREFIX = owlExportProperties.getProperty(KEY_SCENARIOS_URL);
/** The types of folders in Archi */
public static final FolderType[] FOLDER_TYPES = { FolderType.BUSINESS, FolderType.APPLICATION, FolderType.TECHNOLOGY,
FolderType.MOTIVATION, FolderType.IMPLEMENTATION_MIGRATION, FolderType.CONNECTORS, FolderType.RELATIONS };
public static void exportToOwl(IArchimateModel model, File file) throws IOException {
exportToOwl(model, file, getDefaultIRI(file));
}
public static void exportToOwl(IArchimateModel model, File file, String iriThisOntology) throws IOException {
if (iriThisOntology == null || iriThisOntology.trim().length() == 0) {
iriThisOntology = getDefaultIRI(file);
}
// create Ontology manager
OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
OWLDataFactory df = OWLManager.getOWLDataFactory();
OWLOntology ontology;
try {
ontology = manager.createOntology(IRI.create(iriThisOntology));
} catch (OWLOntologyCreationException e) {
e.printStackTrace();
throw new IOException(e);
}
// import the DIO
OWLImportsDeclaration importDeclaraton = df.getOWLImportsDeclaration(TIMBUS_DIO_IRI);
manager.applyChange(new AddImport(ontology, importDeclaraton));
Set<OWLAnnotation> emptyAnnotations = Collections.<OWLAnnotation> emptySet();
for (FolderType folderType : FOLDER_TYPES) {
IFolder folder = model.getFolder(folderType);
List<EObject> elements = new ArrayList<EObject>((int) (folder.getElements().size() * 1.2));
Util.getElements(folder, elements);
for (EObject eObject : elements) {
if (eObject instanceof IArchimateElement) {
IArchimateElement element = (IArchimateElement) eObject;
String elementName = getOWLIRIFragment(element);
String elementClassName = element.eClass().getName();
if (eObject instanceof IRelationship) { // write relationships
IRelationship relationship = (IRelationship) eObject;
String sourceName = getOWLIRIFragment(relationship.getSource());
String tagetName = getOWLIRIFragment(relationship.getTarget());
OWLNamedIndividual source = df.getOWLNamedIndividual(IRI.create("#" + sourceName));
OWLNamedIndividual object = df.getOWLNamedIndividual(IRI.create("#" + tagetName));
// derive the name of the relation from the class name
String propertyName = relationship.eClass().getName().replace("Relationship", "");
if (propertyNamesMap.containsKey(propertyName.toLowerCase())) {
// some relations have a mapping to a better name
propertyName = propertyNamesMap.get(propertyName.toLowerCase());
} else {
propertyName = DEFAULT_PROPERTY;
}
if (eObject instanceof IAccessRelationship) {
// access relations have several subtypes, we add the correct name here
IAccessRelationship accessRelationship = (IAccessRelationship) eObject;
int accesstype = accessRelationship.getAccessType();
propertyName = relationAccessTypes[accesstype];
}
OWLObjectProperty property = df.getOWLObjectProperty(IRI.create(TIMBUS_DIO_URL + "#" + propertyName));
OWLObjectPropertyAssertionAxiom objectPropertyAssertion = df.getOWLObjectPropertyAssertionAxiom(property, source,
object);
manager.applyChange(new AddAxiom(ontology, objectPropertyAssertion));
} else { // write individuals (and data properties)
// writes the indiv with the ID as name
OWLNamedIndividual indiv = df.getOWLNamedIndividual(IRI.create("#" + elementName));
OWLDeclarationAxiom indivDeclaration = df.getOWLDeclarationAxiom(indiv);
manager.applyChange(new AddAxiom(ontology, indivDeclaration));
// add an rdfs:label property as annotation
String labelName = formatString(Util.replaceSpecialWhiteSpace(element.getName()));
OWLAnnotation annotation = df.getOWLAnnotation(df.getRDFSLabel(), df.getOWLLiteral(labelName));
OWLAnnotationAssertionAxiom annotationAssertionAxiom = df
.getOWLAnnotationAssertionAxiom(indiv.getIRI(), annotation);
manager.applyChange(new AddAxiom(ontology, annotationAssertionAxiom));
// add a class expression
OWLClass classExpression = df.getOWLClass(IRI.create(TIMBUS_DIO_URL + "#" + elementClassName));
OWLClassAssertionAxiom classAssertion = df.getOWLClassAssertionAxiom(classExpression, indiv);
manager.applyChange(new AddAxiom(ontology, classAssertion));
if (!element.getProperties().isEmpty()) { // add data properties
for (IProperty eProperty : element.getProperties()) {
OWLDataProperty property = df.getOWLDataProperty(IRI.create(TIMBUS_DIO_URL + "#" + eProperty.getKey()));
OWLLiteral owlLiteral = df.getOWLLiteral(eProperty.getValue(),
OWL2DatatypeImpl.getDatatype(OWL2Datatype.RDF_PLAIN_LITERAL));
OWLDataPropertyAssertionAxiom dataPropertyAssertion = df.getOWLDataPropertyAssertionAxiom(property, indiv,
owlLiteral, emptyAnnotations);
manager.applyChange(new AddAxiom(ontology, dataPropertyAssertion));
}
}
}
}
}
}
FileDocumentTarget fileTarget = new FileDocumentTarget(file);
try {
manager.saveOntology(ontology, new OWLXMLOntologyFormat(), fileTarget);
} catch (OWLOntologyStorageException e) {
e.printStackTrace();
}
}
/**
* Returns a valid IRI fragment - according to http://sourceforge.net/p/owlapi/mailman/owlapi-developer/thread/CAHYxBS
* -dW+FUFLDPZOtbFL1tROZH8W0QmLu8ye9W5L-kCcMPVA@mail.gmail.com/, it must not start with a number, which is however what Archi generates
* as IDs...
*/
private static String getOWLIRIFragment(IArchimateElement element) {
return "i" + element.getId();
}
public static String getDefaultIRI(File file) {
return SCENARIOS_PREFIX + file.getName();
}
/** Exports the layout of the layered view ({@link IViewpoint#LAYERED_VIEWPOINT}) of a model to a CSV separated file */
public static void exportLayout(IArchimateModel model, File layoutFile, File owlFile) throws FileNotFoundException {
exportLayout(layoutFile, getDefaultIRI(owlFile), getLayeredView(model));
}
public static boolean exportLayout(IArchimateModel model, File layoutFile, String ontologyIRI, String viewName)
throws FileNotFoundException {
ArchimateDiagramModel view = null;
if (viewName != null) {
System.out.print("Trying to find view '" + viewName + "'... ");
view = getViewByName(model, viewName);
System.out.println(view != null ? "found" : "not found");
}
if (view == null) {
System.out.print("Trying to find layered view... ");
view = getLayeredView(model);
System.out.println(view != null ? "found" : "not found");
}
if (view == null) {
System.out.print("Checking if there is only one view... ");
EList<EObject> elements = model.getFolder(FolderType.DIAGRAMS).getElements();
if (elements.size() == 1) {
view = (ArchimateDiagramModel) elements.get(0);
System.out.println("succes, using view " + view.getName());
} else if (elements.size() == 0) {
System.out.println("no views found at all!");
} else {
ArrayList<String> viewNames = new ArrayList<String>();
for (EObject eObject : elements) {
viewNames.add(((ArchimateDiagramModel) eObject).getName());
}
System.out.println("found " + elements.size() + " views, please specifiy one of " + viewNames);
}
}
if (ontologyIRI == null || ontologyIRI.trim().length() == 0) {
ontologyIRI = getDefaultIRI(layoutFile);
System.out.println("Ontology IRI not specified, defaulting to " + ontologyIRI + ", computed from file " + layoutFile.getName());
}
return exportLayout(layoutFile, ontologyIRI, view);
}
/** Exports the layout of a model to a CSV separated file */
public static boolean exportLayout(File layoutFile, String defaultIRI, ArchimateDiagramModel view) throws FileNotFoundException {
if (view != null) {
EList<IDiagramModelObject> children = view.getChildren();
ArrayList<String> export = new ArrayList<String>();
HashMap<String, String> iriNameMap = new HashMap<String, String>();
exportChildrenLayout(children, iriNameMap, 0, 0, export, defaultIRI);
Collections.sort(export);
PrintWriter pw = new PrintWriter(layoutFile);
for (String string : export) {
pw.println("# " + iriNameMap.get(string));
pw.println(string);
}
pw.flush();
pw.close();
return true;
} else {
return false;
}
}
public static ArchimateDiagramModel getLayeredView(IArchimateModel model) {
for (EObject eObject : model.getFolder(FolderType.DIAGRAMS).getElements()) {
if (eObject instanceof ArchimateDiagramModel) {
ArchimateDiagramModel diagramModel = (ArchimateDiagramModel) eObject;
if (diagramModel.getViewpoint() == IViewpoint.LAYERED_VIEWPOINT) {
return diagramModel;
}
}
}
return null;
}
public static ArchimateDiagramModel getViewByName(IArchimateModel model, String viewName) {
for (EObject eObject : model.getFolder(FolderType.DIAGRAMS).getElements()) {
if (eObject instanceof ArchimateDiagramModel) {
ArchimateDiagramModel diagramModel = (ArchimateDiagramModel) eObject;
if (diagramModel.getName().equals(viewName)) {
return diagramModel;
}
}
}
return null;
}
public static File getDefaultLayoutFile(File file) {
return new File(file.getAbsolutePath() + ".layout.csv");
}
private static void exportChildrenLayout(EList<IDiagramModelObject> children, HashMap<String, String> iriNameMap, int x, int y,
ArrayList<String> export, String iriPrefix) {
for (IDiagramModelObject diagramModelObject : children) {
int coordX = x + diagramModelObject.getBounds().getX();
int coordY = y + diagramModelObject.getBounds().getY();
if (diagramModelObject instanceof DiagramModelGroup) {
exportChildrenLayout(((DiagramModelGroup) diagramModelObject).getChildren(), iriNameMap, coordX, coordY, export, iriPrefix);
} else {
String elementName = diagramModelObject.getId();
if (diagramModelObject instanceof DiagramModelArchimateObject) {
elementName = getOWLIRIFragment(((DiagramModelArchimateObject) diagramModelObject).getArchimateElement());
}
StringBuilder sb = new StringBuilder(iriPrefix).append("#").append(elementName).append("\t").append(coordX).append("\t")
.append(coordY);
if (diagramModelObject instanceof DiagramModelArchimateObject
&& ((DiagramModelArchimateObject) diagramModelObject).getChildren() != null
&& ((DiagramModelArchimateObject) diagramModelObject).getChildren().size() > 0) {
sb.append("\t").append(diagramModelObject.getBounds().getWidth()).append("\t")
.append(diagramModelObject.getBounds().getHeight());
exportChildrenLayout(((DiagramModelArchimateObject) diagramModelObject).getChildren(), iriNameMap, coordX, coordY,
export, iriPrefix);
}
export.add(sb.toString());
iriNameMap.put(sb.toString(), diagramModelObject.getName());
}
}
}
public static String formatString(String s) {
return s.replace(" ", "_").replace("(", "-").replace(")", "-").replace("/", "_");
}
}