src/main/java/net/timbusproject/reasoner/sparqlexecutor
File was removed.
src/main/resources/local-ontology.owl
File was removed.
src/main/java/net/timbusproject/reasoner/sparqlexecutor/Fuseki.java to src/main/java/net/timbusproject/reasoner/queryprocessor/QueryProcessor.java
--- a/src/main/java/net/timbusproject/reasoner/sparqlexecutor/Fuseki.java +++ b/src/main/java/net/timbusproject/reasoner/queryprocessor/QueryProcessor.java @@ -1,5 +1,5 @@ /** - * Copyright (c) 2013, Caixa Magica Software Lda (CMS). + * Copyright (c) 2014, Caixa Magica Software Lda (CMS). * The work has been developed in the TIMBUS Project and the above-mentioned are Members of the TIMBUS Consortium. * TIMBUS is supported by the European Union under the 7th Framework Programme for research and technological * development and demonstration activities (FP7/2007-2013) under grant agreement no. 269940. @@ -15,134 +15,127 @@ * License or out of the use or inability to use the Work. * See the License for the specific language governing permissions and limitation under the License. */ -package net.timbusproject.reasoner.sparqlexecutor; +package net.timbusproject.reasoner.queryprocessor; +import net.timbusproject.reasoner.spi.AbstractModule; +import net.timbusproject.reasoner.spi.IQueryProcessor; +import net.timbusproject.reasoner.spi.ModuleInstance; import org.apache.commons.io.IOUtils; -import org.apache.http.HttpResponse; -import org.apache.http.auth.AuthScope; -import org.apache.http.auth.UsernamePasswordCredentials; -import org.apache.http.client.HttpClient; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.utils.URIBuilder; -import org.apache.http.conn.scheme.Scheme; -import org.apache.http.conn.ssl.SSLSocketFactory; -import org.apache.http.impl.client.AbstractHttpClient; -import org.apache.http.impl.client.DefaultHttpClient; +import org.osgi.framework.BundleContext; +import org.semanticweb.owlapi.apibinding.OWLManager; +import org.semanticweb.owlapi.model.IRI; +import org.semanticweb.owlapi.model.OWLOntology; +import org.semanticweb.owlapi.model.OWLOntologyManager; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; -import javax.net.ssl.SSLContext; -import javax.net.ssl.TrustManager; -import javax.net.ssl.X509TrustManager; -import java.io.IOException; -import java.io.StringWriter; -import java.net.URISyntaxException; -import java.security.KeyManagementException; -import java.security.NoSuchAlgorithmException; -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; -import java.util.HashMap; -import java.util.Map; -import java.util.Scanner; +import java.io.FileNotFoundException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.URL; +import java.util.*; +import java.util.regex.Matcher; +import java.util.regex.Pattern; /** * Created with IntelliJ IDEA. * User: jorge - * Date: 10/8/13 - * Time: 3:58 PM + * Date: 9/30/13 + * Time: 11:49 AM * To change this template use File | Settings | File Templates. */ -public class Fuseki { +public class QueryProcessor extends AbstractModule implements IQueryProcessor { - enum Output { JSON, XML, TEXT, CSV, TSV; } + private final Logger log = LoggerFactory.getLogger(QueryProcessor.class); - private URIBuilder uri; - private String dataset; - - public Fuseki setURL(URIBuilder uri) { - if (uri == null) throw new IllegalArgumentException(); - this.uri = uri; - return this; - } - public Fuseki setDataset(String dataset) { - if (dataset == null || dataset.length() == 0) throw new IllegalArgumentException(); - this.dataset = dataset; - return this; + @Autowired + public QueryProcessor(BundleContext bundleContext) { + super(bundleContext); + log.debug("Instantiated."); } - private AbstractHttpClient buildHTTP(boolean secure) throws NoSuchAlgorithmException, KeyManagementException { - return secure ? buildHTTPS() : new DefaultHttpClient(); + private String getHostname(String machineId) { + Matcher matcher = Pattern.compile("xri://\\+machine\\?\\+hostid=(?<hostid>[^/]+)/\\+hostname=(?<hostname>[^/]+).*").matcher(machineId); + matcher.find(); + return matcher.group("hostname"); } - private AbstractHttpClient buildHTTPS() throws KeyManagementException, NoSuchAlgorithmException { - AbstractHttpClient https = new DefaultHttpClient(); - SSLContext sc = null; - sc = SSLContext.getInstance("SSL"); - sc.init(null, new TrustManager[]{new X509TrustManager() { + @Override + public ModuleInstance newInstance() { + return new ModuleInstance() { + @Override - public void checkClientTrusted(X509Certificate[] chain, String authType) - throws CertificateException { + public void run(Map<String, InputStream> input, Map<String, OutputStream> output) throws Exception { + final String ERR_NOT_FOUND = "Ontology %s could not be found"; + log.info("Fetching problem environment..."); + String request = IOUtils.toString(input.get("request")); + String target = IOUtils.toString(input.get("target")); + String dataset = IOUtils.toString(input.get("dataset")); + String fuseki = IOUtils.toString(input.get("fuseki")); + String ontology = IOUtils.toString(input.get("ontology")); + String universe = IOUtils.toString(input.get("universe")); + + log.info("Loading ontology..."); + double time = System.currentTimeMillis(); + OWLOntologyManager manager = OWLManager.createOWLOntologyManager(); + if (ontology.isEmpty()) + manager.loadOntologyFromOntologyDocument(new URL(getOntology(dataset, target)).openStream()); + else + manager.loadOntologyFromOntologyDocument(IRI.create(ontology)); + IRI software = IRI.create(target + "#software"); + OWLOntology owlOntology = getOntology(manager, software); + if (owlOntology == null) throw new FileNotFoundException(String.format(ERR_NOT_FOUND, software)); + + URL url = new URL(universe.isEmpty() ? getOntology(dataset, target, true) : universe); + try { + InputStream is = url.openStream(); + if (is != null) { + log.info("Loading universe..."); + Set<OWLOntology> ontologies = new HashSet<OWLOntology>(); + ontologies.add(manager.loadOntologyFromOntologyDocument(is)); + ontologies.add(owlOntology); + owlOntology = OWLManager.createOWLOntologyManager().createOntology( + IRI.create(target + "#merged"), ontologies + ); + } else + log.warn(String.format(ERR_NOT_FOUND, url)); + } catch (FileNotFoundException e) { + log.warn(String.format(ERR_NOT_FOUND, url)); + } + time = (System.currentTimeMillis() - time) / 1000.0 / 60.0; + + output.get("step.out").write(owlOntology.toString().getBytes()); + owlOntology.getOWLOntologyManager().saveOntology(owlOntology, output.get("out")); + log.info(String.format("Environment loaded (%.2fmin)", time)); } - @Override - public void checkServerTrusted(X509Certificate[] chain, String authType) - throws CertificateException { - } - @Override - public X509Certificate[] getAcceptedIssuers() { - return new X509Certificate[]{}; - } - }}, null); - Scheme sch = new Scheme("https", 443, new SSLSocketFactory(sc, SSLSocketFactory.STRICT_HOSTNAME_VERIFIER)); - https.getConnectionManager().getSchemeRegistry().register(sch); - - https.getCredentialsProvider().setCredentials( - new AuthScope(uri.getHost(), uri.getPort()), - loadDefaultCredentials("/default/credentials")); - return https; + }; } - private URIBuilder buildURI() { - return uri != null && uri.getHost() != null ? uri : (uri = loadDefaultEndpoint("/default/endpoint")); + private OWLOntology getOntology(OWLOntologyManager manager, IRI iri) { + for (OWLOntology o : manager.getOntologies()) + if (iri.equals(o.getOntologyID().getOntologyIRI())) + return o; + return null; } - private HashMap<String, Object> execute(Map<String, String> params) throws IOException, URISyntaxException, KeyManagementException, NoSuchAlgorithmException { - HttpClient http = null; - HttpResponse response = null; - StringWriter writer = new StringWriter(); - try { - URIBuilder builder = buildURI().setPath("/" + dataset + "/query"); - http = buildHTTP(builder.getScheme().toLowerCase().equals("https") || builder.getPort() == 443); - for (Map.Entry<String, String> p : params.entrySet()) { - builder.setParameter(p.getKey(), p.getValue()); - } - HttpGet get = new HttpGet(builder.build()); - response = http.execute(get); - IOUtils.copy(response.getEntity().getContent(), writer); - } finally { - if (http != null) { - http.getConnectionManager().shutdown(); - } - } - HashMap<String, Object> map = new HashMap<String, Object>(); - map.put("response", response); - map.put("content", writer.toString()); - return map; + private String getOntology(String dataset, String target) { + return getOntology(dataset, target, false); } - public HashMap<String, Object> query(String query, Output output) throws IOException, NoSuchAlgorithmException, KeyManagementException, URISyntaxException { - Map<String, String> params = new HashMap<String, String>(); - params.put("query", query); - params.put("output", output.toString().toLowerCase()); - return execute(params); + private String getOntology(String dataset, String target, boolean isUniverse) { + return String.format( + "http://localhost/ontologies/%s-%s-software", + (isUniverse ? "universes/" : "") + dataset, getHostname(target) + ); } - private URIBuilder loadDefaultEndpoint(String path) { - Scanner scanner = new Scanner(getClass().getResourceAsStream(path)); - return new URIBuilder().setHost(scanner.nextLine()) - .setPort(Integer.parseInt(scanner.nextLine())).setScheme(scanner.nextLine()); - } - - private UsernamePasswordCredentials loadDefaultCredentials(String path) { - Scanner scanner = new Scanner(getClass().getResourceAsStream(path)); - return new UsernamePasswordCredentials(scanner.nextLine(), scanner.nextLine()); + @Override + public String[] getContracts() { + Collection<String> c = new ArrayList<String>(); + for (Class<?> i : getClass().getInterfaces()) + c.add(i.getCanonicalName()); + return c.toArray(new String[c.size()]); } }