~ the service now formats the results as xml (but the contenttype is wrong)
authorAlexandre Bertails <alexandre@bertails.org>
Sat, 12 Jun 2010 17:20:51 -0400
changeset 207 c23b9fd839cd
parent 205 745da618b07c
child 208 b4daf7d3d232
~ the service now formats the results as xml (but the contenttype is wrong)
src/main/scala/Servlet.scala
src/main/webapp/WEB-INF/web.xml
--- a/src/main/scala/Servlet.scala	Sat Jun 12 09:37:34 2010 -0400
+++ b/src/main/scala/Servlet.scala	Sat Jun 12 17:20:51 2010 -0400
@@ -1,15 +1,18 @@
-package org.w3.calendar
+package org.w3.sparql2sql.servlet
 
 import javax.servlet.http.{HttpServlet, HttpServletRequest, HttpServletResponse} 
 import scala.xml.XML
 
-import java.sql.{DriverManager, Connection, Statement, ResultSet}
+import java.sql.{DriverManager, Connection, Statement, ResultSet, ResultSetMetaData}
+
+import java.sql.{Types => T}
 
 import java.net.URI
 import w3c.sw.sql.{Sql,DatabaseDesc,Relation,RelationDesc,Attribute,Value,Datatype,ForeignKey,Name}
+import w3c.sw.sparql
 import w3c.sw.sparql.Sparql
 import w3c.sw.sql
-import w3c.sw.sparql2sql.{SparqlToSql,StemURI}
+import w3c.sw.sparql2sql.{SparqlToSql,StemURI,SqlToXMLRes}
 
 object Config {
 
@@ -41,10 +44,22 @@
   val db:DatabaseDesc = DDLParser.parseAll(DDLParser.ddl, dbDdl).get
 
   val defaultSparqlQuery = """PREFIX empP : <http://hr.example/DB/Employee#>
+PREFIX task : <http://hr.example/DB/Tasks#>
+PREFIX tass : <http://hr.example/DB/TaskAssignments#>
 PREFIX xsd : <http://www.w3.org/2001/XMLSchema#>
-SELECT ?emp {
-?emp  empP:manager    "18"^^xsd:integer
-}
+SELECT ?name ?bday
+ WHERE { { ?above   tass:employee  ?who .
+           ?above   tass:task      ?atask .
+           ?atask   task:lead      ?taskLead .
+           ?taskLead empP:lastName  ?name }
+         UNION
+         { ?below   tass:task     ?btask .
+           ?btask   task:lead     ?who .
+           ?below   tass:employee ?managed .
+           ?managed empP:lastName  ?name .
+           ?managed empP:birthday  ?bday } 
+         ?who empP:lastName "Smith"^^xsd:string .
+         ?who empP:birthday ?bday }
 """
 
   val defaultStemURI = "http://hr.example/DB/"
@@ -83,6 +98,50 @@
         process(results)
       }
     }
+
+  def process(connection: Connection, sql: String,
+              head: List[String] => String,
+              startres: String,
+          binding: (String, String /*, Map[sparql.Assignable, SparqlToSql.SQL2RDFValueMapper], StemURI*/) => String,
+          endres: String, foot: String): String = {
+
+    query(connection, sql) { results =>
+
+      val metadata = results.getMetaData
+
+      val vars:List[String] =
+        (1 to metadata.getColumnCount) map { column => metadata.getColumnLabel(column) } toList
+
+      def processCell(rs:ResultSet, column:Int):Option[String] =
+	try {
+          val name:String = metadata.getColumnLabel(column)
+          val value:String =
+	    metadata.getColumnType(column) match {
+              case T.VARCHAR => rs.getString(column)
+              case T.INTEGER => rs.getInt(column).toString
+              case T.DATE    => rs.getDate(column).toString
+              case _         => throw new java.lang.Exception("you have to map this type!!!")
+            }
+          Some(binding(name, value))
+	} catch {
+	  case _ => None
+	}
+
+      def processRow(rs:ResultSet):String =
+        (1 to metadata.getColumnCount) flatMap { column => processCell(rs, column) } mkString ""
+
+      val rows:List[String] = bmap(results.next) {
+        processRow(results)
+      }
+
+      val body = rows map { startres + _ + endres } mkString ""
+
+      head(vars) + body + foot
+
+    }
+
+  }
+
 }
 
 
@@ -107,33 +166,24 @@
 
     val sparqlSelect = sparqlParser.parseAll(sparqlParser.select, query).get
 
-    val generated:sql.Select = SparqlToSql(Config.db, sparqlSelect, stemURI, true, false)._1
+    val (generated, rdfmap) = SparqlToSql(Config.db, sparqlSelect, stemURI, true, false)
 
     Class.forName("com.mysql.jdbc.Driver").newInstance
     val connection:Connection = DriverManager.getConnection("jdbc:mysql://localhost/rdb2rdf", "root", "")
-    if (! connection.isClosed) println("Successfully connected")
-
-    import java.sql.{Types => T}
 
-    def f(rs:ResultSet):List[String] = {
-      val metadata = rs.getMetaData
-      val l = for(i <- 1 to metadata.getColumnCount) yield {
-	val t = metadata.getColumnType(i)
-	t match {
-	  case T.VARCHAR => "<VARCHAR:" + rs.getString(i) + ">"
-	  case T.INTEGER => "<INTEGER:" + rs.getInt(i) + ">"
-	  case T.DATE    => "<DATE:" + rs.getDate(i) + ">"
-	  case _         => "<NONMAPPED>"
-	}
-      }
-      l.toList
-    }
+//    if (! connection.isClosed) println("Successfully connected")
 
-    val rows = Control.queryEach(connection, generated.toString) { rs => f(rs) mkString " " }
-    
+    val res = Control.process(connection=connection,
+			      sql=generated.toString,
+			      head=SqlToXMLRes.head(_),
+			      startres=SqlToXMLRes.startresult,
+			      binding=SqlToXMLRes.binding(_, _, rdfmap, stemURI),
+			      endres=SqlToXMLRes.endresult,
+			      foot=SqlToXMLRes.foot)
+
     response.setContentType("text/plain; charset='" + encoding + "'")
 
-    response.getWriter.write(rows mkString "\n")
+    response.getWriter.write(res)
 
   }
 
@@ -142,20 +192,20 @@
     val index =
       <html xmlns="http://www.w3.org/1999/xhtml">
         <head><title>RDB2RDF Sparql endpoint</title></head>
-	<body>
-	  <h1>RDB2RDF Sparql endpoint</h1>
-	  <form action="sparql">
+        <body>
+          <h1>RDB2RDF Sparql endpoint</h1>
+          <form action="sparql">
             <p>
               StemURI: <input cols="80" name="stemuri" id="stemuri" value={ Config.defaultStemURI } /><br />
               <textarea rows="10" cols="80" name="query" id="query">{ Config.defaultSparqlQuery }</textarea>
-	      <input type="submit" />
+              <input type="submit" />
             </p>
-	  </form>
-	  <hr />
-	  <address>
-	    <a href="http://www.w3.org/People/Eric/">Eric Prud'hommeaux</a>, <a href="http://www.w3.org/People/Bertails/">Alexandre Bertails</a>, Jun 2010
-	  </address>
-	</body>
+          </form>
+          <hr />
+          <address>
+            <a href="http://www.w3.org/People/Eric/">Eric Prud'hommeaux</a>, <a href="http://www.w3.org/People/Bertails/">Alexandre Bertails</a>, Jun 2010
+          </address>
+        </body>
       </html>
 
     response.setContentType("application/xml; charset='" + encoding + "'")
--- a/src/main/webapp/WEB-INF/web.xml	Sat Jun 12 09:37:34 2010 -0400
+++ b/src/main/webapp/WEB-INF/web.xml	Sat Jun 12 17:20:51 2010 -0400
@@ -1,7 +1,7 @@
 <web-app xmlns="http://java.sun.com/xml/ns/javaee" version="2.5">
   <servlet>
     <servlet-name>sparqlendpoint</servlet-name>
-    <servlet-class>org.w3.calendar.SparqlEndpoint</servlet-class>
+    <servlet-class>org.w3.sparql2sql.servlet.SparqlEndpoint</servlet-class>
   </servlet>
   <servlet-mapping>
     <servlet-name>sparqlendpoint</servlet-name>