Revision: 13716
          http://gate.svn.sourceforge.net/gate/?rev=13716&view=rev
Author:   valyt
Date:     2011-04-20 14:21:52 +0000 (Wed, 20 Apr 2011)

Log Message:
-----------
A simple Mimir plugin that connects to an external SPARQL endpoint in order to 
apply some semantic constraints to a query.

Added Paths:
-----------
    mimir/trunk/plugins/sparql/.classpath
    mimir/trunk/plugins/sparql/.project
    mimir/trunk/plugins/sparql/.settings/
    mimir/trunk/plugins/sparql/.settings/org.eclipse.jdt.core.prefs
    mimir/trunk/plugins/sparql/build.xml
    mimir/trunk/plugins/sparql/creole.xml
    mimir/trunk/plugins/sparql/src/
    mimir/trunk/plugins/sparql/src/gate/
    mimir/trunk/plugins/sparql/src/gate/mimir/
    mimir/trunk/plugins/sparql/src/gate/mimir/sparql/
    mimir/trunk/plugins/sparql/src/gate/mimir/sparql/SPARQLResultSet.java
    
mimir/trunk/plugins/sparql/src/gate/mimir/sparql/SPARQLSemanticAnnotationHelper.java

Property Changed:
----------------
    mimir/trunk/plugins/sparql/


Property changes on: mimir/trunk/plugins/sparql
___________________________________________________________________
Added: svn:ignore
   + mimir-plugin-sparql-*.jar


Added: mimir/trunk/plugins/sparql/.classpath
===================================================================
--- mimir/trunk/plugins/sparql/.classpath                               (rev 0)
+++ mimir/trunk/plugins/sparql/.classpath       2011-04-20 14:21:52 UTC (rev 
13716)
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+       <classpathentry kind="src" path="src"/>
+       <classpathentry kind="con" 
path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>
+       <classpathentry combineaccessrules="false" kind="src" 
path="/mimir-core"/>
+       <classpathentry kind="output" path="classes"/>
+</classpath>


Property changes on: mimir/trunk/plugins/sparql/.classpath
___________________________________________________________________
Added: svn:eol-style
   + native

Added: mimir/trunk/plugins/sparql/.project
===================================================================
--- mimir/trunk/plugins/sparql/.project                         (rev 0)
+++ mimir/trunk/plugins/sparql/.project 2011-04-20 14:21:52 UTC (rev 13716)
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+       <name>mimir-plugin-sparql</name>
+       <comment></comment>
+       <projects>
+       </projects>
+       <buildSpec>
+               <buildCommand>
+                       
<name>org.eclipse.wst.common.project.facet.core.builder</name>
+                       <arguments>
+                       </arguments>
+               </buildCommand>
+               <buildCommand>
+                       <name>org.eclipse.jdt.core.javabuilder</name>
+                       <arguments>
+                       </arguments>
+               </buildCommand>
+       </buildSpec>
+       <natures>
+               <nature>org.eclipse.jdt.core.javanature</nature>
+               
<nature>org.eclipse.wst.common.project.facet.core.nature</nature>
+       </natures>
+</projectDescription>


Property changes on: mimir/trunk/plugins/sparql/.project
___________________________________________________________________
Added: svn:eol-style
   + native

Added: mimir/trunk/plugins/sparql/.settings/org.eclipse.jdt.core.prefs
===================================================================
--- mimir/trunk/plugins/sparql/.settings/org.eclipse.jdt.core.prefs             
                (rev 0)
+++ mimir/trunk/plugins/sparql/.settings/org.eclipse.jdt.core.prefs     
2011-04-20 14:21:52 UTC (rev 13716)
@@ -0,0 +1,12 @@
+#Tue Apr 19 11:34:27 BST 2011
+eclipse.preferences.version=1
+org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
+org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
+org.eclipse.jdt.core.compiler.compliance=1.6
+org.eclipse.jdt.core.compiler.debug.lineNumber=generate
+org.eclipse.jdt.core.compiler.debug.localVariable=generate
+org.eclipse.jdt.core.compiler.debug.sourceFile=generate
+org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
+org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
+org.eclipse.jdt.core.compiler.source=1.6


Property changes on: 
mimir/trunk/plugins/sparql/.settings/org.eclipse.jdt.core.prefs
___________________________________________________________________
Added: svn:eol-style
   + native

Added: mimir/trunk/plugins/sparql/build.xml
===================================================================
--- mimir/trunk/plugins/sparql/build.xml                                (rev 0)
+++ mimir/trunk/plugins/sparql/build.xml        2011-04-20 14:21:52 UTC (rev 
13716)
@@ -0,0 +1,70 @@
+<project name="mimir-plugin-sparql" default="jar" basedir=".">
+       <property name="app.name" value="mimir-plugin-sparql" />
+       <property name="app.title" value="Mimir Plugin: SPARQL" />
+       
+  <!-- Common Properties -->
+       
+  <property environment="env"/>
+       <property name="core-home" value="../../mimir-core"/>
+       <property file="${core-home}/build.properties" />
+       
+  <path id="core-libs">
+    <fileset dir="${core-home}/lib" includes="**/*.jar" />
+       <fileset dir="${core-home}" includes="mimir-core-*.jar" />
+  </path>
+       
+  <property name="classes.dir" location="classes" />
+  <property name="src.dir" location="src" />
+  <property name="doc.dir" location="doc" />
+  
+  <property name="jar.file" location="${app.name}-${app.version}.jar" />
+  <path id="compile.classpath">
+    <path refid="core-libs" />
+  </path>
+               
+  <target name="clean">
+    <delete dir="${classes.dir}"/>
+    <delete file="${jar.file}"/>
+  </target>
+  
+  <target name="compile">
+    <mkdir dir="${classes.dir}"/>
+    <javac destdir="${classes.dir}"
+           srcdir="${src.dir}"
+           debug="true"
+           target="1.6"
+           source="1.6"
+           classpathref="compile.classpath" />
+  </target>
+  
+  <target name="jar" depends="clean, compile">
+    <jar file="${jar.file}" basedir="${classes.dir}" update="false">
+       </jar>
+  </target>  
+  
+  <target name="distro" depends="jar, javadoc" />
+  
+  <!-- Docs -->
+  <target name="javadoc">
+         <javadoc access="protected"
+                  destdir="${doc.dir}/javadoc"
+                  classpathref="compile.classpath"
+                  Encoding="UTF-8"
+                  Use="yes"
+                  Windowtitle="${app.title} (${app.version}) JavaDoc"
+                  docencoding="UTF-8"
+                  charset="UTF-8"
+                  source="1.6"
+                  useexternalfile="yes"
+                  breakiterator="true">
+           <fileset dir="${src.dir}" includes="**/*.java"/>
+           <link href="http://java.sun.com/javase/6/docs/api/"/>
+           <link href="http://hudson.gate.ac.uk/job/GATE-Nightly/javadoc/"/>
+         </javadoc>
+         <zip destfile="${app.name}-${app.version}-javadocs.zip">
+           <zipfileset dir="${doc.dir}/javadoc"
+                       prefix="${app.name}-${app.version}-javadocs" />
+         </zip>
+         <delete dir="${doc.dir}/javadoc" />
+  </target>
+</project>


Property changes on: mimir/trunk/plugins/sparql/build.xml
___________________________________________________________________
Added: svn:eol-style
   + native

Added: mimir/trunk/plugins/sparql/creole.xml
===================================================================
--- mimir/trunk/plugins/sparql/creole.xml                               (rev 0)
+++ mimir/trunk/plugins/sparql/creole.xml       2011-04-20 14:21:52 UTC (rev 
13716)
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<!-- This plugin does not provide any GATE resources, but uses the CREOLE 
+mechanism to supply a set of jar files to be added to the classpath of the 
caller.-->
+<CREOLE-DIRECTORY>
+  <JAR>mimir-plugin-sparql-3.2.0-snapshot.jar</JAR>
+</CREOLE-DIRECTORY>

Added: mimir/trunk/plugins/sparql/src/gate/mimir/sparql/SPARQLResultSet.java
===================================================================
--- mimir/trunk/plugins/sparql/src/gate/mimir/sparql/SPARQLResultSet.java       
                        (rev 0)
+++ mimir/trunk/plugins/sparql/src/gate/mimir/sparql/SPARQLResultSet.java       
2011-04-20 14:21:52 UTC (rev 13716)
@@ -0,0 +1,304 @@
+/*
+ *  SPARQLResultSet.java
+ *
+ *  Copyright (c) 2007-2011, The University of Sheffield.
+ *
+ *  This file is part of GATE Mímir (see http://gate.ac.uk/family/mimir.html), 
+ *  and is free software, licenced under the GNU Affero General Public License,
+ *  Version 3, November 2007 (also included with this distribution as file 
+ *  LICENCE-AGPL3.html).
+ *
+ *  A commercial licence is also available for organisations whose business
+ *  models preclude the adoption of open source and is subject to a licence
+ *  fee charged by the University of Sheffield. Please contact the GATE team
+ *  (see http://gate.ac.uk/g8/contact) if you require a commercial licence.
+ *
+ *  Valentin Tablan, 20 Apr 2011
+ *  
+ *  $Id$
+ */
+package gate.mimir.sparql;
+
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.Reader;
+import java.io.StringReader;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.LinkedList;
+import java.util.List;
+
+import javax.xml.stream.XMLInputFactory;
+import javax.xml.stream.XMLStreamConstants;
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.XMLStreamReader;
+
+import org.apache.log4j.Logger;
+
+/**
+ * Class representing the result set from a SPARQL query.
+ */
+public class SPARQLResultSet {
+  
+  /**
+   * Re-usable XML input factory used when parsing XML streams.
+   */
+  private static XMLInputFactory xmlInputFactory;
+  
+  static {
+    xmlInputFactory =  XMLInputFactory.newInstance();
+    xmlInputFactory.setProperty("javax.xml.stream.isCoalescing", Boolean.TRUE);
+  }
+  
+  private static final String XMLNS = "http://www.w3.org/2005/sparql-results#";;
+  
+  private static final Logger logger = Logger.getLogger(SPARQLResultSet.class);
+  
+  
+  private String[] variableNames;
+  
+  private String[][] rows;
+  
+
+  /**
+   * 
+   * The supplied input stream will be drained and closed.
+   * @param is
+   * @throws XMLStreamException
+   */
+  public SPARQLResultSet(InputStream is) throws XMLStreamException {
+    this(xmlInputFactory.createXMLStreamReader(is));
+    try{
+      is.close();
+    } catch(IOException e) {
+      logger.error("Could not close the input stream!", e);
+    }
+  }
+  
+  public SPARQLResultSet(Reader reader) throws XMLStreamException {
+    this(xmlInputFactory.createXMLStreamReader(reader));
+    try{
+      reader.close();
+    } catch(IOException e) {
+      logger.error("Could not close the input reader!", e);
+    }
+  }
+  
+  public SPARQLResultSet(XMLStreamReader xsr) throws XMLStreamException {
+    try{
+      // A SPARQL result, in XML looks like this:
+      //<?xml version="1.0"?>
+      //<sparql xmlns="http://www.w3.org/2005/sparql-results#";>
+      //
+      //  <head>
+      //    <variable name="x"/>
+      //    <variable name="hpage"/>
+      //    <variable name="name"/>
+      //    <variable name="age"/>
+      //    <variable name="mbox"/>
+      //    <variable name="friend"/>
+      //  </head>
+      //
+      //  <results>
+      //
+      //    <result> 
+      //      <binding name="x">
+      //  <bnode>r2</bnode>
+      //      </binding>
+      //      <binding name="hpage">
+      //  <uri>http://work.example.org/bob/</uri>
+      //      </binding>
+      //      <binding name="name">
+      //  <literal xml:lang="en">Bob</literal>
+      //      </binding>
+      //      <binding name="age">
+      //  <literal 
datatype="http://www.w3.org/2001/XMLSchema#integer";>30</literal>
+      //      </binding>
+      //      <binding name="mbox">
+      //  <uri>mailto:[email protected]</uri>
+      //      </binding>
+      //    </result>
+      //
+      //    ...
+      //  </results>
+      //
+      //</sparql>
+      
+      // find the root element
+      while(xsr.next() != XMLStreamConstants.START_ELEMENT) {
+        //do nothing
+      }
+      xsr.require(XMLStreamConstants.START_ELEMENT, XMLNS, "sparql");
+      // find the first element
+      int type = xsr.nextTag(); 
+      while(type == XMLStreamConstants.START_ELEMENT) {
+        String elemName = xsr.getLocalName();
+        if(elemName.equals("head")) {
+          parseHead(xsr);
+          xsr.require(XMLStreamConstants.END_ELEMENT, XMLNS, "head");
+        } else if(elemName.equals("results")) {
+          parseResults(xsr);
+          xsr.require(XMLStreamConstants.END_ELEMENT, XMLNS, "results");
+        } else {
+          // unknown element -> skip it
+          type = xsr.next();
+          while(!(type == XMLStreamConstants.END_ELEMENT && 
+                xsr.getLocalName().equals(elemName))) {
+            type = xsr.next();
+          }
+        }
+        // find the next element event
+        type = xsr.nextTag();
+      }
+      xsr.require(XMLStreamConstants.END_ELEMENT, XMLNS, "sparql");
+    } finally {
+      xsr.close();
+    }
+  }
+  
+  private void parseHead(XMLStreamReader xsr) throws XMLStreamException {
+    List<String> variables = new LinkedList<String>();
+    xsr.require(XMLStreamConstants.START_ELEMENT, XMLNS, "head");
+    int type = xsr.nextTag();
+    while(!(type == XMLStreamConstants.END_ELEMENT && 
+            xsr.getLocalName().equals("head"))) {
+      if(type == XMLStreamConstants.START_ELEMENT) {
+        String elemName = xsr.getLocalName();
+        if(elemName.equals("variable")) {
+          String varName = xsr.getAttributeValue(null, "name");
+          if(varName != null) variables.add(varName);
+        }
+        // consume all till the end of this element 
+        type = xsr.next();
+        while(! (type == XMLStreamConstants.END_ELEMENT && 
+                xsr.getLocalName().equals(elemName))){
+          type = xsr.next();
+        }
+      }
+      type = xsr.next();
+    }
+    variableNames = variables.toArray(new String[variables.size()]);
+  }
+  
+  private void parseResults(XMLStreamReader xsr) throws XMLStreamException {
+    xsr.require(XMLStreamConstants.START_ELEMENT, XMLNS, "results");
+    List<String[]> results = new LinkedList<String[]>();
+    int type = xsr.nextTag();
+    while(type == XMLStreamConstants.START_ELEMENT) {
+      xsr.require(XMLStreamConstants.START_ELEMENT, XMLNS, "result");
+      String[] aResult = new String[variableNames.length];
+      Arrays.fill(aResult, null);
+      type = xsr.nextTag();
+      while(type == XMLStreamConstants.START_ELEMENT) {
+        xsr.require(XMLStreamConstants.START_ELEMENT, XMLNS, "binding");
+        String varName = xsr.getAttributeValue(null, "name");
+        int column = 0;
+        while(column < variableNames.length && 
+              !variableNames[column].equals(varName)){
+          column++;
+        }
+        if(column >= variableNames.length){
+          throw new RuntimeException("Malformed input: could not find column " 
+
+                       "for variable \"" + varName + "\" ");
+        }
+        type = xsr.nextTag();
+        xsr.require(XMLStreamConstants.START_ELEMENT, XMLNS, null);
+        String elemName = xsr.getLocalName();
+        if(elemName.equals("uri")) {
+          aResult[column] = xsr.getElementText();
+          xsr.require(XMLStreamConstants.END_ELEMENT, XMLNS, elemName);
+        } else if(elemName.equals("literal")) {
+          aResult[column] = xsr.getElementText();
+          xsr.require(XMLStreamConstants.END_ELEMENT, XMLNS, elemName);
+        } else {
+          // some other kind of element, we don't care about
+          type = xsr.next();
+          while(! (type == XMLStreamConstants.END_ELEMENT && 
+                  xsr.getLocalName().equals(elemName))){
+            type = xsr.next();
+          }
+        }
+        // find the closing binding tag
+        type = xsr.nextTag();
+        xsr.require(XMLStreamConstants.END_ELEMENT, XMLNS, "binding");
+        // ...and open the next one  
+        type = xsr.nextTag();
+      }
+      xsr.require(XMLStreamConstants.END_ELEMENT, XMLNS, "result");
+      // save the new result
+      results.add(aResult);
+      type = xsr.nextTag();
+    }
+    xsr.require(XMLStreamConstants.END_ELEMENT, XMLNS, "results");
+    rows = results.toArray(new String[results.size()][]);
+  }
+  
+  /**
+   * The names of the bound variables, as returned by the SPARQL endpoint.
+   * @return
+   */
+  public String[] getColumnNames() {
+    return variableNames;
+  }
+  
+  /**
+   * The values returned by the SPARQL endpoint. Each row is an array of String
+   * values, each entry in the array being a value for the corresponding 
column 
+   * (as returned by {@link #getColumnNames()}).  
+   * @return a bi-dimnesional array of Strings, where the first index selects 
+   * the row, and the second index selects the column. 
+   */
+  public String[][] getRows() {
+    return rows;
+  }
+  
+  @Override
+  public String toString() {
+    StringBuilder str = new StringBuilder();
+    if(variableNames != null) {
+      for(int i = 0; i < variableNames.length; i++) {
+        if(i > 0) str.append(", ");
+        str.append(variableNames[i] != null ? 
+                "\"" + variableNames[i] + "\"" : "null");
+      }
+      str.append("\n");
+    }
+    
+    if(rows != null) {
+      for(String[] aRow : rows) {
+        for(int i = 0; i < aRow.length; i++) {
+          if(i > 0) str.append(", ");
+          str.append(aRow[i] != null ? "\"" + aRow[i] + "\"" : "null");
+        }
+        str.append("\n");  
+      }
+    }
+    return str.toString();
+  }
+
+  public static void main(String[] args) throws Exception{
+    String query = "PREFIX owl: <http://www.w3.org/2002/07/owl#>\n" +
+               "PREFIX dbpedia: <http://dbpedia.org/resource/>\n" +
+               "PREFIX dbp: <http://dbpedia.org/ontology/>\n" +
+               "PREFIX foaf: <http://xmlns.com/foaf/0.1/>\n" +
+               "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\n" +
+               "SELECT DISTINCT ?label ?inst ?cls\n" +
+               "   WHERE {\n" +
+               "   {\n" +
+               "     ?inst dbp:type dbpedia:Public_company .\n" +
+               "     ?inst foaf:name ?label .\n" +
+               "     FILTER (lang(?label) = \"en\")\n" +
+                               "     ?inst a ?cls .\n" +
+                               "     ?cls a owl:Class .\n" +
+                               "     FILTER (?cls = dbp:Company)\n" +
+                               "   }\n" +
+                               "}";
+    SPARQLSemanticAnnotationHelper ssah = new SPARQLSemanticAnnotationHelper(
+            "annType", 
"http://localhost:8080/openrdf-workbench/repositories/DBPedia/query";, new 
String[]{}, 
+            new String[]{}, new String[]{}, new String[]{}, new String[]{}, 
+            null);
+    System.out.println(ssah.runQuery(query));
+  }
+  
+}


Property changes on: 
mimir/trunk/plugins/sparql/src/gate/mimir/sparql/SPARQLResultSet.java
___________________________________________________________________
Added: svn:keywords
   + Id
Added: svn:eol-style
   + native

Added: 
mimir/trunk/plugins/sparql/src/gate/mimir/sparql/SPARQLSemanticAnnotationHelper.java
===================================================================
--- 
mimir/trunk/plugins/sparql/src/gate/mimir/sparql/SPARQLSemanticAnnotationHelper.java
                                (rev 0)
+++ 
mimir/trunk/plugins/sparql/src/gate/mimir/sparql/SPARQLSemanticAnnotationHelper.java
        2011-04-20 14:21:52 UTC (rev 13716)
@@ -0,0 +1,154 @@
+/*
+ * SPARQLSemanticAnnotationHelper.java
+ * 
+ * Copyright (c) 2007-2011, The University of Sheffield.
+ * 
+ * This file is part of GATE Mímir (see http://gate.ac.uk/family/mimir.html),
+ * and is free software, licenced under the GNU Affero General Public License,
+ * Version 3, November 2007 (also included with this distribution as file
+ * LICENCE-AGPL3.html).
+ * 
+ * A commercial licence is also available for organisations whose business
+ * models preclude the adoption of open source and is subject to a licence fee
+ * charged by the University of Sheffield. Please contact the GATE team (see
+ * http://gate.ac.uk/g8/contact) if you require a commercial licence.
+ * 
+ * Valentin Tablan, 19 Apr 2011
+ * 
+ * $Id$
+ */
+package gate.mimir.sparql;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.UnsupportedEncodingException;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.net.URLEncoder;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import javax.xml.stream.XMLInputFactory;
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.XMLStreamReader;
+
+import org.apache.log4j.Logger;
+
+import gate.mimir.Constraint;
+import gate.mimir.ConstraintType;
+import gate.mimir.SemanticAnnotationHelper;
+import gate.mimir.index.Indexer;
+import gate.mimir.index.Mention;
+import gate.mimir.search.QueryEngine;
+import gate.mimir.util.DelegatingSemanticAnnotationHelper;
+import gate.util.GateRuntimeException;
+
+/**
+ * A Semantic annotation helper that, at query time, connects to a SPARQL
+ * endpoint to obtain a list of candidate URIs that are then passed to the
+ * underlying delegate annotation helper.
+ */
+public class SPARQLSemanticAnnotationHelper extends
+                                           DelegatingSemanticAnnotationHelper {
+  private static final Logger logger = Logger
+      .getLogger(SPARQLSemanticAnnotationHelper.class);
+
+  /**
+   * The name used for the synthetic feature used at query time to supply the
+   * SPARQL query.
+   */
+  public static final String SPARQL_QUERY_FEATURE_NAME = "sparql";
+
+  /**
+   * The service endpoint where SPARQL queries are forwarded to.
+   */
+  private String sparqlEndpoint;
+
+  public SPARQLSemanticAnnotationHelper(String annotationType,
+      String sparqlEndpoint, String[] nominalFeatureNames,
+      String[] integerFeatureNames, String[] floatFeatureNames,
+      String[] textFeatureNames, String[] uriFeatureNames,
+      SemanticAnnotationHelper delegate) {
+    super(annotationType, nominalFeatureNames, integerFeatureNames,
+        floatFeatureNames, textFeatureNames, uriFeatureNames, delegate);
+    this.sparqlEndpoint = sparqlEndpoint;
+  }
+
+  @Override
+  public void init(QueryEngine queryEngine) {
+    super.init(queryEngine);
+  }
+
+  @Override
+  public List<Mention> getMentions(String annotationType,
+      List<Constraint> constraints, QueryEngine engine) {
+    // Accumulate the mentions in a set, so that we remove duplicates.
+    Set<Mention> mentions = new HashSet<Mention>();
+    List<Constraint> passThroughConstraints = new ArrayList<Constraint>();
+    String query = null;
+    for(Constraint aConstraint : constraints) {
+      if(aConstraint.getFeatureName() == SPARQL_QUERY_FEATURE_NAME) {
+        query = (String)aConstraint.getValue();
+      } else {
+        passThroughConstraints.add(aConstraint);
+      }
+    }
+    if(query == null) {
+      // no SPARQL constraints in this query
+      return delegate.getMentions(annotationType, constraints, engine);
+    } else {
+      // run the query on the SPARQL endpoint
+      try {
+        SPARQLResultSet srs = runQuery(query);
+        // convert each result row into a query for the delegate
+        for(String[] aRow : srs.getRows()) {
+          List<Constraint> delegateConstraints =
+              new ArrayList<Constraint>(passThroughConstraints);
+          for(int i = 0; i < srs.getColumnNames().length; i++) {
+            delegateConstraints.add(new Constraint(ConstraintType.EQ, srs
+                .getColumnNames()[i], aRow[i]));
+          }
+          mentions.addAll(delegate.getMentions(annotationType, 
+              delegateConstraints, engine));
+        }
+      } catch(IOException e) {
+        logger.error(
+            "I/O error while communicating with " + "SPARQL endpoint.", e);
+        throw new GateRuntimeException("I/O error while communicating with "
+            + "SPARQL endpoint.", e);
+      } catch(XMLStreamException e) {
+        logger.error("Error parsing results from SPARQL endpoint.", e);
+        throw new GateRuntimeException("Error parsing results from SPARQL "
+            + "endpoint.", e);
+      }
+      return new ArrayList<Mention>(mentions);
+    }
+  }
+
+  /**
+   * Runs a query against the SPARQL endpoint and returns the results.
+   * 
+   * @param query
+   * @return
+   * @throws XMLStreamException
+   */
+  protected SPARQLResultSet runQuery(String query) throws IOException,
+      XMLStreamException {
+    try {
+      String urlStr =
+          sparqlEndpoint + "?query=" + URLEncoder.encode(query, "UTF-8");
+      URL url = new URL(urlStr);
+      InputStream is = url.openStream();
+      return new SPARQLResultSet(is);
+    } catch(UnsupportedEncodingException e) {
+      // like that's gonna happen...
+      throw new RuntimeException("UTF-8 encoding not supported by this JVM");
+    } catch(MalformedURLException e) {
+      // this may actually happen
+      throw new RuntimeException("Invalid URL - have you set the correct "
+          + "SPARQL endpoint?", e);
+    }
+  }
+}


Property changes on: 
mimir/trunk/plugins/sparql/src/gate/mimir/sparql/SPARQLSemanticAnnotationHelper.java
___________________________________________________________________
Added: svn:keywords
   + Id
Added: svn:eol-style
   + native


This was sent by the SourceForge.net collaborative development platform, the 
world's largest Open Source development site.

------------------------------------------------------------------------------
Benefiting from Server Virtualization: Beyond Initial Workload 
Consolidation -- Increasing the use of server virtualization is a top
priority.Virtualization can reduce costs, simplify management, and improve 
application availability and disaster protection. Learn more about boosting 
the value of server virtualization. http://p.sf.net/sfu/vmware-sfdev2dev
_______________________________________________
GATE-cvs mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/gate-cvs

Reply via email to