1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package com.ontotext.wsmo4j.parser.owl;
20
21 import java.io.IOException;
22 import java.io.Reader;
23 import java.lang.reflect.UndeclaredThrowableException;
24 import java.util.*;
25
26 import org.deri.wsmo4j.io.serializer.wsml.VisitorSerializeWSMLTerms;
27 import org.omwg.ontology.*;
28 import org.openrdf.model.*;
29 import org.openrdf.model.Value;
30 import org.openrdf.sesame.Sesame;
31 import org.openrdf.sesame.admin.StdOutAdminListener;
32 import org.openrdf.sesame.config.AccessDeniedException;
33 import org.openrdf.sesame.config.ConfigurationException;
34 import org.openrdf.sesame.constants.QueryLanguage;
35 import org.openrdf.sesame.constants.RDFFormat;
36 import org.openrdf.sesame.query.QueryResultsTable;
37 import org.openrdf.sesame.repository.local.LocalRepository;
38 import org.openrdf.sesame.sail.*;
39 import org.wsmo.common.*;
40 import org.wsmo.common.Namespace;
41 import org.wsmo.common.exception.InvalidModelException;
42 import org.wsmo.common.exception.SynchronisationException;
43 import org.wsmo.factory.*;
44 import org.wsmo.wsml.ParserException;
45
46
47
48
49
50
51
52
53
54
55 public class WSMLFromOWL {
56
57 LocalRepository _repository;
58 WsmoFactory _factory;
59 LogicalExpressionFactory _leFactory;
60 DataFactory _dataFactory;
61
62 String allOntologiesQuery = "select O from {O} rdf:type {<"+OWLConstants.OWL_Ontology+">}";
63
64 String importedOntologyQuery =
65 "select Y from {O} rdf:type {<" + OWLConstants.OWL_Ontology + ">} "+
66 ",{O} <" + OWLConstants.OWL_imports + "> {Y}";
67
68 String classesQuery = "select X from {X} rdf:type {rdfs:Class}";
69
70 String mainOntology =
71 "select O from {O} rdf:type {<"+OWLConstants.OWL_Ontology+">} "+
72 " ,[ {} P {O} ] where P = null and O != <http://www.w3.org/2002/07/owl>";
73
74 String annotationsQuery = "select X from {X} rdf:type {<"+OWLConstants.OWL_AnnotationProperty+">}";
75
76 String annotationsOntoPropsQuery = "select X from {X} rdf:type {<"+OWLConstants.OWL_OntologyProperty+">}";
77
78 String restrictionsQuery = "select X from {X} rdf:type {<"+OWLConstants.OWL_Restriction+">}";
79
80 String SEQHeadsQuery = "select X from "+
81 "[{} <"+OWLConstants.OWL_distinctMembers+"> {X}], "+
82 "[{} <"+OWLConstants.OWL_intersectionOf+"> {X}], "+
83 "[{} <"+OWLConstants.OWL_unionOf+"> {X}], "+
84 "[{} <"+OWLConstants.OWL_complementOf+"> {X}], "+
85 "[{} <"+OWLConstants.OWL_oneOf+"> {X}] ";
86
87 String propertiesQuery = "select X from {X} rdf:type {rdf:Property}";
88
89 IRI dcSameAs = null;
90 public WSMLFromOWL(WsmoFactory _factory, LogicalExpressionFactory _leFactory, DataFactory _dataFactory) {
91 if (_factory == null)
92 _factory = Factory.createWsmoFactory(null);
93 this._factory = _factory;
94
95 if (_leFactory == null)
96 _leFactory = Factory.createLogicalExpressionFactory(null);
97 this._leFactory = _leFactory;
98
99 if (_dataFactory == null)
100 _dataFactory = Factory.createDataFactory(null);
101 this._dataFactory = _dataFactory;
102
103 try {
104 _repository = Sesame.getService().createRepository("owl_helper", true);
105 RdfSchemaRepository _src =(RdfSchemaRepository)_repository.getSail();
106 ValueFactory fact =_src.getValueFactory();
107 URI owlCls = fact.createURI(OWLConstants.OWL_Class);
108 URI rdfsCls = fact.createURI(OWLConstants.RDFS_Class);
109 URI rdfsSubCls = fact.createURI(OWLConstants.RDFS_subClassOf);
110 URI owlDataTypeProp = fact.createURI(OWLConstants.OWL_DatatypeProperty);
111 URI owlObjectProp = fact.createURI(OWLConstants.OWL_ObjectProperty);
112 URI rdfProp = fact.createURI(OWLConstants.RDF_Property);
113 _src.startTransaction();
114 _src.addStatement(owlCls, rdfsSubCls, rdfsCls);
115 _src.addStatement(owlObjectProp, rdfsSubCls, rdfProp);
116 _src.addStatement(owlDataTypeProp, rdfsSubCls, rdfProp);
117 _src.commitTransaction();
118
119 } catch (SailUpdateException sue) {
120 throw new RuntimeException("bad configuration", sue);
121 } catch (ConfigurationException e) {
122
123 throw new RuntimeException("bad configuration", e);
124 }
125 }
126
127 public void addData(Reader content, String baseURL) {
128 assert baseURL != null;
129 StdOutAdminListener listener = new StdOutAdminListener();
130 try {
131 _repository.addData(content, baseURL, RDFFormat.RDFXML, false, listener);
132 } catch (IOException e1) {
133 e1.printStackTrace();
134 } catch (AccessDeniedException e2) {
135 e2.printStackTrace();
136 }
137 }
138
139 void collectNodesInSEQ(Resource v, Collection here){
140 try {
141 Resource next = null;
142 do {
143 if (next != null)
144 v = next;
145 next = null;
146 StatementIterator iter = v.getSubjectStatements();
147 while (iter.hasNext()) {
148 Statement st = iter.next();
149 if (0==st.getPredicate().getURI().compareTo(Constants.RDF_first)) {
150 Value val = st.getObject();
151 here.add(val);
152 }
153 else if (0==st.getPredicate().getURI().compareTo(Constants.RDF_rest))
154 next = (Resource)st.getObject();
155 }
156 iter.close();
157 } while(next != null);
158 } catch (Exception e) {
159 e.printStackTrace();
160 }
161 }
162
163
164
165 void initial_collect() {
166
167 ArrayList theCollection = new ArrayList();
168 try {
169 QueryResultsTable result = _repository.performTableQuery(QueryLanguage.SERQL, SEQHeadsQuery);
170 for (int i = 0; i < result.getRowCount(); i++) {
171 theCollection.add(result.getValue(i, 0));
172
173 ArrayList here = new ArrayList();
174 collectNodesInSEQ((Resource)result.getValue(i, 0), here);
175
176 }
177 } catch (Exception e) {
178 e.printStackTrace();
179 }
180 }
181
182 String xForm(String val){
183 int pos = val.indexOf('#');
184 if (pos < 0 || pos == val.length())
185 return VisitorSerializeWSMLTerms.escapeNonSQNameSymbols(val);
186
187 Iterator iter = theOntology.listNamespaces().iterator();
188 while (iter.hasNext()) {
189 Namespace ns = (Namespace)iter.next();
190 if(ns.getIRI().toString().startsWith( val.substring(0,pos))) {
191 return VisitorSerializeWSMLTerms.escapeNonSQNameSymbols(
192 ns.getPrefix()+val.substring(pos));
193 }
194 }
195 Namespace ns = theOntology.getDefaultNamespace();
196 if(ns.getIRI().toString().startsWith( val.substring(0,pos))) {
197 return VisitorSerializeWSMLTerms.escapeNonSQNameSymbols(
198 val.substring(pos+1));
199 }
200 return "_\""+val+"\"";
201 }
202
203 DataValue createDataValueFromLiteral(Literal literal) {
204 WsmlDataType type = null;
205 URI data = literal.getDatatype();
206 if (data != null) {
207 try {
208 type = _dataFactory.createWsmlDataType(data.toString());
209 } catch (IllegalArgumentException iae) {
210 return _dataFactory.createWsmlString(literal.getLabel());
211 }
212 try {
213 return _dataFactory.createDataValueFromJavaObject(type, literal.getLabel());
214 } catch (IllegalArgumentException iae) {
215 String lit = literal.getLabel();
216 try {
217 return _dataFactory.createWsmlInteger(lit);
218 } catch (NumberFormatException nfe) {
219 try {
220 return _dataFactory.createWsmlDecimal(lit);
221 } catch (NumberFormatException nfe2) {
222 return _dataFactory.createWsmlString(lit);
223 }
224 }
225 }
226 } else {
227 String lit = literal.getLabel();
228 try {
229 return _dataFactory.createWsmlInteger(lit);
230 } catch (NumberFormatException nfe) {
231 try {
232 return _dataFactory.createWsmlDecimal(lit);
233 } catch (NumberFormatException nfe2) {
234 return _dataFactory.createWsmlString(lit);
235 }
236 }
237 }
238
239
240
241
242
243 }
244
245 int carinalities = 1;
246
247 void WSMLminCardinalityExpr(StringBuffer result, String prop, int card){
248 result.append("?x memberOf |class| implies exists ");
249 ArrayList distinctVars = new ArrayList();
250 if (card > 1)
251 result.append('{');
252 for (int i = 0; i < card; i++) {
253 String var = "?y"+(i+1);
254 distinctVars.add(var);
255 if (i > 0)
256 result.append(", ");
257 result.append(var);
258 }
259 if (card > 1)
260 result.append('}');
261 result.append("( ?x[");
262
263
264 for (int i = 0; i < card; i++) {
265 if (i > 0)
266 result.append(", ");
267 result.append(prop + " hasValue "+distinctVars.get(i));
268 }
269 result.append("]");
270
271 if (card > 1) {
272 for (int i = 0; i < distinctVars.size()-1; i++) {
273 for (int j = i+1; j < distinctVars.size(); j++) {
274 result.append(" and "+distinctVars.get(i)+" != "+distinctVars.get(j));
275 }
276 }
277 }
278 result.append(").\n");
279
280 }
281
282 void WSMLmaxCardinalityExpr(StringBuffer result, String prop, int card){
283 result.append("?x memberOf |class| implies exists ");
284
285 ArrayList distinctVars = new ArrayList();
286 if (card > 0)
287 result.append('{');
288
289 for (int i = 0; i <= card; i++) {
290 String var = "?y"+(i+1);
291 distinctVars.add(var);
292 if (i > 0)
293 result.append(", ");
294 result.append(var);
295 }
296 if (card > 0)
297 result.append('}');
298 result.append("( ?x[");
299
300 for (int i = 0; i <= card; i++) {
301 if (i > 0)
302 result.append(", ");
303 result.append(prop + " hasValue "+distinctVars.get(i));
304 }
305 result.append("] ");
306
307 boolean bComma= false;
308 if (card > 0) {
309 result.append("and (");
310 for (int i = 0; i < distinctVars.size()-1; i++) {
311 for (int j = i+1; j < distinctVars.size(); j++) {
312 if (bComma)
313 result.append(" or ");
314 bComma = true;
315 result.append(distinctVars.get(i)+" = "+distinctVars.get(j));
316 }
317 }
318 result.append(")");
319 }
320 result.append(" ).\n");
321 }
322
323 void helperXXXValuesFromBody(StringBuffer result, Value argument) {
324 StatementIterator iter2 = null;
325 try {
326 iter2 = ((Resource)argument).getSubjectStatements();
327
328 boolean anRestrictionAsargument = false;
329 URI restrictionOnProperty = null;
330 URI restrictionKind = null;
331 Value restrictionKindValue = null;
332
333 while (iter2.hasNext()) {
334 Statement st = iter2.next();
335 String pred = st.getPredicate().getURI();
336 if (0==pred.compareTo(OWLConstants.OWL_intersectionOf)) {
337
338 handleSetClass((Resource)argument);
339 ArrayList list = new ArrayList();
340 collectNodesInSEQ((Resource)st.getObject(), list);
341 boolean bFirst = true;
342 for (Iterator iter = list.iterator(); iter.hasNext();) {
343 Resource r = (Resource)iter.next();
344
345 if (r instanceof URI) {
346 if (bFirst == false) {
347 result.append(" and ");
348 }
349 result.append("?y1 memberOf "+xForm(((URI)r).getURI()));
350 } else {
351 throw new RuntimeException("Nested " + OWLConstants.OWL_intersectionOf + " Not supported");
352 }
353 bFirst = false;
354 }
355 break;
356 } else if (0==pred.compareTo(OWLConstants.OWL_unionOf)) {
357
358 handleSetClass((Resource)argument);
359 ArrayList list = new ArrayList();
360 collectNodesInSEQ((Resource)st.getObject(), list);
361 boolean bFirst = true;
362 for (Iterator iter = list.iterator(); iter.hasNext();) {
363 Resource r = (Resource)iter.next();
364
365 if (r instanceof URI) {
366 if (bFirst == false)
367 result.append(" or ");
368 result.append("?y1 memberOf "+xForm(((URI)r).getURI()));
369 } else {
370 throw new RuntimeException("Nested " + OWLConstants.OWL_unionOf + " Not supported");
371 }
372 bFirst = false;
373 }
374 break;
375 } else if (0==pred.compareTo(OWLConstants.OWL_oneOf)) {
376
377 handleSetClass((Resource)argument);
378 ArrayList list = new ArrayList();
379 collectNodesInSEQ((Resource)st.getObject(), list);
380 boolean bFirst = true;
381 for (Iterator iter = list.iterator(); iter.hasNext();) {
382 Resource r = (Resource)iter.next();
383
384 if (r instanceof URI) {
385 if (bFirst == false)
386 result.append(" or ");
387 result.append("?y1 = "+xForm(((URI)r).getURI()));
388 } else {
389 throw new RuntimeException("Nested " + OWLConstants.OWL_oneOf + " Not supported");
390 }
391 bFirst = false;
392 }
393 break;
394 } if (0==pred.compareTo(OWLConstants.OWL_complementOf)) {
395
396 handleSetClass((Resource)argument);
397 result.append("not ?y1 memberOf "+xForm(((URI)st.getObject()).getURI()));
398 break;
399 } if (0==pred.compareTo(OWLConstants.OWL_onProperty)) {
400 restrictionOnProperty = (URI)st.getObject();
401 } if (0==pred.compareTo(OWLConstants.OWL_hasValue)) {
402 restrictionKind = (URI)st.getPredicate();
403 restrictionKindValue = (URI)st.getObject();
404 } if (0==pred.compareTo(OWLConstants.OWL_allValuesFrom)) {
405 restrictionKind = (URI)st.getPredicate();
406 restrictionKindValue = st.getObject();
407 } else if (0==pred.compareTo(Constants.RDF_type) &&
408 0==OWLConstants.OWL_Restriction.compareTo(st.getObject().toString())) {
409 anRestrictionAsargument = true;
410 }
411 }
412 if (anRestrictionAsargument) {
413 if (0==restrictionKind.getLocalName().compareTo("hasValue")) {
414 String value = null;
415 if (restrictionKindValue instanceof URI) {
416 value = xForm(((URI)restrictionKindValue).getURI());
417 } else if (restrictionKindValue instanceof Literal) {
418 Literal literal = (Literal)restrictionKindValue;
419 value = createDataValueFromLiteral(literal).toString();
420 }
421 result.append("?y1["+xForm(restrictionOnProperty.getURI())+" hasValue "+value+"]");
422 } else if (0==restrictionKind.getLocalName().compareTo("allValuesFrom")) {
423 StatementIterator collFind = null;
424 ArrayList enumeratedClass = new ArrayList();
425 try {
426 collFind = ((Resource)restrictionKindValue).getSubjectStatements();
427 while (collFind.hasNext()) {
428 Statement st = collFind.next();
429 if (0==st.getPredicate().getLocalName().compareTo("oneOf")) {
430 collectNodesInSEQ((Resource)st.getObject(), enumeratedClass);
431 break;
432 }
433 }
434 } catch (Exception e) {
435 e.printStackTrace();
436 } finally {
437 collFind.close();
438 }
439 boolean bcomma = false;
440 for (Iterator iterEnum = enumeratedClass.iterator(); iterEnum.hasNext();){
441 if (bcomma)
442 result.append(" or ");
443 Value inst = (Value)iterEnum.next();
444 String value = null;
445 if (inst instanceof URI) {
446 value = xForm(((URI)inst).getURI());
447 } else if (inst instanceof Literal) {
448 Literal literal = (Literal)inst;
449 value = createDataValueFromLiteral(literal).toString();
450 }
451
452 result.append ("?y1["+xForm(restrictionOnProperty.getURI())+ " hasValue "+value+"]");
453 bcomma = true;
454 }
455
456 } else {
457 throw new RuntimeException("restrictionKind "+restrictionKind.getURI()+"not supported!");
458 }
459 }
460 } catch (RuntimeException e) {
461 throw e;
462 } catch (Exception e) {
463 e.printStackTrace();
464 } finally {
465 iter2.close();
466 }
467 }
468 void WSMLRestrictionBuilder(StringBuffer result, Resource restriction, URI onProperty, String kind, Value argument) {
469 if (0 == kind.compareTo("cardinality")) {
470 if (!(argument instanceof Literal))
471 return ;
472 Literal arg = (Literal)argument;
473 String value = arg.getLabel();
474 int card = 0;
475 try {
476 card = Integer.parseInt(value);
477 } catch (NumberFormatException e) {
478
479 return ;
480 }
481 if (card <= 0) {
482
483 return;
484 }
485 String prop = xForm(onProperty.getURI());
486 WSMLminCardinalityExpr(result, prop, card);
487 WSMLmaxCardinalityExpr(result, prop, card);
488 } else if (0 == kind.compareTo("minCardinality")) {
489 if (!(argument instanceof Literal))
490 return ;
491 Literal arg = (Literal)argument;
492 String value = arg.getLabel();
493 int card = 0;
494 try {
495 card = Integer.parseInt(value);
496 } catch (NumberFormatException e) {
497
498 return ;
499 }
500 String prop = xForm(onProperty.getURI());
501 WSMLminCardinalityExpr(result, prop, card);
502 } else if (0 == kind.compareTo("maxCardinality")) {
503 if (!(argument instanceof Literal))
504 return ;
505 Literal arg = (Literal)argument;
506 String value = arg.getLabel();
507 int card = 0;
508 try {
509 card = Integer.parseInt(value);
510 } catch (NumberFormatException e) {
511
512 return ;
513 }
514 String prop = xForm(onProperty.getURI());
515 WSMLmaxCardinalityExpr(result, prop, card);
516 } else if (0 == kind.compareTo("hasValue")) {
517 String value = null;
518 if (argument instanceof URI) {
519 value = xForm(((URI)argument).getURI());
520 } else if (argument instanceof Literal) {
521 Literal literal = (Literal)argument;
522 value = createDataValueFromLiteral(literal).toString();
523 }
524 result.append("?x memberOf |class| implies ?x["+xForm(onProperty.getURI())+" hasValue "+value+"].\n");
525 } else if(0 == kind.compareTo("someValuesFrom")) {
526 result.append("?x memberOf |class| implies exists ?y1 (?x["+xForm(onProperty.getURI())+" hasValue ?y1] and (");
527 if (argument instanceof URI)
528 result.append("?y1 memberOf "+xForm(((URI)argument).getURI()));
529 else {
530 helperXXXValuesFromBody(result, argument);
531 }
532 result.append(") ).\n");
533 } else if (0 == kind.compareTo("allValuesFrom")) {
534
535 result.append("?x memberOf |class| and ?x["+xForm(onProperty.getURI())+" hasValue ?y1] implies (");
536
537 if (argument instanceof URI)
538 result.append("?y1 memberOf "+xForm(((URI)argument).getURI())+").\n");
539 else {
540 helperXXXValuesFromBody(result, argument);
541 result.append(" ).\n");
542
543 }
544
545 }
546 }
547
548 HashMap allRestrictions;
549
550 void handleRestrictionOnProperty() {
551 allRestrictions = new HashMap();
552 String query = "select R, P, card, minc, maxc, hasv, some, allv from "+
553 "{R} rdf:type {<"+OWLConstants.OWL_Restriction+">} "+
554 ", {R} <"+OWLConstants.OWL_onProperty+"> {P} "+
555 ",[ {R} <"+OWLConstants.OWL_cardinality+"> {card} ] "+
556 ",[ {R} <"+OWLConstants.OWL_minCardinality+"> {minc} ] "+
557 ",[ {R} <"+OWLConstants.OWL_maxCardinality+"> {maxc} ] "+
558 ",[ {R} <"+OWLConstants.OWL_hasValue+"> {hasv} ] "+
559 ",[ {R} <"+OWLConstants.OWL_someValuesFrom+"> {some} ]"+
560 ",[ {R} <"+OWLConstants.OWL_allValuesFrom+"> {allv} ] "
561 ;
562 try {
563 QueryResultsTable result = _repository.performTableQuery(QueryLanguage.SERQL, query);
564 for (int i = 0; i < result.getRowCount(); i++) {
565 Resource restr = (Resource)result.getValue(i, 0);
566 StringBuffer out = new StringBuffer();
567
568 if (null != result.getValue(i, 2)) {
569 WSMLRestrictionBuilder(out, restr, (URI)result.getValue(i, 1), "cardinality", result.getValue(i, 2));
570 }
571
572 if (null != result.getValue(i, 3)) {
573 WSMLRestrictionBuilder(out, restr, (URI)result.getValue(i, 1), "minCardinality", result.getValue(i, 3));
574 }
575
576 if (null != result.getValue(i, 4)) {
577 WSMLRestrictionBuilder(out, restr, (URI)result.getValue(i, 1), "maxCardinality", result.getValue(i, 4));
578 }
579
580 if (null != result.getValue(i, 5)){
581 WSMLRestrictionBuilder(out, restr, (URI)result.getValue(i, 1), "hasValue", result.getValue(i, 5));
582 }
583
584 if (null != result.getValue(i, 6)) {
585 WSMLRestrictionBuilder(out, restr, (URI)result.getValue(i, 1), "someValuesFrom", (Resource)result.getValue(i, 6));
586 }
587
588 if (null != result.getValue(i, 7)) {
589 WSMLRestrictionBuilder(out, restr, (URI)result.getValue(i, 1), "allValuesFrom", (Resource)result.getValue(i, 7));
590
591 }
592
593 if (out.length() == 0) {
594 continue;
595 }
596
597 allClasses.remove(restr);
598 allRestrictions.put(restr, out.toString());
599 }
600 result = null;
601 } catch (RuntimeException e) {
602 throw e;
603 } catch (Exception e) {
604 e.printStackTrace();
605 }
606 }
607
608 HashMap defaultClasses = new HashMap();
609 HashMap defaultProperties = new HashMap();
610
611 void collectDefaultClasses() {
612 defaultClasses.clear();
613 try {
614 QueryResultsTable result = _repository.performTableQuery(QueryLanguage.SERQL, classesQuery);
615 for (int i = 0; i < result.getRowCount(); i++) {
616 defaultClasses.put(result.getValue(i, 0), result.getValue(i, 0));
617 }
618 result = null;
619 } catch (Exception e) {
620 e.printStackTrace();
621 }
622 }
623
624 void collectDefaultProperties() {
625 defaultProperties.clear();
626 try {
627 QueryResultsTable result = _repository.performTableQuery(QueryLanguage.SERQL, propertiesQuery);
628 for (int i = 0; i < result.getRowCount(); i++) {
629 defaultProperties.put(result.getValue(i, 0), result.getValue(i, 0));
630 }
631 result = null;
632 } catch (Exception e) {
633 e.printStackTrace();
634 }
635 }
636
637 HashMap setClasses = new HashMap();
638 void handleSetClass(Resource node) {
639 setClasses.put(node, node);
640 allClasses.remove(node);
641 }
642
643 HashMap allClasses;
644
645 void handleClasses(){
646 allClasses = new HashMap();
647 try {
648 QueryResultsTable result = _repository.performTableQuery(QueryLanguage.SERQL, classesQuery);
649 for (int i = 0; i < result.getRowCount(); i++) {
650 Value v = result.getValue(i, 0);
651 if (null == defaultClasses.get(v))
652 allClasses.put(v,v);
653 }
654 result = null;
655 } catch (Exception e) {
656 e.printStackTrace();
657 }
658 }
659
660 HashMap allProperties;
661
662 void handleProperties(){
663 allProperties = new HashMap();
664 try {
665 QueryResultsTable result = _repository.performTableQuery(QueryLanguage.SERQL, propertiesQuery);
666 for (int i = 0; i < result.getRowCount(); i++) {
667 Value v = result.getValue(i, 0);
668 if (null == defaultProperties.get(v))
669 allProperties.put(v,v);
670 }
671 result = null;
672 } catch (Exception e) {
673 e.printStackTrace();
674 }
675 }
676
677 HashMap allInstances;
678
679 void handleInstances() {
680 allInstances = new HashMap();
681
682 String query = "select distinct I from {I} rdf:type {C} "+
683 " , [{I} rdfs:subClassOf {Q} ] "+
684 " , [{I} rdfs:subPropertyOf {P}] "+
685 " , [{I} L {rdf:List} ]"+
686 " , [{I} R {<"+OWLConstants.OWL_Restriction+">} ]"+
687 " , [{I} <"+OWLConstants.OWL_distinctMembers+"> {F} ]"+
688 " , [{I} O {<"+OWLConstants.OWL_Ontology+">} ]"+
689 " , [{DEF} rdfs:isDefinedBy {I} ]"+
690 " where Q = NULL AND P = NULL and L = NULL and R = NULL and F = NULL and O = NULL and DEF = NULL"
691 ;
692
693 try {
694 QueryResultsTable result = _repository.performTableQuery(QueryLanguage.SERQL, query);
695 for (int i = 0; i < result.getRowCount(); i++) {
696 Value v = result.getValue(i, 0);
697 allInstances.put(v,v);
698 }
699 } catch (Exception e) {
700 e.printStackTrace();
701 }
702 }
703
704 boolean isExternalClass(Resource cls) {
705 RdfSchemaSource _src =(RdfSchemaSource)_repository.getSail();
706 ValueFactory fact =_src.getValueFactory();
707 URI typeP = fact.createURI(OWLConstants.RDF_type);
708 URI owlCls = fact.createURI(OWLConstants.OWL_Class.toString());
709 return !_src.hasExplicitStatement(cls, typeP, owlCls);
710 }
711
712 boolean isExternalIndividual(Resource cls) {
713 RdfSchemaSource _src =(RdfSchemaSource)_repository.getSail();
714 ValueFactory fact =_src.getValueFactory();
715 URI typeP = fact.createURI(OWLConstants.RDF_type);
716
717 return !_src.hasExplicitStatement(cls, typeP, null);
718 }
719
720 boolean isInferred(Resource s, URI pred, Value v) {
721 RdfSchemaSource _src =(RdfSchemaSource)_repository.getSail();
722 return !_src.hasExplicitStatement(s, pred, v);
723 }
724
725 boolean isExternalProperty(Resource cls) {
726 RdfSchemaSource _src =(RdfSchemaSource)_repository.getSail();
727 ValueFactory fact =_src.getValueFactory();
728 URI typeP = fact.createURI(OWLConstants.RDF_type);
729 URI owlObjectProp = fact.createURI(OWLConstants.OWL_ObjectProperty);
730 URI owlDataProp = fact.createURI(OWLConstants.OWL_DatatypeProperty);
731 URI rdfProperty = fact.createURI(OWLConstants.RDF_Property);
732 if (_src.hasExplicitStatement(cls, typeP, owlObjectProp))
733 return false;
734 if (_src.hasExplicitStatement(cls, typeP, owlDataProp))
735 return false;
736 if (_src.hasExplicitStatement(cls, typeP, rdfProperty))
737 return false;
738 return true;
739 }
740
741 ArrayList getSameAs(Resource res) {
742 ArrayList result = new ArrayList();
743 RdfSchemaSource _src =(RdfSchemaSource)_repository.getSail();
744 ValueFactory fact =_src.getValueFactory();
745 URI sameAsP = fact.createURI(OWLConstants.OWL_sameAs);
746 StatementIterator iter = null;
747 try {
748 iter = _src.getStatements(res, sameAsP, null);
749 while (iter.hasNext()) {
750 result.add(iter.next().getObject());
751 }
752 } catch (Exception e) {
753 e.printStackTrace();
754 } finally {
755 iter.close();
756 }
757 return result;
758 }
759
760 void handleRestrictionSet() {
761 String query = "select R from"+
762 "{R} rdf:type {<"+OWLConstants.OWL_Restriction+">} "+
763 ", [{R} <"+OWLConstants.OWL_onProperty+"> {P} ] "+
764 "where P = NULL";
765 try {
766 QueryResultsTable result = _repository.performTableQuery(QueryLanguage.SERQL, query);
767 for (int i = 0; i < result.getRowCount(); i++) {
768 Value v = result.getValue(i, 0);
769 }
770 } catch (Exception e) {
771 e.printStackTrace();
772 }
773 }
774
775 HashMap allIntersections;
776 HashMap allUnions;
777 void handleClassPartial() {
778 allIntersections = new HashMap();
779 allUnions = new HashMap();
780 String query = "select C, inter, eq, uni, comp from"+
781 "{C} rdf:type {<"+OWLConstants.OWL_Class+">} "+
782 ",[ {C} <"+OWLConstants.OWL_intersectionOf+"> {inter}] "+
783 ",[ {C} <"+OWLConstants.OWL_equivalentClass+"> {eq}] "+
784 ",[ {C} <"+OWLConstants.OWL_unionOf+"> {uni}] "+
785 ",[ {C} <"+OWLConstants.OWL_complementOf+"> {comp}] ";
786 try {
787 QueryResultsTable result = _repository.performTableQuery(QueryLanguage.SERQL, query);
788 for (int i = 0; i < result.getRowCount(); i++) {
789 Value v = result.getValue(i, 0);
790 if (null != result.getValue(i, 1)) {
791 allIntersections.put(v, result.getValue(i, 1));
792 } else if (null != result.getValue(i, 3)) {
793 allUnions.put(v, result.getValue(i, 3));
794 } else if (null != result.getValue(i, 2) ||
795 null != result.getValue(i, 4)) {
796 }
797 }
798 } catch (Exception e) {
799 e.printStackTrace();
800 }
801 }
802
803 HashMap allAttributes;
804 void handlePossibleAttributes() {
805 allAttributes = new HashMap();
806 for (Iterator iter = allProperties.keySet().iterator(); iter.hasNext();) {
807 Resource res = (Resource)iter.next();
808 if (isExternalProperty(res))
809 continue;
810 String query = "select C from {<"+res+">} rdfs:domain {C}";
811 try {
812 QueryResultsTable result = _repository.performTableQuery(QueryLanguage.SERQL, query);
813 for (int i = 0; i < result.getRowCount(); i++) {
814 Value v = result.getValue(i, 0);
815 if (allClasses.containsKey(v))
816 allAttributes.put(res, v);
817 }
818 } catch (Exception e) {
819 e.printStackTrace();
820 }
821 }
822 for (Iterator iter = allAttributes.keySet().iterator(); iter.hasNext();) {
823 allProperties.remove(iter.next());
824 }
825 }
826
827
828
829
830
831
832
833 public Ontology process(Reader content, String defaultNs) throws Exception {
834
835
836 try {
837 dcSameAs = _factory.createIRI(Constants.DC_NS+"sameAs");
838
839
840
841
842
843
844 collectDefaultClasses();
845 collectDefaultProperties();
846 if (defaultNs == null)
847 addData(content, "");
848 else
849 addData(content, defaultNs);
850
851 processOntologies();
852 assert theOntology != null;
853 if (defaultNs == null) {
854 defaultNs = theOntology.getIdentifier().toString();
855 if (defaultNs.endsWith("#") == false)
856 defaultNs+='#';
857 }
858 theOntology.setDefaultNamespace(_factory.createIRI(defaultNs));
859
860 theOntology.addNamespace(_factory.createNamespace("dc", _factory.createIRI(Constants.DC_NS)));
861 theOntology.addNamespace(_factory.createNamespace("wsml", _factory.createIRI(WSML.WSML_NAMESPACE)));
862 theOntology.addNamespace(_factory.createNamespace("xsd", _factory.createIRI(Constants.XSD_NS)));
863 handleClasses();
864 handleRestrictionOnProperty();
865 handleProperties();
866 handleInstances();
867 handleClassPartial();
868
869
870 processClassDefinitions();
871 processRelationDefinitions();
872 processIndividuals();
873
874 } catch (Exception ex) {
875
876 ex.printStackTrace();
877 throw ex;
878 }
879 return theOntology;
880 }
881
882 int axiom_counter = 0;
883
884 void processAsUnionClass(Resource res) throws InvalidModelException {
885 String uriStr = getGenerateID(res, "Concept");
886 IRI id = _factory.createIRI(uriStr);
887 String logExpr = "?x memberOf "+xForm(uriStr)+"\n"+
888 "impliedBy ";
889 Concept concept = _factory.getConcept(id);
890
891
892 ArrayList list = new ArrayList();
893 collectNodesInSEQ((Resource)allUnions.get(res), list);
894 boolean bHasOne = false;
895 for (Iterator sc = list.iterator(); sc.hasNext();) {
896 Resource element = (Resource) sc.next();
897 if (allClasses.containsKey(element)) {
898
899 IRI ref = _factory.createIRI(getGenerateID(element, "Concept"));
900
901 if (bHasOne)
902 logExpr +=" or ";
903 logExpr += "?x memberOf "+xForm(ref.toString());
904 bHasOne = true;
905 } else if (allRestrictions.containsKey(element)){
906 IRI asId = _factory.createIRI(uriStr + (++axiom_counter));
907 Axiom ax = _factory.createAxiom(asId);
908 theOntology.addAxiom(ax);
909
910 ax.addNFPValue(_factory.createIRI(Constants.DC_relation), id);
911 String foo = (String)allRestrictions.get(element);
912 do {
913 int pos = foo.indexOf("|class|");
914 if (pos < 0)
915 break;
916 foo = foo.substring(0, pos)+ xForm(uriStr)+foo.substring(pos + "|class|".length());
917 } while (true);
918 try {
919 ax.addDefinition(_leFactory.createLogicalExpression(foo, theOntology));
920 } catch (ParserException pe) {
921 throw new InvalidModelException(pe);
922 }
923 concept.addNFPValue(_factory.createIRI(Constants.DC_relation), asId);
924 }
925 }
926 try {
927 {
928 IRI asId = _factory.createIRI(uriStr + (++axiom_counter));
929 Axiom ax = _factory.createAxiom(asId);
930 theOntology.addAxiom(ax);
931 logExpr+= " .";
932 ax.addNFPValue(_factory.createIRI(Constants.DC_relation), id);
933 ax.addDefinition(_leFactory.createLogicalExpression(logExpr, theOntology));
934 concept.addNFPValue(_factory.createIRI(Constants.DC_relation), asId);
935 }
936
937 String query = "select R from "+
938 " {<"+uriStr+">} serql:directSubClassOf {R}, {R} rdf:type {<"+OWLConstants.OWL_Restriction+">}"
939 ;
940 QueryResultsTable result = _repository.performTableQuery(QueryLanguage.SERQL, query);
941 for (int i = 0; i < result.getRowCount(); i++) {
942 Resource element = (Resource)result.getValue(i, 0);
943 IRI asId = _factory.createIRI(uriStr + (++axiom_counter));
944 Axiom ax = _factory.createAxiom(asId);
945 theOntology.addAxiom(ax);
946
947 ax.addNFPValue(_factory.createIRI(Constants.DC_relation), id);
948 String foo = (String)allRestrictions.get(element);
949 do {
950 int pos = foo.indexOf("|class|");
951 if (pos < 0)
952 break;
953 foo = foo.substring(0, pos)+ xForm(uriStr)+foo.substring(pos + "|class|".length());
954 } while (true);
955 ax.addDefinition(_leFactory.createLogicalExpression(foo, theOntology));
956 concept.addNFPValue(_factory.createIRI(Constants.DC_relation), asId);
957
958 }
959 }catch (Exception e) {
960 e.printStackTrace();
961 }
962 }
963
964 void processAsIntersectionClass(Resource res) throws InvalidModelException {
965 String uriStr = getGenerateID(res, "Concept");
966 IRI id = _factory.createIRI(uriStr);
967 Concept concept = _factory.getConcept(id);
968
969 ArrayList list = new ArrayList();
970 collectNodesInSEQ((Resource)allIntersections.get(res), list);
971
972 for (Iterator sc = list.iterator(); sc.hasNext();) {
973 Resource element = (Resource) sc.next();
974 if (allClasses.containsKey(element)) {
975
976 IRI ref = _factory.createIRI(getGenerateID(element, "Concept"));
977 concept.addSuperConcept(_factory.getConcept(ref));
978
979 } else if (allRestrictions.containsKey(element)){
980 IRI asId = _factory.createIRI(uriStr + (++axiom_counter));
981 Axiom ax = _factory.createAxiom(asId);
982 theOntology.addAxiom(ax);
983
984 ax.addNFPValue(_factory.createIRI(Constants.DC_relation), id);
985 String foo = (String)allRestrictions.get(element);
986 do {
987 int pos = foo.indexOf("|class|");
988 if (pos < 0)
989 break;
990 foo = foo.substring(0, pos)+ xForm(uriStr)+foo.substring(pos + "|class|".length());
991 } while (true);
992 try {
993 ax.addDefinition(_leFactory.createLogicalExpression(foo, theOntology));
994 } catch (ParserException pe) {
995 throw new InvalidModelException(pe);
996 }
997 concept.addNFPValue(_factory.createIRI(Constants.DC_relation), asId);
998 }
999 }
1000 try {
1001 String query = "select R from "+
1002 " {<"+uriStr+">} serql:directSubClassOf {R}, {R} rdf:type {<"+OWLConstants.OWL_Restriction+">}"
1003 ;
1004 QueryResultsTable result = _repository.performTableQuery(QueryLanguage.SERQL, query);
1005 for (int i = 0; i < result.getRowCount(); i++) {
1006 Resource element = (Resource)result.getValue(i, 0);
1007 IRI asId = _factory.createIRI(uriStr + (++axiom_counter));
1008 Axiom ax = _factory.createAxiom(asId);
1009 theOntology.addAxiom(ax);
1010
1011 ax.addNFPValue(_factory.createIRI(Constants.DC_relation), id);
1012 String foo = (String)allRestrictions.get(element);
1013 do {
1014 int pos = foo.indexOf("|class|");
1015 if (pos < 0)
1016 break;
1017 foo = foo.substring(0, pos)+ xForm(uriStr)+foo.substring(pos + "|class|".length());
1018 } while (true);
1019 ax.addDefinition(_leFactory.createLogicalExpression(foo, theOntology));
1020 concept.addNFPValue(_factory.createIRI(Constants.DC_relation), asId);
1021
1022 }
1023 }catch (Exception e) {
1024 e.printStackTrace();
1025 }
1026 }
1027
1028 private String anonIDPrefix;
1029 String getGenerateID(Resource res, String type) {
1030 if (res instanceof URI) {
1031 return ((URI)res).getURI();
1032 }
1033 if (anonIDPrefix == null) {
1034 anonIDPrefix = (theOntology.getDefaultNamespace() == null) ?
1035 theOntology.getIdentifier().toString()
1036 : theOntology.getDefaultNamespace().getIRI().toString();
1037 anonIDPrefix += (anonIDPrefix.endsWith("#")) ? "anonymous" : "#anonymous";
1038 }
1039 return anonIDPrefix + type + '_' + ((BNode)res).getID();
1040 }
1041
1042 void processClassDefinitions() throws InvalidModelException {
1043
1044 for (Iterator iter = allClasses.keySet().iterator(); iter.hasNext();) {
1045 Resource res = (Resource)iter.next();
1046 if (isExternalClass(res))
1047 continue;
1048
1049 IRI id = _factory.createIRI(getGenerateID(res, "Concept"));
1050
1051 Concept concept = _factory.createConcept(id);
1052 ArrayList sameAs = getSameAs(res);
1053 for (Iterator i = sameAs.iterator(); i.hasNext();) {
1054 concept.addNFPValue(dcSameAs, _factory.createIRI( i.next().toString()));
1055 }
1056 theOntology.addConcept(concept);
1057 }
1058
1059 for (Iterator iter = allClasses.keySet().iterator(); iter.hasNext();) {
1060 Resource res = (Resource)iter.next();
1061 if (isExternalClass(res))
1062 continue;
1063 if (allIntersections.containsKey(res)) {
1064 processAsIntersectionClass(res);
1065 } if (allUnions.containsKey(res)) {
1066 processAsUnionClass(res);
1067 } else
1068 {
1069 IRI id = _factory.createIRI(getGenerateID(res, "Concept"));;
1070 Concept concept = _factory.getConcept(id);
1071 String query = "select SC from {<"+id.toString()+">} serql:directSubClassOf {SC} "
1072 ;
1073 try {
1074 QueryResultsTable result = _repository.performTableQuery(QueryLanguage.SERQL, query);
1075
1076 for (int i = 0; i < result.getRowCount(); i++) {
1077 Value v = result.getValue(i, 0);
1078 if (allClasses.containsKey(v)) {
1079 IRI ref = _factory.createIRI( getGenerateID((Resource)v, "Concept"));
1080 concept.addSuperConcept(_factory.getConcept(ref));
1081
1082 } else if (allRestrictions.containsKey(v)) {
1083 IRI asId = _factory.createIRI(id.toString() +(++axiom_counter));
1084 Axiom ax = _factory.createAxiom(asId);
1085 ax.addNFPValue(_factory.createIRI(Constants.DC_relation), id);
1086 theOntology.addAxiom(ax);
1087 String foo = (String)allRestrictions.get(v);
1088 do {
1089 int pos = foo.indexOf("|class|");
1090 if (pos < 0)
1091 break;
1092 foo = foo.substring(0, pos)+ xForm(id.toString())+foo.substring(pos + "|class|".length());
1093 } while (true);
1094 ax.addDefinition(_leFactory.createLogicalExpression(foo, theOntology));
1095 concept.addNFPValue(_factory.createIRI(Constants.DC_relation), asId);
1096 }
1097 }
1098 } catch (Exception e) {
1099
1100 e.printStackTrace();
1101 }
1102 }
1103
1104 }
1105 }
1106
1107 void processRelationDefinitions() throws InvalidModelException {
1108
1109 for (Iterator iter = allProperties.keySet().iterator(); iter.hasNext();) {
1110 Resource res = (Resource)iter.next();
1111 if (isExternalProperty(res))
1112 continue;
1113 IRI id = _factory.createIRI(getGenerateID(res, "Relation"));
1114 Relation relation = _factory.createRelation(id);
1115
1116 ArrayList sameAs = getSameAs(res);
1117 for (Iterator i = sameAs.iterator(); i.hasNext();) {
1118 relation.addNFPValue(dcSameAs, _factory.createIRI( i.next().toString()));
1119 }
1120 theOntology.addRelation(relation);
1121 relation.createParameter((byte)0);
1122 relation.createParameter((byte)1);
1123
1124 }
1125 for (Iterator iter = allProperties.keySet().iterator(); iter.hasNext();) {
1126 Resource res = (Resource)iter.next();
1127 if (isExternalProperty(res))
1128 continue;
1129 String query = "select SP from {<"+res+">} serql:directSubPropertyOf {SP} ";
1130 IRI id = _factory.createIRI(getGenerateID(res, "Relation"));
1131 Relation relation = _factory.getRelation(id);
1132 try {
1133 QueryResultsTable result = _repository.performTableQuery(QueryLanguage.SERQL, query);
1134
1135 for (int i = 0; i < result.getRowCount(); i++) {
1136 URI v = (URI)result.getValue(i, 0);
1137 IRI idSuper = _factory.createIRI(v.getURI());
1138 relation.addSuperRelation(_factory.getRelation(idSuper));
1139 }
1140 } catch (Exception e) {
1141 e.printStackTrace();
1142 }
1143
1144
1145 StatementIterator stIter = null;
1146 ArrayList axioms = new ArrayList();
1147 try {
1148 stIter = res.getSubjectStatements();
1149 boolean bDataTypeProp = false;
1150 boolean bObjectProp = false;
1151 boolean bHasRange = false;
1152 boolean bHasDomain = false;
1153 while (stIter.hasNext()) {
1154 Statement st = stIter.next();
1155 URI u = st.getPredicate();
1156 if (0==u.getURI().compareTo(Constants.RDFS_domain)) {
1157 String domainConcept = getGenerateID((Resource)st.getObject(), "Concept");
1158
1159 String concept = xForm(domainConcept);
1160 IRI domainIRI = _factory.createIRI(domainConcept);
1161 relation.getParameter((byte)0).addType(_factory.getConcept(domainIRI));
1162 String attr = xForm(res.toString());
1163 axioms.add("?x memberOf "+concept+" impliedBy "+attr+"(?x,?y).");
1164 bHasDomain = true;
1165 continue;
1166 }
1167 if (0==u.getURI().compareTo(Constants.RDFS_range)) {
1168 String rangeConceptID = getGenerateID((Resource)st.getObject(), "Concept");
1169 String concept = xForm(rangeConceptID);
1170 IRI rangeIRI = _factory.createIRI(rangeConceptID);
1171 relation.getParameter((byte)1).addType(_factory.getConcept(rangeIRI));
1172 String attr = xForm(res.toString());
1173 axioms.add("?y memberOf "+concept+" impliedBy "+attr+"(?x,?y).");
1174 bHasRange = true;
1175 continue;
1176 }
1177 if (0==u.getURI().compareTo(Constants.RDF_type)) {
1178 String value = st.getObject().toString();
1179 if (0 == value.compareTo(OWLConstants.OWL_TransitiveProperty)) {
1180 String attr = xForm(res.toString());
1181 axioms.add("?x["+attr+" hasValue ?z] impliedBy ?x["+attr+" hasValue ?y] and ?y["+attr+" hasValue ?z].");
1182 continue;
1183 }
1184 if (0 == value.compareTo(OWLConstants.OWL_SymmetricProperty)) {
1185 String attr = xForm(res.toString());
1186 axioms.add("?x["+attr+" hasValue ?y] impliedBy ?y["+attr+" hasValue ?x].");
1187 continue;
1188 }
1189 if (0 == value.compareTo(OWLConstants.OWL_DatatypeProperty)) {
1190 bDataTypeProp = true;
1191 }
1192 if (0 == value.compareTo(OWLConstants.OWL_ObjectProperty)) {
1193 bObjectProp = true;
1194 }
1195 }
1196 if (0==u.getURI().compareTo(OWLConstants.OWL_inverseOf)) {
1197 String value = xForm(st.getObject().toString());
1198 String attr = xForm(res.toString());
1199 axioms.add("?x["+attr+" hasValue ?y] impliedBy ?y["+value+" hasValue ?x].");
1200 if (0 != value.compareTo(attr))
1201 axioms.add("?x["+value+" hasValue ?y] impliedBy ?y["+attr+" hasValue ?x].");
1202 continue;
1203 }
1204
1205 }
1206 if (!bHasDomain && (bDataTypeProp || bObjectProp )) {
1207 IRI thingIRI = _factory.createIRI(OWLConstants.OWL_Thing);
1208 relation.getParameter((byte)0).addType(_factory.getConcept(thingIRI));
1209 }
1210 if (!bHasRange) {
1211 if (bDataTypeProp) {
1212 IRI stringIRI = _factory.createIRI(Constants.XSD_string);
1213 relation.getParameter((byte)1).addType(_factory.getConcept(stringIRI));
1214 } else if (bObjectProp) {
1215 IRI thingIRI = _factory.createIRI(OWLConstants.OWL_Thing);
1216 relation.getParameter((byte)1).addType(_factory.getConcept(thingIRI));
1217 }
1218 }
1219 } catch (Exception e) {
1220 e.printStackTrace();
1221 } finally {
1222 stIter.close();
1223 }
1224 for (Iterator axIter = axioms.iterator(); axIter.hasNext();) {
1225 IRI asId = _factory.createIRI(id.toString() + (++axiom_counter));
1226 Axiom ax = _factory.createAxiom(asId);
1227 theOntology.addAxiom(ax);
1228
1229 ax.addNFPValue(_factory.createIRI(Constants.DC_relation), id);
1230 String foo = (String)axIter.next();
1231 try {
1232 ax.addDefinition(_leFactory.createLogicalExpression(foo, theOntology));
1233 } catch (ParserException pe) {
1234 throw new InvalidModelException(pe);
1235 }
1236 relation.addNFPValue(_factory.createIRI(Constants.DC_relation), asId);
1237 }
1238 }
1239 }
1240
1241 void processIndividuals() throws InvalidModelException {
1242 for (Iterator iter = allInstances.keySet().iterator(); iter.hasNext();) {
1243 Resource res = (Resource)iter.next();
1244 if (isExternalIndividual(res)) {
1245 continue;
1246 }
1247 if (allClasses.containsKey(res)) {
1248 continue;
1249 }
1250 if (allProperties.containsKey(res)) {
1251 continue;
1252 }
1253 IRI id = _factory.createIRI(getGenerateID(res, "Instance"));
1254 Instance instance = _factory.createInstance(id);
1255 theOntology.addInstance(instance);
1256 ArrayList sameAs = getSameAs(res);
1257 for (Iterator i = sameAs.iterator(); i.hasNext();) {
1258 instance.addNFPValue(dcSameAs, _factory.createIRI( i.next().toString()));
1259 }
1260
1261 String query = "select C from {<" + id.toString() +">} serql:directType {C} "+
1262 " where C != <"+OWLConstants.OWL_Thing+">";
1263 try {
1264 QueryResultsTable result = _repository.performTableQuery(QueryLanguage.SERQL, query);
1265 for (int i = 0; i < result.getRowCount(); i++) {
1266 URI v = (URI)result.getValue(i, 0);
1267 IRI ref = _factory.createIRI(v.getURI());
1268 try {
1269 instance.addConcept(_factory.getConcept(ref));
1270 } catch (UndeclaredThrowableException se) {
1271 instance.addConcept(_factory.createConcept(ref));
1272 } catch (SynchronisationException se3) {
1273 instance.addConcept(_factory.createConcept(ref));
1274 }
1275 }
1276 } catch (Exception e) {
1277 e.printStackTrace();
1278 }
1279
1280
1281 query = "select P,V,SP from {<"+ id.toString() +">} P {V} "+
1282 " ,[{V} rdfs:subClassOf {Q}]"+
1283 " ,[{P} serql:directSubPropertyOf {SP}]"+
1284 " where Q = NULL";
1285 try {
1286 QueryResultsTable result = _repository.performTableQuery(QueryLanguage.SERQL, query);
1287 for (int i = 0; i < result.getRowCount(); i++) {
1288 URI v = (URI)result.getValue(i, 0);
1289 if (!allProperties.containsKey(v))
1290 continue;
1291 if (isInferred(res,v, result.getValue(i, 1)))
1292 continue;
1293
1294 IRI ref = _factory.createIRI(v.getURI());
1295 Relation parent = _factory.getRelation(ref);
1296
1297 Identifier anon = _factory.createAnonymousID();
1298 RelationInstance relInst = _factory.createRelationInstance(anon, parent);
1299 theOntology.addRelationInstance(relInst);
1300
1301 try {
1302 relInst.setRelation(parent);
1303 } catch (SynchronisationException se) {
1304 parent = _factory.createRelation(ref);
1305 parent.createParameter((byte)0);
1306 parent.createParameter((byte)1);
1307 relInst.setRelation(parent);
1308 }
1309 try {
1310 relInst.setParameterValue((byte)0, instance);
1311 } catch (IllegalArgumentException e) {
1312
1313 }
1314
1315 Value val = result.getValue(i, 1);
1316 if (val instanceof URI) {
1317 IRI refInst = _factory.createIRI(((URI)val).getURI());
1318 relInst.setParameterValue((byte)1, _factory.getInstance( refInst));
1319 } else if (val instanceof Literal) {
1320 DataValue dataValue = createDataValueFromLiteral((Literal)val);
1321 relInst.setParameterValue((byte)1, dataValue);
1322 }
1323 }
1324 } catch (Exception e) {
1325 e.printStackTrace();
1326 }
1327 }
1328 }
1329
1330 Ontology theOntology = null;
1331
1332 void processOntologies() throws Exception {
1333
1334 QueryResultsTable result = _repository.performTableQuery(QueryLanguage.SERQL, mainOntology);
1335 if (result.getRowCount() != 1) {
1336 throw new RuntimeException("the content should have a single OWL ontology! numOntologies="+result.getRowCount());
1337 }
1338 for (int i = 0; i < result.getRowCount(); i++) {
1339 URI asUri = (URI)result.getValue(i, 0);
1340 IRI id = _factory.createIRI(asUri.getURI());
1341 theOntology = _factory.createOntology(id);
1342 }
1343
1344
1345 result = _repository.performTableQuery(QueryLanguage.SERQL, importedOntologyQuery);
1346 for (int i = 0; i < result.getRowCount(); i++) {
1347 URI asUri = (URI)result.getValue(i, 0);
1348 IRI id = _factory.createIRI(asUri.getURI());
1349 theOntology.addOntology( _factory.getOntology(id));
1350 }
1351
1352
1353 String query = "select P, V from "+
1354 " {<"+theOntology.getIdentifier().toString()+">} P {V} "+
1355 " ,{P} rdf:type {<"+OWLConstants.OWL_AnnotationProperty+">} ";
1356 result = _repository.performTableQuery(QueryLanguage.SERQL, query);
1357 for (int i = 0; i < result.getRowCount(); i++) {
1358 Value val = result.getValue(i, 1);
1359 if (val instanceof URI)
1360 theOntology.addNFPValue(_factory.createIRI(Constants.DC_description),
1361 _factory.createIRI(val.toString()));
1362 else {
1363 theOntology.addNFPValue(_factory.createIRI(Constants.DC_description),
1364 createDataValueFromLiteral((Literal)val));
1365 }
1366 }
1367 RdfSchemaSource src = (RdfSchemaSource)_repository.getSail();
1368 NamespaceIterator nsIter = src.getNamespaces();
1369 while (nsIter.hasNext()) {
1370 nsIter.next();
1371 theOntology.addNamespace(_factory.createNamespace(nsIter.getPrefix(),
1372 _factory.createIRI( nsIter.getName())));
1373 }
1374
1375 }
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395 }
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444