View Javadoc

1   /*
2    ORDI - Ontology Repository and Data Integration
3   
4    Copyright (c) 2004-2007, 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  package com.ontotext.ordi.wsmo4rdf;
19  
20  import java.io.File;
21  import java.io.IOException;
22  import java.io.Reader;
23  import java.io.StringReader;
24  import java.util.ArrayList;
25  import java.util.HashMap;
26  import java.util.HashSet;
27  import java.util.Iterator;
28  import java.util.List;
29  import java.util.Map;
30  import java.util.Set;
31  import java.util.Map.Entry;
32  
33  import org.openrdf.model.Statement;
34  import org.openrdf.model.URI;
35  import org.openrdf.rio.RDFHandler;
36  import org.openrdf.rio.RDFHandlerException;
37  import org.openrdf.rio.RDFParser;
38  import org.openrdf.rio.RDFParserFactory;
39  import org.openrdf.rio.rdfxml.RDFXMLParserFactory;
40  import org.wsmo.common.Entity;
41  import org.wsmo.common.IRI;
42  import org.wsmo.common.TopEntity;
43  import org.wsmo.common.exception.InvalidModelException;
44  import org.wsmo.factory.Factory;
45  import org.wsmo.factory.LogicalExpressionFactory;
46  import org.wsmo.factory.WsmoFactory;
47  import org.wsmo.wsml.Parser;
48  import org.wsmo.wsml.ParserException;
49  
50  import com.ontotext.ordi.exception.ORDIException;
51  import com.ontotext.ordi.exception.ORDIRuntimeException;
52  import com.ontotext.ordi.tripleset.ORDIConst;
53  import com.ontotext.ordi.tripleset.TConnection;
54  import com.ontotext.ordi.tripleset.TSource;
55  import com.ontotext.ordi.trree.TRREEAdapter;
56  import com.ontotext.ordi.wsmo4rdf.impl.Util;
57  import com.ontotext.ordi.wsmo4rdf.impl.WSMLConnectionAdapterImpl;
58  import com.ontotext.ordi.wsmo4rdf.impl.WSMLfromTriplesImpl;
59  import com.ontotext.ordi.wsmo4rdf.impl.WSMLConnectionAdapterImpl.IteratorAdapter;
60  import com.ontotext.ordi.wsmo4rdf.impl.WSMLConnectionAdapterImpl.WSMLTriple;
61  
62  public class WSMLTripleParser implements Parser {
63  
64      public static final String BASE_URL = "BASE_URL";
65      public static final String DEFAULT_BASE_URL = "urn:ordi:default:";
66      private final WsmoFactory wsmoFactory;
67      private final LogicalExpressionFactory leFactory;
68      private final Object baseURL;
69  
70      public WSMLTripleParser(Map<Object, Object> params) {
71          // Initialize WSMO factories
72          Object factory = params.get(Factory.WSMO_FACTORY);
73          if (factory == null || factory instanceof WsmoFactory == false) {
74              factory = Factory.createWsmoFactory(null);
75          }
76          wsmoFactory = (WsmoFactory) factory;
77          factory = params.get(Factory.LE_FACTORY);
78          if (factory == null
79                  || factory instanceof LogicalExpressionFactory == false) {
80              factory = Factory.createLogicalExpressionFactory(null);
81          }
82          leFactory = (LogicalExpressionFactory) factory;
83          baseURL = params.get(BASE_URL);
84      }
85  
86      public TopEntity[] parse(Reader src) throws IOException, ParserException,
87              InvalidModelException {
88          if (src == null) {
89              throw new IllegalArgumentException();
90          }
91          return parseWithBaseURL(src, baseURL);
92      }
93  
94      @SuppressWarnings("unchecked")
95      public TopEntity[] parse(Reader src, Map options) throws IOException,
96              ParserException, InvalidModelException {
97          if (src == null) {
98              throw new IllegalArgumentException();
99          }
100         if (options == null) {
101             options = new HashMap();
102         }
103         return parseWithBaseURL(src, options.get(BASE_URL));
104     }
105 
106     public TopEntity[] parse(StringBuffer src) throws ParserException,
107             InvalidModelException {
108         try {
109             if (src == null) {
110                 throw new IllegalArgumentException();
111             }
112             return parse(new StringReader(src.toString()));
113         } catch (IOException e) {
114             throw new RuntimeException("Internal IOException!", e);
115         }
116     }
117 
118     @SuppressWarnings("unchecked")
119     public TopEntity[] parse(StringBuffer src, Map options)
120             throws ParserException, InvalidModelException {
121         if (src == null) {
122             throw new IllegalArgumentException();
123         }
124         if (options == null) {
125             options = new HashMap();
126         }
127         return parse(src);
128     }
129 
130     public Set<String> listKeywords() {
131         return new HashSet<String>();
132     }
133 
134     public List<Object> getWarnings() {
135         return new ArrayList<Object>();
136     }
137 
138     public List<Object> getErrors() {
139         return new ArrayList<Object>();
140     }
141 
142     private TopEntity[] parseWithBaseURL(Reader src, Object baseURL)
143             throws IOException, ParserException, InvalidModelException {
144         if (baseURL == null)
145             baseURL = this.baseURL != null ? this.baseURL : DEFAULT_BASE_URL;
146 
147         File tempDir = new File(System.getProperty("java.io.tmpdir")
148                 + File.separator + "wsmlparser-" + System.currentTimeMillis());
149         tempDir.mkdir();
150 
151         try {
152             Map<Object, Object> props = new HashMap<Object, Object>();
153             props
154                     .put(TRREEAdapter.STORAGE_DIRECTORY, tempDir
155                             .getAbsolutePath());
156             TSource source = com.ontotext.ordi.Factory.createTSource(props);
157             TConnection connection = source.getConnection();
158 
159             RDFParserFactory factory = new RDFXMLParserFactory();
160             RDFParser parser = factory.getParser();
161             WSMLRDFHandler handler = new WSMLRDFHandler(source.getConnection());
162             parser.setRDFHandler(handler);
163 
164             try {
165                 parser.parse(src, baseURL.toString());
166             } catch (Exception e) {
167                 throw new ORDIRuntimeException("Error while parsing the RDF!",
168                         e);
169             }
170             WSMLfromTriples wsmlBuilder = new WSMLfromTriplesImpl(wsmoFactory,
171                     leFactory, connection);
172             WSMLConnectionAdapterImpl wsmlConnection = new WSMLConnectionAdapterImpl(
173                     connection);
174             List<TopEntity> result = new ArrayList<TopEntity>();
175             String[] metaClass = new String[] { Constants.WSML_ontology,
176                     Constants.WSML_ggMediator, Constants.WSML_wgMediator,
177                     Constants.WSML_wwMediator, Constants.WSML_ooMediator,
178                     Constants.WSML_goal, Constants.WSML_webService };
179             for (int i = 0; i < metaClass.length; i++) {
180                 IteratorAdapter iterator = wsmlConnection.search(null,
181                         wsmoFactory.createIRI(Constants.RDF_type), wsmoFactory
182                                 .createIRI(metaClass[i]));
183                 while (iterator.hasNext()) {
184                     WSMLTriple triple = iterator.next();
185                     Iterator<Entity> eIterator = wsmlBuilder.construct(
186                             triple.getSubject()).iterator();
187                     while (eIterator.hasNext()) {
188                         TopEntity te = (TopEntity) eIterator.next();
189                         Iterator<Entry<String, IRI>> nsIter = handler.namespaces
190                                 .entrySet().iterator();
191                         while (nsIter.hasNext()) {
192                             Entry<String, IRI> entry = nsIter.next();
193                             if (entry.getKey().length() > 0) {
194                                 te.addNamespace(wsmoFactory.createNamespace(entry
195                                         .getKey(), entry.getValue()));
196                             }
197                             else {
198                                 te.setDefaultNamespace(entry.getValue());
199                             }
200                         }
201                         result.add(te);
202                     }
203                 }
204             }
205             source.shutdown();
206             return result.toArray(new TopEntity[result.size()]);
207         } finally {
208             deleteNonEmptyDir(tempDir);
209         }
210     }
211 
212     private void deleteNonEmptyDir(File file) {
213         if (file.isDirectory()) {
214             File[] files = file.listFiles();
215             for (int i = 0; i < files.length; i++)
216                 deleteNonEmptyDir(files[i]);
217         }
218         file.delete();
219     }
220 
221     private class WSMLRDFHandler implements RDFHandler {
222 
223         private TConnection connection;
224         private URI namedGraph;
225         private Map<String, IRI> namespaces = new HashMap<String, IRI>();
226 
227         public WSMLRDFHandler(TConnection connection) {
228             if (connection == null || connection.isOpen() == false) {
229                 throw new IllegalArgumentException(
230                         "The connection is not opened or invalid!");
231             }
232             this.connection = connection;
233             namedGraph = Util.toURI(wsmoFactory
234                     .createIRI(ORDIConst.DEFAULT_GRAPH));
235         }
236 
237         public void startRDF() {
238         }
239 
240         public void endRDF() {
241         }
242 
243         public void handleComment(String comment) {
244         }
245 
246         public void handleNamespace(String ns, String prefix) {
247             if (ns.startsWith("wsmo4rdf_"))
248                 return;
249             if (namespaces.containsKey(ns) == false)
250                 namespaces.put(ns, wsmoFactory.createIRI(prefix));
251         }
252 
253         public void handleStatement(Statement statement)
254                 throws RDFHandlerException {
255             try {
256                 connection.addStatement(statement.getSubject(), statement
257                         .getPredicate(), statement.getObject(), namedGraph);
258             } catch (ORDIException e) {
259                 throw new RDFHandlerException("Error while writting.", e);
260             }
261         }
262     }
263 }