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 */
019/**
020 *
021 */
022package org.dllearner.kb.sparql.simple;
023
024import org.slf4j.Logger;
025import org.slf4j.LoggerFactory;
026
027import org.apache.jena.ontology.OntModel;
028import org.apache.jena.query.Query;
029import org.apache.jena.query.QueryExecution;
030import org.apache.jena.query.QueryExecutionFactory;
031import org.apache.jena.query.QueryFactory;
032import org.apache.jena.shared.JenaException;
033import com.jamonapi.Monitor;
034import com.jamonapi.MonitorFactory;
035
036/**
037 * @author didierc
038 */
039public class QueryExecutor {
040
041        private static Logger log = LoggerFactory.getLogger(QueryExecutor.class);
042
043        public OntModel executeQuery(String queryString, String endpoint,
044                        OntModel model, String defaultGraphURI) {
045                Monitor monQueryingTotal = MonitorFactory.start("Query time total")
046                                .start();
047                try {
048                        Query query = QueryFactory.create(queryString);
049                        log.debug("Jena Query: ", query);
050                        QueryExecution qExec;
051                        if (defaultGraphURI == null) {
052                                qExec = QueryExecutionFactory.sparqlService(endpoint, query);
053
054                        } else {
055                                qExec = QueryExecutionFactory.sparqlService(endpoint, query,
056                                                defaultGraphURI);
057                        }
058
059                        log.debug("Qexec: {}", qExec.getQuery());
060                        qExec.execConstruct(model);
061                } catch (JenaException e) {
062                        log.warn("Query failed (skipping):\n" + queryString, e);
063                }
064                monQueryingTotal.stop();
065                return model;
066        }
067}