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