001    package org.nlp2rdf.ontology.impl;
002    
003    import com.hp.hpl.jena.ontology.OntModel;
004    import com.hp.hpl.jena.ontology.OntModelSpec;
005    import com.hp.hpl.jena.rdf.model.ModelFactory;
006    import org.apache.log4j.Logger;
007    import org.nlp2rdf.ontology.OntologyLoader;
008    
009    import java.io.File;
010    import java.io.FileOutputStream;
011    import java.io.IOException;
012    import java.io.UnsupportedEncodingException;
013    import java.net.URL;
014    import java.net.URLEncoder;
015    import java.nio.channels.Channels;
016    import java.nio.channels.ReadableByteChannel;
017    
018    /**
019     * Loads and caches Ontologies in cacheDir
020     * Use loadImports to recursively load any models. They will be included as Jena submodels
021     *
022     * @author Sebastian Hellmann <hellmann@informatik.uni-leipzig.de>
023     */
024    public class OntologyCache extends SimpleLoader implements OntologyLoader {
025        private static final Logger log = Logger.getLogger(OntologyCache.class);
026        final private String cacheDir;
027    
028    
029        public OntologyCache(String cacheDir) {
030            this.cacheDir = cacheDir;
031            File f = new File(cacheDir);
032            if (!f.exists()) {
033                f.mkdir();
034            }
035        }
036    
037    
038        @Override
039        public OntModel loadOntology(String ontologyUri) {
040            OntModel model = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM, ModelFactory.createDefaultModel());
041            try {
042                if (!isOntologyCached(ontologyUri)) {
043    
044                    cache(ontologyUri);
045                    log.info("ontology " + ontologyUri + " was cached. To refresh, delete folder: " + new File(cacheDir).getAbsolutePath());
046                }
047    
048                model.read(new File(makeFilenameFromOntologyUrl(ontologyUri)).toURI().toURL().toString());
049                log.info("ontology " + ontologyUri + " was loaded from cache. To refresh, delete folder: " + new File(cacheDir).getAbsolutePath());
050    
051            } catch (IOException e) {
052                log.warn("caching ontology failed, trying to load from url");
053                model.read(ontologyUri);
054            } catch (Exception e) {
055                log.error("Could not load cached ontology trying to download", e);
056            }
057    
058            return model;
059        }
060    
061        public void clearCache() {
062    
063            File[] files = listAllFiles();
064            for (File file : files) {
065                try {
066                    if (file.delete()) {
067                        log.info("Deleted file " + file.toString());
068                    }
069                } catch (Exception e) {
070                    log.warn("could not delete file");
071                }
072    
073            }
074        }
075    
076        private File[] listAllFiles() {
077            File f = new File(cacheDir);
078            return f.listFiles();
079        }
080    
081        /*
082        private void initMapping() {
083            File[] files = listAllFiles();
084            LocationMapper l = FileManager.get().getLocationMapper();
085            for (File f : files) {
086                try {
087                    l.altMapping(URLDecoder.decode(f.toString(), "UTF-8"), f.toURI().toURL().toString());
088                } catch (MalformedURLException e) {
089                    log.error("", e);
090                } catch (UnsupportedEncodingException e) {
091                    log.error("", e);
092                }
093            }
094        }
095         */
096    
097        public void download(String from, String to) throws IOException {
098    
099            try {
100                URL google = new URL(from);
101                ReadableByteChannel rbc = Channels.newChannel(google.openStream());
102                FileOutputStream fos = new FileOutputStream(to);
103                fos.getChannel().transferFrom(rbc, 0, 1 << 24);
104                log.debug("successfully downloaded " + from + " to " + to + " ");
105            } catch (IOException e) {
106                log.warn("caching the ontology failed " + from, e);
107            }
108    
109        }
110    
111        //encodes the ontologyUrls
112        private String makeFilenameFromOntologyUrl(String ontologyUrl) throws UnsupportedEncodingException {
113            return cacheDir + URLEncoder.encode(ontologyUrl, "UTF-8");
114        }
115    
116        private void cache(String ontologyUrl) throws IOException {
117            download(ontologyUrl, makeFilenameFromOntologyUrl(ontologyUrl));
118        }
119    
120    
121        public static void main(String[] args) throws IOException {
122            OntologyCache oc = new OntologyCache("/tmp/");
123            OntModel m = oc.loadOntology("http://nachhalt.sfb632.uni-potsdam.de/owl/stanford.owl");
124            oc.loadImports(m);
125        }
126    
127        public boolean isOntologyCached(String ontologyUri) {
128            try {
129                return new File(makeFilenameFromOntologyUrl(ontologyUri)).exists();
130            } catch (Exception e) {
131                log.error("", e);
132            }
133            return false;
134    
135        }
136    }