001/**
002 * Copyright (C) 2007 - 2016, Jens Lehmann
003 *
004 * This file is part of DL-Learner.
005 *
006 * DL-Learner is free software; you can redistribute it and/or modify
007 * it under the terms of the GNU General Public License as published by
008 * the Free Software Foundation; either version 3 of the License, or
009 * (at your option) any later version.
010 *
011 * DL-Learner is distributed in the hope that it will be useful,
012 * but WITHOUT ANY WARRANTY; without even the implied warranty of
013 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
014 * GNU General Public License for more details.
015 *
016 * You should have received a copy of the GNU General Public License
017 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
018 */
019package org.dllearner.kb;
020
021import org.apache.jena.ontology.OntModelSpec;
022import org.apache.log4j.Logger;
023import org.dllearner.core.AbstractKnowledgeSource;
024import org.dllearner.core.ComponentAnn;
025import org.dllearner.core.ComponentInitException;
026import org.dllearner.core.annotations.NoConfigOption;
027import org.dllearner.core.config.ConfigOption;
028import org.dllearner.utilities.URLencodeUTF8;
029import org.semanticweb.owlapi.model.IRI;
030import org.semanticweb.owlapi.model.OWLOntology;
031import org.semanticweb.owlapi.model.OWLOntologyCreationException;
032import org.semanticweb.owlapi.model.OWLOntologyManager;
033
034import java.io.File;
035import java.net.MalformedURLException;
036import java.net.URISyntaxException;
037import java.net.URL;
038import java.nio.file.Path;
039import java.nio.file.Paths;
040import java.util.LinkedList;
041import java.util.List;
042
043/**
044 * @author Jens Lehmann
045 * @author Sebastian Hellmann
046 *         <p/>
047 *         SH added SPARQL capabilities.  Either URL is set directly or the basedir and filename is set or the URL and the SPARQL query is set
048 */
049@ComponentAnn(name = "OWL File", shortName = "owlfile", version = 0.9)
050public class OWLFile extends AbstractKnowledgeSource implements OWLOntologyKnowledgeSource {
051
052    private static Logger logger = Logger.getLogger(OWLFile.class);
053
054    // TODO: turn this into a config option
055    @ConfigOption(description = "URL pointer to the KB file or Endpoint")
056    private URL url;
057    @ConfigOption(description = "relative or absolute path to KB file")
058    private String fileName;
059    @ConfigOption(description = "separately specify directory of KB file")
060    private String baseDir;
061
062    @ConfigOption(description = "SPARQL CONSTRUCT expression to download from Endpoint")
063    private String sparql = null;
064    @ConfigOption(description = "a list of default graph URIs to query from the Endpoint")
065    private List<String> defaultGraphURIs = new LinkedList<>();
066    @ConfigOption(description = "a list of named graph URIs to query from the Endpoint")
067    private List<String> namedGraphURIs = new LinkedList<>();
068
069        @NoConfigOption // set via reasoningString
070    private OntModelSpec reasoning = OntModelSpec.OWL_MEM;
071    @ConfigOption(defaultValue = "false", description = "Enable JENA reasoning on the Ontology Model."
072                + " Available reasoners are: \"micro_rule\", \"mini_rule\", \"rdfs\", \"rule\"")
073    private String reasoningString = "";
074
075    public OWLFile() {
076
077    }
078
079    public OWLFile(URL url) {
080        this.url = url;
081    }
082
083    public OWLFile(String filename) {
084        try {
085            url = new File(filename).toURI().toURL();
086        } catch (MalformedURLException e) {
087            e.printStackTrace();
088        }
089    }
090
091    /* (non-Javadoc)
092      * @see org.dllearner.core.Component#init()
093      */
094    @Override
095    public void init() throws ComponentInitException {
096        setReasoning(getReasoningString());
097        if (sparql != null) {
098            StringBuilder sb = new StringBuilder();
099
100            //make URL
101            sb.append(url.toString());
102            sb.append("?query=").append(URLencodeUTF8.encode(sparql));
103            sb.append("&format=application%2Frdf%2Bxml");
104
105            for (String graph : defaultGraphURIs) {
106                sb.append("&default-graph-uri=").append(URLencodeUTF8.encode(graph));
107            }
108            for (String graph : namedGraphURIs) {
109                sb.append("&named-graph-uri=").append(URLencodeUTF8.encode(graph));
110            }
111            logger.debug(sb.toString());
112
113            try {
114                url = new URL(sb.toString());
115            } catch (MalformedURLException e) {
116                throw new RuntimeException(e);
117            }
118
119        } else if (url == null) {
120                try {
121                        Path path = Paths.get(fileName);
122
123                        if(!path.isAbsolute() && baseDir != null) {// else relative to base directory
124                                path = Paths.get(baseDir, fileName);
125                        }
126
127                        url = path.normalize().toUri().toURL();
128                } catch (MalformedURLException e) {
129                        throw new RuntimeException(e);
130                }
131        }
132        
133        initialized = true;
134    }
135
136    @Override
137    public OWLOntology createOWLOntology(OWLOntologyManager manager) {
138        try {
139                return manager.loadOntologyFromOntologyDocument(IRI.create(getURL().toURI()));
140        } catch (OWLOntologyCreationException | URISyntaxException e) {
141            throw new RuntimeException(e);
142        }
143    }
144
145    public URL getURL() {
146        return url;
147    }
148
149    public void setURL(URL url) {
150        this.url = url;
151    }
152
153    public String getBaseDir() {
154        return baseDir;
155    }
156
157        public void setBaseDir(String baseDir) {
158                this.baseDir = baseDir;
159        }
160
161    public URL getUrl() {
162        return url;
163    }
164
165    public void setUrl(URL url) {
166        this.url = url;
167    }
168
169    public String getFileName() {
170        return fileName;
171    }
172
173    public void setFileName(String fileName) {
174        this.fileName = fileName;
175    }
176
177    public String getSparql() {
178        return sparql;
179    }
180
181    public void setSparql(String sparql) {
182        setSparql(sparql, true);
183    }
184    
185    public void setSparql(String sparql, boolean autoQuote) {
186        if (autoQuote) {
187                // quote IRIs
188                sparql = sparql.replaceAll("(?<=^|\\s|\\()((?:([^<(:/?#\\s]*):)(?://([^/?#]*?))?([^?#]*?)(?:\\?([^#]*?))?(?:#(.*?))?)(?=(,|\\.|;|)(\\)|\\s|$))", "<$1>");
189        }
190        this.sparql = sparql;
191    }
192
193    public List<String> getDefaultGraphURIs() {
194        return defaultGraphURIs;
195    }
196
197    public void setDefaultGraphURIs(List<String> defaultGraphURIs) {
198        this.defaultGraphURIs = defaultGraphURIs;
199    }
200
201    public List<String> getNamedGraphURIs() {
202        return namedGraphURIs;
203    }
204
205    public void setNamedGraphURIs(List<String> namedGraphURIs) {
206        this.namedGraphURIs = namedGraphURIs;
207    }
208
209    public void setReasoning(String reasoning) {
210        switch (reasoning) {
211        case "micro_rule":
212                this.reasoning = OntModelSpec.OWL_MEM_MICRO_RULE_INF;
213                break;
214        case "mini_rule":
215                this.reasoning = OntModelSpec.OWL_MEM_MINI_RULE_INF;
216                break;
217        case "true":
218        case "rdfs":
219                this.reasoning = OntModelSpec.OWL_MEM_RDFS_INF;
220                break;
221        case "rule":
222                this.reasoning = OntModelSpec.OWL_MEM_RULE_INF;
223                break;
224        case "false":
225        case "":
226                this.reasoning = OntModelSpec.OWL_MEM;
227                break;
228        default:
229                logger.warn("Unknown reasoning type: " + reasoning + ", must be one of [micro_rule, mini_rule, rdfs, rule]");
230                this.reasoning = OntModelSpec.OWL_MEM;
231        }
232    }
233
234    public void setReasoning(boolean reasoning) {
235                this.setReasoning(reasoning ? "rdfs" : "");
236        }
237
238    public void setReasoning(OntModelSpec reasoning) {
239        this.reasoning = reasoning;
240    }
241
242        public OntModelSpec getReasoning() {
243                return this.reasoning;
244        }
245
246        public String getReasoningString() {
247                return reasoningString;
248        }
249
250        public void setReasoningString(String reasoningString) {
251                this.reasoningString = reasoningString;
252        }
253}