You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@marmotta.apache.org by wi...@apache.org on 2013/04/05 18:33:18 UTC

[1/6] git commit: refacotring SparqlWebService to distinct possible content types to return per query type

Updated Branches:
  refs/heads/master ed9268155 -> 468e810e0


refacotring SparqlWebService to distinct possible content types to return per query type


Project: http://git-wip-us.apache.org/repos/asf/incubator-marmotta/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-marmotta/commit/1ceb90a5
Tree: http://git-wip-us.apache.org/repos/asf/incubator-marmotta/tree/1ceb90a5
Diff: http://git-wip-us.apache.org/repos/asf/incubator-marmotta/diff/1ceb90a5

Branch: refs/heads/master
Commit: 1ceb90a53fc4593a8e39e120abc9e85175dbf257
Parents: ed92681
Author: Sergio Fernández <wi...@apache.org>
Authored: Fri Apr 5 12:50:22 2013 +0200
Committer: Sergio Fernández <wi...@apache.org>
Committed: Fri Apr 5 12:50:22 2013 +0200

----------------------------------------------------------------------
 .../platform/sparql/api/sparql/SparqlService.java  |  100 ++++++-
 .../sparql/services/sparql/SparqlServiceImpl.java  |  107 +++++--
 .../services/sparql/SparqlWritersHelper.java       |  116 +++++++
 .../sparql/webservices/SparqlWebService.java       |  242 ++++++---------
 4 files changed, 393 insertions(+), 172 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-marmotta/blob/1ceb90a5/platform/marmotta-sparql/src/main/java/org/apache/marmotta/platform/sparql/api/sparql/SparqlService.java
----------------------------------------------------------------------
diff --git a/platform/marmotta-sparql/src/main/java/org/apache/marmotta/platform/sparql/api/sparql/SparqlService.java b/platform/marmotta-sparql/src/main/java/org/apache/marmotta/platform/sparql/api/sparql/SparqlService.java
index 373ab87..4fc372d 100644
--- a/platform/marmotta-sparql/src/main/java/org/apache/marmotta/platform/sparql/api/sparql/SparqlService.java
+++ b/platform/marmotta-sparql/src/main/java/org/apache/marmotta/platform/sparql/api/sparql/SparqlService.java
@@ -21,13 +21,19 @@ import org.apache.marmotta.platform.core.exception.MarmottaException;
 import org.apache.marmotta.platform.sparql.services.sparqlio.rdf.SPARQLGraphResultWriter;
 import org.apache.marmotta.platform.core.exception.InvalidArgumentException;
 import org.openrdf.model.Value;
+import org.openrdf.query.BooleanQuery;
+import org.openrdf.query.GraphQuery;
 import org.openrdf.query.MalformedQueryException;
+import org.openrdf.query.Query;
 import org.openrdf.query.QueryEvaluationException;
 import org.openrdf.query.QueryLanguage;
+import org.openrdf.query.TupleQuery;
 import org.openrdf.query.UpdateExecutionException;
 import org.openrdf.query.resultio.BooleanQueryResultWriter;
 import org.openrdf.query.resultio.TupleQueryResultWriter;
+import org.openrdf.repository.RepositoryException;
 
+import java.io.OutputStream;
 import java.util.List;
 import java.util.Map;
 
@@ -37,10 +43,21 @@ import java.util.Map;
  * User: sschaffe
  */
 public interface SparqlService {
+	
+	/**
+	 * Parse query 
+	 * 
+	 * @param language language 
+	 * @param query query
+	 * @return query parsed
+	 * @throws RepositoryException
+	 * @throws MalformedQueryException
+	 */
+	Query parseQuery(QueryLanguage language, String query) throws RepositoryException, MalformedQueryException ;
 
     /**
      * Evaluate a SPARQL query on the KiWi TripleStore. Writes the query results 
-     * to the output stream passed as argument os in the output format specified 
+     * to the output stream passed as argument on in the output format specified 
      * as argument outputFormat.
      *
      * see http://www.w3.org/TR/sparql11-query/
@@ -54,8 +71,79 @@ public interface SparqlService {
      * @throws InvalidArgumentException if the output format or query language are undefined
      * @throws org.apache.marmotta.platform.core.exception.MarmottaException if the query evaluation fails
      */
-	public void query(QueryLanguage queryLanguage, String query, TupleQueryResultWriter tupleWriter, BooleanQueryResultWriter booleanWriter, SPARQLGraphResultWriter graphWriter) throws InvalidArgumentException, MarmottaException, MalformedQueryException, QueryEvaluationException;
+	void query(QueryLanguage queryLanguage, String query, TupleQueryResultWriter tupleWriter, BooleanQueryResultWriter booleanWriter, SPARQLGraphResultWriter graphWriter) throws InvalidArgumentException, MarmottaException, MalformedQueryException, QueryEvaluationException;
 
+	/**
+	 * Evaluate a SPARQL query on the KiWi TripleStore. Writes the query results 
+     * to the stream passed in the format requested.
+     * 
+	 * @param query
+	 * @param output
+	 * @param format
+	 * @throws QueryEvaluationException
+	 */
+	void query(Query query, OutputStream output, String format) throws QueryEvaluationException;
+	
+	/**
+	 * Evaluate a SPARQL tuple query on the KiWi TripleStore. Writes the query results 
+     * to the writer passed.
+	 * 
+	 * @param tuple query
+	 * @param writer the writer to use to write results
+	 * @throws QueryEvaluationException
+	 */
+    void query(TupleQuery query, TupleQueryResultWriter writer) throws QueryEvaluationException;
+    
+    /**
+     * Evaluate a SPARQL tuple query on the KiWi TripleStore. Writes the query results 
+     * to the stream passed in the format requested.
+     * 
+     * @param query
+     * @param output
+     * @param format
+     */
+    void query(TupleQuery query, OutputStream output, String format) throws QueryEvaluationException;
+    
+    /**
+     * Evaluate a SPARQL boolean query on the KiWi TripleStore. Writes the query results 
+     * to the writer passed.
+     * 
+     * @param query boolean query
+     * @param writer the writer to use to write results
+     * @throws QueryEvaluationException
+     */
+    void query(BooleanQuery query, BooleanQueryResultWriter writer) throws QueryEvaluationException;
+    
+    /**
+     * Evaluate a SPARQL boolean query on the KiWi TripleStore. Writes the query results 
+     * to the stream passed in the format requested.
+     * 
+     * @param query
+     * @param output
+     * @param format
+     */
+    void query(BooleanQuery query, OutputStream output, String format) throws QueryEvaluationException;    
+    
+    /**
+     * Evaluate a SPARQL graph query on the KiWi TripleStore. Writes the query results 
+     * to the writer passed.
+     * 
+     * @param query graph query
+     * @param writer the writer to use to write results
+     * @throws QueryEvaluationException
+     */
+    void query(GraphQuery query, SPARQLGraphResultWriter writer) throws QueryEvaluationException;
+    
+    /**
+     * Evaluate a SPARQL graph query on the KiWi TripleStore. Writes the query results 
+     * to the stream passed in the format requested.
+     * 
+     * @param query
+     * @param output
+     * @param format
+     */
+    void query(GraphQuery query, OutputStream output, String format) throws QueryEvaluationException;    
+	
     /**
      * Evaluate a SPARQL ASK query on the KiWi TripleStore
      *
@@ -66,10 +154,10 @@ public interface SparqlService {
      * @param query         the SPARQL query to evaluate in SPARQL 1.1 syntax
      * @throws org.apache.marmotta.platform.core.exception.MarmottaException if the query evaluation fails
      */
-	public boolean ask(QueryLanguage queryLanguage, String query) throws MarmottaException;
+	boolean ask(QueryLanguage queryLanguage, String query) throws MarmottaException;
 
     /**
-     * Evaluate a SPARQL query on the LMF TripleStore. Returns the results as a list of result maps, each element
+     * Evaluate a SPARQL query on the KiWi TripleStore. Returns the results as a list of result maps, each element
      * a KiWiNode.
      *
      * see http://www.w3.org/TR/sparql11-query/
@@ -80,7 +168,7 @@ public interface SparqlService {
     public List<Map<String,Value>> query(QueryLanguage queryLanguage, String query) throws MarmottaException;
 
     /**
-     * Execute a SPARQL update on the LMF TripleStore. Throws a KiWiException in case the update execution fails.
+     * Execute a SPARQL update on the KiWi TripleStore. Throws a KiWiException in case the update execution fails.
      *
      * see http://www.w3.org/TR/sparql11-update/
      *
@@ -88,6 +176,6 @@ public interface SparqlService {
      * @param query  a string representing the update query in SPARQL Update 1.1 syntax
      * @throws Exception
      */
-    public void update(QueryLanguage queryLanguage, String query) throws InvalidArgumentException, MarmottaException, MalformedQueryException, UpdateExecutionException;
+    void update(QueryLanguage queryLanguage, String query) throws InvalidArgumentException, MarmottaException, MalformedQueryException, UpdateExecutionException;
 
 }

http://git-wip-us.apache.org/repos/asf/incubator-marmotta/blob/1ceb90a5/platform/marmotta-sparql/src/main/java/org/apache/marmotta/platform/sparql/services/sparql/SparqlServiceImpl.java
----------------------------------------------------------------------
diff --git a/platform/marmotta-sparql/src/main/java/org/apache/marmotta/platform/sparql/services/sparql/SparqlServiceImpl.java b/platform/marmotta-sparql/src/main/java/org/apache/marmotta/platform/sparql/services/sparql/SparqlServiceImpl.java
index c20d7f1..bfefd4d 100644
--- a/platform/marmotta-sparql/src/main/java/org/apache/marmotta/platform/sparql/services/sparql/SparqlServiceImpl.java
+++ b/platform/marmotta-sparql/src/main/java/org/apache/marmotta/platform/sparql/services/sparql/SparqlServiceImpl.java
@@ -18,6 +18,7 @@
 package org.apache.marmotta.platform.sparql.services.sparql;
 
 import java.io.IOException;
+import java.io.OutputStream;
 import java.util.HashMap;
 import java.util.LinkedList;
 import java.util.List;
@@ -26,7 +27,6 @@ import java.util.Map;
 import javax.enterprise.context.ApplicationScoped;
 import javax.inject.Inject;
 
-import org.apache.marmotta.kiwi.model.rdf.KiWiNode;
 import org.apache.marmotta.platform.core.api.config.ConfigurationService;
 import org.apache.marmotta.platform.core.api.triplestore.SesameService;
 import org.apache.marmotta.platform.core.exception.InvalidArgumentException;
@@ -53,11 +53,11 @@ import org.openrdf.repository.RepositoryConnection;
 import org.openrdf.repository.RepositoryException;
 import org.slf4j.Logger;
 
-
 /**
  * Sparql Service implementation
  *
- * @author sschaffe
+ * @author Sebastian Schaffert
+ * @author Sergio Fernández
  */
 @ApplicationScoped
 public class SparqlServiceImpl implements SparqlService {
@@ -73,6 +73,20 @@ public class SparqlServiceImpl implements SparqlService {
 
     @Inject
     private SesameService sesameService;
+    
+    @Override
+    public Query parseQuery(QueryLanguage language, String query) throws RepositoryException, MalformedQueryException {
+    	Query sparqlQuery = null;
+        RepositoryConnection connection = sesameService.getConnection();
+        try {
+            connection.begin();
+            sparqlQuery = connection.prepareQuery(language, query);
+            connection.commit();
+        } finally {
+            connection.close();
+        }
+        return sparqlQuery;
+    }
 
     @Override
     public void query(QueryLanguage queryLanguage, String query, TupleQueryResultWriter tupleWriter, BooleanQueryResultWriter booleanWriter, SPARQLGraphResultWriter graphWriter) throws MarmottaException, MalformedQueryException, QueryEvaluationException {
@@ -87,14 +101,11 @@ public class SparqlServiceImpl implements SparqlService {
                 Query sparqlQuery = connection.prepareQuery(queryLanguage, query);
 
                 if (sparqlQuery instanceof TupleQuery) {
-                    TupleQuery tupleQuery = (TupleQuery) sparqlQuery;
-                    tupleQuery.evaluate(tupleWriter);
+                    query((TupleQuery) sparqlQuery, tupleWriter);
                 } else if (sparqlQuery instanceof BooleanQuery) {
-                    BooleanQuery booleanQuery = (BooleanQuery) sparqlQuery;
-                    booleanWriter.write(booleanQuery.evaluate());
+                    query((BooleanQuery) sparqlQuery, booleanWriter);
                 } else if (sparqlQuery instanceof GraphQuery) {
-                    GraphQuery graphQuery = (GraphQuery) sparqlQuery;
-                    graphWriter.write(graphQuery.evaluate());
+                    query((GraphQuery) sparqlQuery, graphWriter);
                 } else {
                     connection.rollback();
                     throw new InvalidArgumentException("SPARQL query type " + sparqlQuery.getClass() + " not supported!");
@@ -104,26 +115,72 @@ public class SparqlServiceImpl implements SparqlService {
             } finally {
                 connection.close();
             }
-        } catch(RepositoryException ex) {
-            log.error("error while getting repository connection");
-            throw new MarmottaException("error while getting repository connection",ex);
-        } catch (TupleQueryResultHandlerException e) {
-            throw new MarmottaException("error while writing query result in format ",e);
-        } catch (IOException e) {
-            throw new MarmottaException("error while writing query result in format ",e);
+        } catch(RepositoryException e) {
+            log.error("error while getting repository connection: {}", e);
+            throw new MarmottaException("error while getting repository connection", e);
+        } catch (QueryEvaluationException e) {
+        	log.error("error while evaluating query: {}", e);
+            throw new MarmottaException("error while writing query result in format ", e);
         }
 
-        log.debug("SPARQL execution took {}ms",System.currentTimeMillis()-start);
+        log.debug("SPARQL execution took {}ms", System.currentTimeMillis()-start);
+    }
+    
+    @Override
+    public void query(Query query, OutputStream output, String format) throws QueryEvaluationException {
+        if (query instanceof TupleQuery) {
+        	query((TupleQuery)query, output, format);
+        } else if (query instanceof BooleanQuery) {
+        	query((BooleanQuery)query, output, format);
+        } else if (query instanceof GraphQuery) {
+        	query((GraphQuery)query, output, format);
+        } else {
+            throw new InvalidArgumentException("SPARQL query type " + query.getClass() + " not supported!");
+        }
     }
 
-//    private static Pattern subTypePattern = Pattern.compile("[a-z]+/([a-z0-9-._]+\\+)?([a-z0-9-._]+)(;.*)?");
-//    private String parseSubType(String mimeType) {
-//        Matcher matcher = subTypePattern.matcher(mimeType);
-//        if(matcher.matches()) return matcher.group(2);
-//        else
-//            return mimeType;
-//    }
-
+    @Override
+    public void query(TupleQuery query, TupleQueryResultWriter writer) throws QueryEvaluationException {
+    	try {
+			query.evaluate(writer);
+		} catch (TupleQueryResultHandlerException e) {
+			throw new QueryEvaluationException("error while writing query tuple result: ",e);
+		}
+    }
+    
+    @Override
+    public void query(TupleQuery query, OutputStream output, String format) throws QueryEvaluationException {
+    	query(query, SparqlWritersHelper.getTupleResultWriter(format, output));
+    }
+    
+    @Override
+    public void query(BooleanQuery query, BooleanQueryResultWriter writer) throws QueryEvaluationException {
+    	try {
+			writer.write(query.evaluate());
+		} catch (IOException e) {
+			throw new QueryEvaluationException("error while writing query boolean result: ",e);
+		}
+    }
+    
+    @Override
+    public void query(BooleanQuery query, OutputStream output, String format) throws QueryEvaluationException {
+    	query(query, SparqlWritersHelper.getBooleanResultWriter(format, output));
+    }
+    
+    @Override
+    public void query(GraphQuery query, SPARQLGraphResultWriter writer) throws QueryEvaluationException {
+    	try {
+			writer.write(query.evaluate());
+		} catch (IOException e) {
+			throw new QueryEvaluationException("error while writing query graph result: ",e);
+		}
+    }
+    
+    @Override
+    public void query(GraphQuery query, OutputStream output, String format) throws QueryEvaluationException {
+    	query(query, SparqlWritersHelper.getGraphResultWriter(format, output));
+    }
+    
     /**
      * Evaluate a SPARQL query on the LMF TripleStore. Returns the results as a list of result maps, each element
      * a KiWiNode.

http://git-wip-us.apache.org/repos/asf/incubator-marmotta/blob/1ceb90a5/platform/marmotta-sparql/src/main/java/org/apache/marmotta/platform/sparql/services/sparql/SparqlWritersHelper.java
----------------------------------------------------------------------
diff --git a/platform/marmotta-sparql/src/main/java/org/apache/marmotta/platform/sparql/services/sparql/SparqlWritersHelper.java b/platform/marmotta-sparql/src/main/java/org/apache/marmotta/platform/sparql/services/sparql/SparqlWritersHelper.java
new file mode 100644
index 0000000..f827c57
--- /dev/null
+++ b/platform/marmotta-sparql/src/main/java/org/apache/marmotta/platform/sparql/services/sparql/SparqlWritersHelper.java
@@ -0,0 +1,116 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.marmotta.platform.sparql.services.sparql;
+
+import java.io.OutputStream;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.apache.commons.lang.StringUtils;
+import org.apache.marmotta.platform.core.exception.InvalidArgumentException;
+import org.apache.marmotta.platform.sparql.services.sparqlio.rdf.SPARQLGraphResultWriter;
+import org.apache.marmotta.platform.sparql.services.sparqlio.sparqlhtml.SPARQLBooleanHTMLWriter;
+import org.apache.marmotta.platform.sparql.services.sparqlio.sparqlhtml.SPARQLResultsHTMLWriter;
+import org.apache.marmotta.platform.sparql.services.sparqlio.sparqljson.SPARQLBooleanJSONWriter;
+import org.apache.marmotta.platform.sparql.services.sparqlio.sparqljson.SPARQLResultsJSONWriter;
+import org.openrdf.query.resultio.BooleanQueryResultWriter;
+import org.openrdf.query.resultio.TupleQueryResultWriter;
+import org.openrdf.query.resultio.sparqlxml.SPARQLBooleanXMLWriter;
+import org.openrdf.query.resultio.sparqlxml.SPARQLResultsXMLWriter;
+import org.openrdf.query.resultio.text.BooleanTextWriter;
+import org.openrdf.query.resultio.text.csv.SPARQLResultsCSVWriter;
+
+/**
+ * Helper for working with SPARQL Writers
+ * 
+ * @author Sergio Fernández
+ *
+ */
+public class SparqlWritersHelper {
+	
+    public static TupleQueryResultWriter getTupleResultWriter(String format, OutputStream os) {
+        //build outputwriter
+        final TupleQueryResultWriter out;
+        if(format == null) {
+            out = new SPARQLResultsXMLWriter(os);
+        } else if(parseSubType(format).equals("html")) {
+            out = new SPARQLResultsHTMLWriter(os);
+        } else if(parseSubType(format).equals("json")) {
+            out = new SPARQLResultsJSONWriter(os);
+        } else if(parseSubType(format).equals("xml")) {
+            out = new SPARQLResultsXMLWriter(os);
+        } else if(parseSubType(format).equals("csv")) {
+            out = new SPARQLResultsCSVWriter(os);
+        } else throw new InvalidArgumentException("could not produce format "+format);
+        return out;
+    }
+
+    public static BooleanQueryResultWriter getBooleanResultWriter(String format, OutputStream os) {
+        //build outputwriter
+        final BooleanQueryResultWriter out;
+        if(format == null) {
+            out = new SPARQLBooleanXMLWriter(os);
+        } else if(parseSubType(format).equals("html")) {
+            out = new SPARQLBooleanHTMLWriter(os);
+        } else if(parseSubType(format).equals("json")) {
+            out = new SPARQLBooleanJSONWriter(os);
+        } else if(parseSubType(format).equals("xml")) {
+            out = new SPARQLBooleanXMLWriter(os);
+        } else if(parseSubType(format).equals("csv")) {
+            out = new BooleanTextWriter(os);
+        } else throw new InvalidArgumentException("could not produce format "+format);
+        return out;
+    }
+
+    public static SPARQLGraphResultWriter getGraphResultWriter(String format, OutputStream os) {
+        return new SPARQLGraphResultWriter(os,format);
+    }
+    
+    //TODO: move this to another place
+    
+    public static Pattern subTypePattern = Pattern.compile("[a-z]+/([a-z0-9-._]+\\+)?([a-z0-9-._]+)(;.*)?");
+    
+    public static String parseSubType(String mimeType) {
+        Matcher matcher = subTypePattern.matcher(mimeType);
+        if (matcher.matches())
+            return matcher.group(2);
+        else
+            return mimeType;
+    }
+    
+    public static String buildSparqlContentType(String resultType) {
+        if(StringUtils.isBlank(resultType)) {
+            return "application/sparql-results+xml;charset=utf-8";
+        } else if(parseSubType(resultType).equals("html") ) {
+        	return "text/html;charset=utf-8";
+        } else if(parseSubType(resultType).equals("json") ) {
+        	return "application/sparql-results+json;charset=utf-8";
+        } else if(parseSubType(resultType).equals("rdf+xml") ) {
+        	return "application/rdf+xml;charset=utf-8";
+        } else if(parseSubType(resultType).equals("rdf+n3") ) {
+        	return "text/rdf+n3;charset=utf-8";
+        } else if(parseSubType(resultType).equals("n3") ) {
+        	return "text/rdf+n3;charset=utf-8";
+        } else if(parseSubType(resultType).equals("csv") ) {
+        	return "text/csv;charset=utf-8";
+        } else {
+        	return "application/sparql-results+xml;charset=utf-8";
+        }
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-marmotta/blob/1ceb90a5/platform/marmotta-sparql/src/main/java/org/apache/marmotta/platform/sparql/webservices/SparqlWebService.java
----------------------------------------------------------------------
diff --git a/platform/marmotta-sparql/src/main/java/org/apache/marmotta/platform/sparql/webservices/SparqlWebService.java b/platform/marmotta-sparql/src/main/java/org/apache/marmotta/platform/sparql/webservices/SparqlWebService.java
index f15f6df..58a1ee7 100644
--- a/platform/marmotta-sparql/src/main/java/org/apache/marmotta/platform/sparql/webservices/SparqlWebService.java
+++ b/platform/marmotta-sparql/src/main/java/org/apache/marmotta/platform/sparql/webservices/SparqlWebService.java
@@ -17,56 +17,60 @@
  */
 package org.apache.marmotta.platform.sparql.webservices;
 
-import org.apache.marmotta.platform.core.exception.MarmottaException;
-import org.apache.marmotta.platform.sparql.api.sparql.SparqlService;
-import org.apache.marmotta.platform.sparql.services.sparqlio.rdf.SPARQLGraphResultWriter;
-import org.apache.marmotta.platform.sparql.services.sparqlio.sparqlhtml.SPARQLBooleanHTMLWriter;
-import org.apache.marmotta.platform.sparql.services.sparqlio.sparqlhtml.SPARQLResultsHTMLWriter;
-import org.apache.marmotta.platform.sparql.services.sparqlio.sparqljson.SPARQLBooleanJSONWriter;
-import org.apache.marmotta.platform.sparql.services.sparqlio.sparqljson.SPARQLResultsJSONWriter;
-import com.google.common.collect.Lists;
-import com.google.common.io.CharStreams;
-import org.apache.marmotta.platform.core.api.config.ConfigurationService;
-import org.apache.marmotta.platform.core.exception.InvalidArgumentException;
-import org.apache.marmotta.platform.core.util.WebServiceUtil;
-import org.apache.commons.lang.StringUtils;
-import org.apache.marmotta.commons.http.ContentType;
-import org.apache.marmotta.commons.http.LMFHttpUtils;
-import org.openrdf.query.MalformedQueryException;
-import org.openrdf.query.QueryEvaluationException;
-import org.openrdf.query.QueryLanguage;
-import org.openrdf.query.UpdateExecutionException;
-import org.openrdf.query.resultio.BooleanQueryResultWriter;
-import org.openrdf.query.resultio.TupleQueryResultWriter;
-import org.openrdf.query.resultio.sparqlxml.SPARQLBooleanXMLWriter;
-import org.openrdf.query.resultio.sparqlxml.SPARQLResultsXMLWriter;
-import org.openrdf.query.resultio.text.BooleanTextWriter;
-import org.openrdf.query.resultio.text.csv.SPARQLResultsCSVWriter;
-import org.slf4j.Logger;
-
-import javax.enterprise.context.ApplicationScoped;
-import javax.inject.Inject;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.*;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.StreamingOutput;
-import javax.ws.rs.core.UriBuilder;
-
 import java.io.IOException;
 import java.io.OutputStream;
 import java.io.UnsupportedEncodingException;
 import java.net.URI;
 import java.net.URISyntaxException;
 import java.net.URLDecoder;
+import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
+
+import javax.enterprise.context.ApplicationScoped;
+import javax.inject.Inject;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.Consumes;
+import javax.ws.rs.FormParam;
+import javax.ws.rs.GET;
+import javax.ws.rs.HeaderParam;
+import javax.ws.rs.OPTIONS;
+import javax.ws.rs.POST;
+import javax.ws.rs.Path;
+import javax.ws.rs.QueryParam;
+import javax.ws.rs.WebApplicationException;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.Response.Status;
+import javax.ws.rs.core.StreamingOutput;
+import javax.ws.rs.core.UriBuilder;
+
+import org.apache.commons.lang.StringUtils;
+import org.apache.marmotta.commons.http.ContentType;
+import org.apache.marmotta.commons.http.LMFHttpUtils;
+import org.apache.marmotta.platform.core.api.config.ConfigurationService;
+import org.apache.marmotta.platform.core.exception.InvalidArgumentException;
+import org.apache.marmotta.platform.core.exception.MarmottaException;
+import org.apache.marmotta.platform.core.util.WebServiceUtil;
+import org.apache.marmotta.platform.sparql.api.sparql.SparqlService;
+import org.apache.marmotta.platform.sparql.services.sparql.SparqlWritersHelper;
+import org.openrdf.query.BooleanQuery;
+import org.openrdf.query.GraphQuery;
+import org.openrdf.query.MalformedQueryException;
+import org.openrdf.query.Query;
+import org.openrdf.query.QueryEvaluationException;
+import org.openrdf.query.QueryLanguage;
+import org.openrdf.query.TupleQuery;
+import org.openrdf.query.UpdateExecutionException;
+import org.openrdf.repository.RepositoryException;
+import org.slf4j.Logger;
+
+import com.google.common.collect.Lists;
+import com.google.common.io.CharStreams;
 
 /**
- * Execute SPARQL query (both query and update) on the LMF triple store
+ * Execute SPARQL query (both query and update) on the kiwi triple store
  * according the SPARQL 1.1 Protocol
  * 
  * @link http://www.w3.org/TR/sparql11-protocol/
@@ -82,7 +86,7 @@ public class SparqlWebService {
     public static final String SELECT = "/select";
     public static final String UPDATE = "/update";
     public static final String SNORQL = "/snorql";
-
+    
     @Inject
     private Logger log;
 
@@ -147,36 +151,46 @@ public class SparqlWebService {
     @GET
     @Path(SELECT)
     public Response selectGet(@QueryParam("query") String query, @QueryParam("output") String resultType, @Context HttpServletRequest request) {
-        if(resultType == null) {
-            List<ContentType> acceptedTypes = LMFHttpUtils.parseAcceptHeader(request.getHeader("Accept"));
-            List<ContentType> offeredTypes  = LMFHttpUtils.parseStringList(Lists.newArrayList("application/sparql-results+xml","application/sparql-results+json","text/html", "application/rdf+xml", "text/csv"));
-
-            ContentType bestType = LMFHttpUtils.bestContentType(offeredTypes,acceptedTypes);
-
-            if(bestType != null) {
-                resultType = bestType.getMime();
-            }
-        }
-
-        try {
-            if(resultType != null) {
-                if (StringUtils.isNotBlank(query))
-                    return buildQueryResponse(resultType, query);
-                else {
-                    if (parseSubType(resultType).equals("html"))
-                        return Response.seeOther(new URI(configurationService.getServerUri() + "sparql/admin/snorql/snorql.html")).build();
-                    else
-                        return Response.status(Response.Status.BAD_REQUEST).entity("no SPARQL query specified").build();
-                }
-            } else
-                return Response.status(Response.Status.BAD_REQUEST).entity("no result format specified or unsupported result format").build();
-        } catch (InvalidArgumentException ex) {
-            return Response.status(Response.Status.BAD_REQUEST).entity(ex.getMessage()).build();
-        } catch(Exception e) {
-            log.error("query execution threw an exception",e);
-
-            return Response.serverError().entity("query not supported").build();
-        }
+    	 if (StringUtils.isBlank(query)) {
+             try {
+            	 return Response.temporaryRedirect(new URI(configurationService.getServerUri() + "sparql/admin/snorql/snorql.html")).build();
+			} catch (URISyntaxException e) {
+				 return Response.status(Status.NOT_FOUND).build();
+			}
+         } else {
+        	try {
+    			final Query sparqlQuery = sparqlService.parseQuery(QueryLanguage.SPARQL, query);
+    			
+				final String format;
+    	        if(StringUtils.isBlank(resultType)) {
+        			List<ContentType> offeredTypes = new ArrayList<ContentType>();
+        			if (sparqlQuery instanceof TupleQuery || sparqlQuery instanceof BooleanQuery) {
+        				offeredTypes = LMFHttpUtils.parseStringList(Lists.newArrayList("application/sparql-results+xml", "application/sparql-results+json", "text/html", "text/csv"));
+        			} else if (sparqlQuery instanceof GraphQuery) {
+        				offeredTypes = LMFHttpUtils.parseStringList(Lists.newArrayList("application/rdf+xml", "text/rdf+n3", "text/turtle", "application/json"));
+        			}
+    	        	List<ContentType> acceptedTypes = LMFHttpUtils.parseAcceptHeader(request.getHeader("Accept"));
+    	            ContentType bestType = LMFHttpUtils.bestContentType(offeredTypes,acceptedTypes);
+    	            if(bestType != null) {
+    	                format = bestType.getMime();
+    	            } else {
+    	            	format = "";
+    	            }
+    	        } else {
+    	        	format = resultType; //FIXME: validate?
+    	        }
+    			
+    	        return buildQueryResponse(format, sparqlQuery);
+    	        
+    		} catch (RepositoryException e) {
+    			return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
+    		} catch (MalformedQueryException e) {
+    			return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build();
+    		} catch (Exception e) {
+                log.error("query execution threw an exception",e);
+                return Response.serverError().entity("query not supported").build();
+			}	 
+         }
     }
 
     /**
@@ -343,7 +357,7 @@ public class SparqlWebService {
                         resultType = bestType.getMime();
                     }
                 }
-                if (parseSubType(resultType).equals("html"))
+                if (SparqlWritersHelper.parseSubType(resultType).equals("html"))
                     return Response.seeOther(new URI(configurationService.getServerUri() + "sparql/admin/update.html")).build();
                 else
                     return Response.status(Response.Status.BAD_REQUEST).entity("no SPARQL query specified").build();
@@ -481,7 +495,7 @@ public class SparqlWebService {
             @Override
             public void write(OutputStream output) throws IOException, WebApplicationException {
                 try {
-                    sparqlService.query(QueryLanguage.SPARQL,query,getTupleResultWriter(resultType,output),getBooleanResultWriter(resultType,output), getGraphResultWriter(resultType,output));
+                    sparqlService.query(QueryLanguage.SPARQL, query, SparqlWritersHelper.getTupleResultWriter(resultType, output), SparqlWritersHelper.getBooleanResultWriter(resultType, output), SparqlWritersHelper.getGraphResultWriter(resultType, output));
                 } catch (MarmottaException ex) {
                     throw new WebApplicationException(ex.getCause(), Response.status(Response.Status.BAD_REQUEST).entity(WebServiceUtil.jsonErrorResponse(ex)).build());
                 } catch (QueryEvaluationException e) {
@@ -492,76 +506,22 @@ public class SparqlWebService {
             }
         };
 
-        //set returntype
-        String s = "";
-        if(resultType ==null) {
-            s = "application/sparql-results+xml;charset=utf-8";
-        } else if(parseSubType(resultType).equals("html") ) {
-            s = "text/html;charset=utf-8";
-        } else if(parseSubType(resultType).equals("json") ) {
-            s = "application/sparql-results+json;charset=utf-8";
-        } else if(parseSubType(resultType).equals("rdf+xml") ) {
-            s = "application/rdf+xml;charset=utf-8";
-        } else if(parseSubType(resultType).equals("rdf+n3") ) {
-            s = "text/rdf+n3;charset=utf-8";
-        } else if(parseSubType(resultType).equals("n3") ) {
-            s = "text/rdf+n3;charset=utf-8";
-        } else if(parseSubType(resultType).equals("csv") ) {
-            s = "text/csv;charset=utf-8";
-        } else {
-            s = "application/sparql-results+xml;charset=utf-8";
-        }
-
-        Response r = Response.ok().entity(entity).header("Content-Type", s).build();
-        return r;
-    }
-
-    private static Pattern subTypePattern = Pattern.compile("[a-z]+/([a-z0-9-._]+\\+)?([a-z0-9-._]+)(;.*)?");
-    private String parseSubType(String mimeType) {
-        Matcher matcher = subTypePattern.matcher(mimeType);
-        if (matcher.matches())
-            return matcher.group(2);
-        else
-            return mimeType;
-    }
-
-
-    private TupleQueryResultWriter getTupleResultWriter(String format, OutputStream os) {
-        //build outputwriter
-        final TupleQueryResultWriter out;
-        if(format == null) {
-            out = new SPARQLResultsXMLWriter(os);
-        } else if(parseSubType(format).equals("html")) {
-            out = new SPARQLResultsHTMLWriter(os);
-        } else if(parseSubType(format).equals("json")) {
-            out = new SPARQLResultsJSONWriter(os);
-        } else if(parseSubType(format).equals("xml")) {
-            out = new SPARQLResultsXMLWriter(os);
-        } else if(parseSubType(format).equals("csv")) {
-            out = new SPARQLResultsCSVWriter(os);
-        } else throw new InvalidArgumentException("could not produce format "+format);
-        return out;
-    }
-
-    private BooleanQueryResultWriter getBooleanResultWriter(String format, OutputStream os) {
-        //build outputwriter
-        final BooleanQueryResultWriter out;
-        if(format == null) {
-            out = new SPARQLBooleanXMLWriter(os);
-        } else if(parseSubType(format).equals("html")) {
-            out = new SPARQLBooleanHTMLWriter(os);
-        } else if(parseSubType(format).equals("json")) {
-            out = new SPARQLBooleanJSONWriter(os);
-        } else if(parseSubType(format).equals("xml")) {
-            out = new SPARQLBooleanXMLWriter(os);
-        } else if(parseSubType(format).equals("csv")) {
-            out = new BooleanTextWriter(os);
-        } else throw new InvalidArgumentException("could not produce format "+format);
-        return out;
+        return Response.ok().entity(entity).header("Content-Type", SparqlWritersHelper.buildSparqlContentType(resultType)).build();
     }
-
-    protected SPARQLGraphResultWriter getGraphResultWriter(String format, OutputStream os) {
-        return new SPARQLGraphResultWriter(os,format);
+	
+	private Response buildQueryResponse(final String resultType, final Query query) throws Exception {
+        StreamingOutput entity = new StreamingOutput() {
+            @Override
+            public void write(OutputStream output) throws IOException, WebApplicationException {
+                try {
+                    sparqlService.query(query, output, resultType);
+                } catch (QueryEvaluationException e) {
+                    throw new WebApplicationException(e.getCause(), Response.status(Response.Status.BAD_REQUEST).entity(WebServiceUtil.jsonErrorResponse(e)).build());
+                }
+            }
+        };
+        
+        return Response.ok().entity(entity).header("Content-Type", SparqlWritersHelper.buildSparqlContentType(resultType)).build();
     }
 
 }


[3/6] git commit: changed the strategy, becuase Query objects cannot be shared accross different repository connections

Posted by wi...@apache.org.
changed the strategy, becuase Query objects cannot be shared accross different repository connections


Project: http://git-wip-us.apache.org/repos/asf/incubator-marmotta/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-marmotta/commit/7150b1a7
Tree: http://git-wip-us.apache.org/repos/asf/incubator-marmotta/tree/7150b1a7
Diff: http://git-wip-us.apache.org/repos/asf/incubator-marmotta/diff/7150b1a7

Branch: refs/heads/master
Commit: 7150b1a73ad710757e24ecc94513b8d5825d3441
Parents: b92d74f
Author: Sergio Fernández <wi...@apache.org>
Authored: Fri Apr 5 14:02:21 2013 +0200
Committer: Sergio Fernández <wi...@apache.org>
Committed: Fri Apr 5 14:02:21 2013 +0200

----------------------------------------------------------------------
 .../platform/sparql/api/sparql/SparqlService.java  |   83 ++-------------
 .../sparql/services/sparql/SparqlServiceImpl.java  |   63 ++++++++----
 .../sparql/webservices/SparqlWebService.java       |    2 +-
 3 files changed, 53 insertions(+), 95 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-marmotta/blob/7150b1a7/platform/marmotta-sparql/src/main/java/org/apache/marmotta/platform/sparql/api/sparql/SparqlService.java
----------------------------------------------------------------------
diff --git a/platform/marmotta-sparql/src/main/java/org/apache/marmotta/platform/sparql/api/sparql/SparqlService.java b/platform/marmotta-sparql/src/main/java/org/apache/marmotta/platform/sparql/api/sparql/SparqlService.java
index 4fc372d..3a226b3 100644
--- a/platform/marmotta-sparql/src/main/java/org/apache/marmotta/platform/sparql/api/sparql/SparqlService.java
+++ b/platform/marmotta-sparql/src/main/java/org/apache/marmotta/platform/sparql/api/sparql/SparqlService.java
@@ -17,26 +17,23 @@
  */
 package org.apache.marmotta.platform.sparql.api.sparql;
 
+import java.io.OutputStream;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.marmotta.platform.core.exception.InvalidArgumentException;
 import org.apache.marmotta.platform.core.exception.MarmottaException;
 import org.apache.marmotta.platform.sparql.services.sparqlio.rdf.SPARQLGraphResultWriter;
-import org.apache.marmotta.platform.core.exception.InvalidArgumentException;
 import org.openrdf.model.Value;
-import org.openrdf.query.BooleanQuery;
-import org.openrdf.query.GraphQuery;
 import org.openrdf.query.MalformedQueryException;
 import org.openrdf.query.Query;
 import org.openrdf.query.QueryEvaluationException;
 import org.openrdf.query.QueryLanguage;
-import org.openrdf.query.TupleQuery;
 import org.openrdf.query.UpdateExecutionException;
 import org.openrdf.query.resultio.BooleanQueryResultWriter;
 import org.openrdf.query.resultio.TupleQueryResultWriter;
 import org.openrdf.repository.RepositoryException;
 
-import java.io.OutputStream;
-import java.util.List;
-import java.util.Map;
-
 /**
  * Add file description here!
  * <p/>
@@ -77,72 +74,12 @@ public interface SparqlService {
 	 * Evaluate a SPARQL query on the KiWi TripleStore. Writes the query results 
      * to the stream passed in the format requested.
      * 
-	 * @param query
-	 * @param output
-	 * @param format
-	 * @throws QueryEvaluationException
-	 */
-	void query(Query query, OutputStream output, String format) throws QueryEvaluationException;
-	
-	/**
-	 * Evaluate a SPARQL tuple query on the KiWi TripleStore. Writes the query results 
-     * to the writer passed.
-	 * 
-	 * @param tuple query
-	 * @param writer the writer to use to write results
-	 * @throws QueryEvaluationException
+	 * @param query query
+	 * @param output strem to write 
+	 * @param format mimetype
+	 * @throws MarmottaException
 	 */
-    void query(TupleQuery query, TupleQueryResultWriter writer) throws QueryEvaluationException;
-    
-    /**
-     * Evaluate a SPARQL tuple query on the KiWi TripleStore. Writes the query results 
-     * to the stream passed in the format requested.
-     * 
-     * @param query
-     * @param output
-     * @param format
-     */
-    void query(TupleQuery query, OutputStream output, String format) throws QueryEvaluationException;
-    
-    /**
-     * Evaluate a SPARQL boolean query on the KiWi TripleStore. Writes the query results 
-     * to the writer passed.
-     * 
-     * @param query boolean query
-     * @param writer the writer to use to write results
-     * @throws QueryEvaluationException
-     */
-    void query(BooleanQuery query, BooleanQueryResultWriter writer) throws QueryEvaluationException;
-    
-    /**
-     * Evaluate a SPARQL boolean query on the KiWi TripleStore. Writes the query results 
-     * to the stream passed in the format requested.
-     * 
-     * @param query
-     * @param output
-     * @param format
-     */
-    void query(BooleanQuery query, OutputStream output, String format) throws QueryEvaluationException;    
-    
-    /**
-     * Evaluate a SPARQL graph query on the KiWi TripleStore. Writes the query results 
-     * to the writer passed.
-     * 
-     * @param query graph query
-     * @param writer the writer to use to write results
-     * @throws QueryEvaluationException
-     */
-    void query(GraphQuery query, SPARQLGraphResultWriter writer) throws QueryEvaluationException;
-    
-    /**
-     * Evaluate a SPARQL graph query on the KiWi TripleStore. Writes the query results 
-     * to the stream passed in the format requested.
-     * 
-     * @param query
-     * @param output
-     * @param format
-     */
-    void query(GraphQuery query, OutputStream output, String format) throws QueryEvaluationException;    
+	void query(Query query, OutputStream output, String format) throws MarmottaException;
 	
     /**
      * Evaluate a SPARQL ASK query on the KiWi TripleStore

http://git-wip-us.apache.org/repos/asf/incubator-marmotta/blob/7150b1a7/platform/marmotta-sparql/src/main/java/org/apache/marmotta/platform/sparql/services/sparql/SparqlServiceImpl.java
----------------------------------------------------------------------
diff --git a/platform/marmotta-sparql/src/main/java/org/apache/marmotta/platform/sparql/services/sparql/SparqlServiceImpl.java b/platform/marmotta-sparql/src/main/java/org/apache/marmotta/platform/sparql/services/sparql/SparqlServiceImpl.java
index bfefd4d..93f0bff 100644
--- a/platform/marmotta-sparql/src/main/java/org/apache/marmotta/platform/sparql/services/sparql/SparqlServiceImpl.java
+++ b/platform/marmotta-sparql/src/main/java/org/apache/marmotta/platform/sparql/services/sparql/SparqlServiceImpl.java
@@ -127,20 +127,46 @@ public class SparqlServiceImpl implements SparqlService {
     }
     
     @Override
-    public void query(Query query, OutputStream output, String format) throws QueryEvaluationException {
-        if (query instanceof TupleQuery) {
-        	query((TupleQuery)query, output, format);
-        } else if (query instanceof BooleanQuery) {
-        	query((BooleanQuery)query, output, format);
-        } else if (query instanceof GraphQuery) {
-        	query((GraphQuery)query, output, format);
-        } else {
-            throw new InvalidArgumentException("SPARQL query type " + query.getClass() + " not supported!");
+    public void query(Query query, OutputStream output, String format) throws MarmottaException {
+        long start = System.currentTimeMillis();
+
+        log.debug("executing SPARQL query:\n{}", query);
+
+        try {
+            RepositoryConnection connection = sesameService.getConnection();
+            try {
+                connection.begin();
+                Query sparqlQuery = connection.prepareQuery(QueryLanguage.SPARQL, query.toString());
+
+                if (sparqlQuery instanceof TupleQuery) {
+                	query((TupleQuery)sparqlQuery, output, format);
+                } else if (sparqlQuery instanceof BooleanQuery) {
+                	query((BooleanQuery)sparqlQuery, output, format);
+                } else if (sparqlQuery instanceof GraphQuery) {
+                	query((GraphQuery)sparqlQuery, output, format);
+                } else {
+                    throw new InvalidArgumentException("SPARQL query type " + sparqlQuery.getClass() + " not supported!");
+                }
+
+                connection.commit();
+			} finally {
+                connection.close();
+            }
+        } catch(RepositoryException e) {
+            log.error("error while getting repository connection: {}", e);
+            throw new MarmottaException("error while getting repository connection", e);
+        } catch (QueryEvaluationException e) {
+        	log.error("error while evaluating query: {}", e);
+            throw new MarmottaException("error while writing query result in format ", e);
+        } catch (MalformedQueryException e) {
+        	log.error("error because malformed query: {}", e);
+            throw new MarmottaException("error because malformed query result in format ", e);
         }
+
+        log.debug("SPARQL execution took {}ms", System.currentTimeMillis()-start);
     }
 
-    @Override
-    public void query(TupleQuery query, TupleQueryResultWriter writer) throws QueryEvaluationException {
+    private void query(TupleQuery query, TupleQueryResultWriter writer) throws QueryEvaluationException {
     	try {
 			query.evaluate(writer);
 		} catch (TupleQueryResultHandlerException e) {
@@ -148,13 +174,11 @@ public class SparqlServiceImpl implements SparqlService {
 		}
     }
     
-    @Override
-    public void query(TupleQuery query, OutputStream output, String format) throws QueryEvaluationException {
+    private void query(TupleQuery query, OutputStream output, String format) throws QueryEvaluationException {
     	query(query, SparqlWritersHelper.getTupleResultWriter(format, output));
     }
     
-    @Override
-    public void query(BooleanQuery query, BooleanQueryResultWriter writer) throws QueryEvaluationException {
+    private void query(BooleanQuery query, BooleanQueryResultWriter writer) throws QueryEvaluationException {
     	try {
 			writer.write(query.evaluate());
 		} catch (IOException e) {
@@ -162,13 +186,11 @@ public class SparqlServiceImpl implements SparqlService {
 		}
     }
     
-    @Override
-    public void query(BooleanQuery query, OutputStream output, String format) throws QueryEvaluationException {
+    private void query(BooleanQuery query, OutputStream output, String format) throws QueryEvaluationException {
     	query(query, SparqlWritersHelper.getBooleanResultWriter(format, output));
     }
     
-    @Override
-    public void query(GraphQuery query, SPARQLGraphResultWriter writer) throws QueryEvaluationException {
+    private void query(GraphQuery query, SPARQLGraphResultWriter writer) throws QueryEvaluationException {
     	try {
 			writer.write(query.evaluate());
 		} catch (IOException e) {
@@ -176,8 +198,7 @@ public class SparqlServiceImpl implements SparqlService {
 		}
     }
     
-    @Override
-    public void query(GraphQuery query, OutputStream output, String format) throws QueryEvaluationException {
+    private void query(GraphQuery query, OutputStream output, String format) throws QueryEvaluationException {
     	query(query, SparqlWritersHelper.getGraphResultWriter(format, output));
     }
     

http://git-wip-us.apache.org/repos/asf/incubator-marmotta/blob/7150b1a7/platform/marmotta-sparql/src/main/java/org/apache/marmotta/platform/sparql/webservices/SparqlWebService.java
----------------------------------------------------------------------
diff --git a/platform/marmotta-sparql/src/main/java/org/apache/marmotta/platform/sparql/webservices/SparqlWebService.java b/platform/marmotta-sparql/src/main/java/org/apache/marmotta/platform/sparql/webservices/SparqlWebService.java
index 58a1ee7..56dd26a 100644
--- a/platform/marmotta-sparql/src/main/java/org/apache/marmotta/platform/sparql/webservices/SparqlWebService.java
+++ b/platform/marmotta-sparql/src/main/java/org/apache/marmotta/platform/sparql/webservices/SparqlWebService.java
@@ -515,7 +515,7 @@ public class SparqlWebService {
             public void write(OutputStream output) throws IOException, WebApplicationException {
                 try {
                     sparqlService.query(query, output, resultType);
-                } catch (QueryEvaluationException e) {
+                } catch (MarmottaException e) {
                     throw new WebApplicationException(e.getCause(), Response.status(Response.Status.BAD_REQUEST).entity(WebServiceUtil.jsonErrorResponse(e)).build());
                 }
             }


[2/6] git commit: starting the infrastructure to test the sparql module

Posted by wi...@apache.org.
starting the infrastructure to test the sparql module


Project: http://git-wip-us.apache.org/repos/asf/incubator-marmotta/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-marmotta/commit/b92d74f5
Tree: http://git-wip-us.apache.org/repos/asf/incubator-marmotta/tree/b92d74f5
Diff: http://git-wip-us.apache.org/repos/asf/incubator-marmotta/diff/b92d74f5

Branch: refs/heads/master
Commit: b92d74f54b7ab6e6ff898be992ed7469dc97a710
Parents: 1ceb90a
Author: Sergio Fernández <wi...@apache.org>
Authored: Fri Apr 5 13:27:56 2013 +0200
Committer: Sergio Fernández <wi...@apache.org>
Committed: Fri Apr 5 13:27:56 2013 +0200

----------------------------------------------------------------------
 platform/marmotta-sparql/pom.xml                   |   54 ++++++++++++
 .../sparql/webservices/SparqlWebServiceTest.java   |   53 ++++++++++++
 .../marmotta-sparql/src/test/resources/foaf.rdf    |   63 +++++++++++++++
 3 files changed, 170 insertions(+), 0 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-marmotta/blob/b92d74f5/platform/marmotta-sparql/pom.xml
----------------------------------------------------------------------
diff --git a/platform/marmotta-sparql/pom.xml b/platform/marmotta-sparql/pom.xml
index 24ac806..c809d5c 100644
--- a/platform/marmotta-sparql/pom.xml
+++ b/platform/marmotta-sparql/pom.xml
@@ -163,6 +163,60 @@
             <groupId>org.openrdf.sesame</groupId>
             <artifactId>sesame-queryresultio-text</artifactId>
         </dependency>
+        
+        <!-- testing -->
+        <dependency>
+            <groupId>org.apache.marmotta</groupId>
+            <artifactId>marmotta-core</artifactId>
+            <version>${project.version}</version>
+            <type>test-jar</type>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.mortbay.jetty</groupId>
+            <artifactId>jetty-embedded</artifactId>
+            <version>6.1.26</version>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>junit</groupId>
+            <artifactId>junit</artifactId>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.jboss.weld.se</groupId>
+            <artifactId>weld-se-core</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>com.h2database</groupId>
+            <artifactId>h2</artifactId>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>com.jayway.restassured</groupId>
+            <artifactId>rest-assured</artifactId>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.hamcrest</groupId>
+            <artifactId>hamcrest-library</artifactId>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.hamcrest</groupId>
+            <artifactId>hamcrest-core</artifactId>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>com.google.code.tempus-fugit</groupId>
+            <artifactId>tempus-fugit</artifactId>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>com.googlecode.jatl</groupId>
+            <artifactId>jatl</artifactId>
+            <scope>test</scope>
+        </dependency>       
 
     </dependencies>
 

http://git-wip-us.apache.org/repos/asf/incubator-marmotta/blob/b92d74f5/platform/marmotta-sparql/src/test/java/org/apache/marmotta/platform/sparql/webservices/SparqlWebServiceTest.java
----------------------------------------------------------------------
diff --git a/platform/marmotta-sparql/src/test/java/org/apache/marmotta/platform/sparql/webservices/SparqlWebServiceTest.java b/platform/marmotta-sparql/src/test/java/org/apache/marmotta/platform/sparql/webservices/SparqlWebServiceTest.java
new file mode 100644
index 0000000..d7d3a61
--- /dev/null
+++ b/platform/marmotta-sparql/src/test/java/org/apache/marmotta/platform/sparql/webservices/SparqlWebServiceTest.java
@@ -0,0 +1,53 @@
+package org.apache.marmotta.platform.sparql.webservices;
+
+import java.io.IOException;
+import java.io.InputStream;
+
+import org.apache.marmotta.platform.core.api.importer.ImportService;
+import org.apache.marmotta.platform.core.api.triplestore.ContextService;
+import org.apache.marmotta.platform.core.api.user.UserService;
+import org.apache.marmotta.platform.core.exception.io.MarmottaImportException;
+import org.apache.marmotta.platform.core.test.base.JettyMarmotta;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+import com.jayway.restassured.RestAssured;
+
+/**
+ * Tests for testing the SPAQL endpoint
+ * 
+ * @author Sergio Fernández
+ *
+ */
+public class SparqlWebServiceTest {
+
+    private static JettyMarmotta marmotta;
+
+    @BeforeClass
+    public static void setUp() throws MarmottaImportException {
+        marmotta = new JettyMarmotta("/marmotta");
+        ImportService importService = marmotta.getService(ImportService.class);
+        UserService userService = marmotta.getService(UserService.class);
+        ContextService contextService = marmotta.getService(ContextService.class);
+        InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("foaf.rdf"); 
+        importService.importData(is, "application/rdf+xml", userService.getAnonymousUser(), contextService.getDefaultContext());
+
+        RestAssured.baseURI = "http://localhost";
+        RestAssured.port = marmotta.getPort();
+        RestAssured.basePath = marmotta.getContext();
+
+    }
+
+    @AfterClass
+    public static void tearDown() {
+        marmotta.shutdown();
+    }
+
+    @Test
+    public void testSet() throws IOException, InterruptedException {
+        
+
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-marmotta/blob/b92d74f5/platform/marmotta-sparql/src/test/resources/foaf.rdf
----------------------------------------------------------------------
diff --git a/platform/marmotta-sparql/src/test/resources/foaf.rdf b/platform/marmotta-sparql/src/test/resources/foaf.rdf
new file mode 100644
index 0000000..d026773
--- /dev/null
+++ b/platform/marmotta-sparql/src/test/resources/foaf.rdf
@@ -0,0 +1,63 @@
+<?xml version="1.0" encoding="utf-8"?>
+<rdf:RDF
+    xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
+    xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
+    xmlns:owl="http://www.w3.org/2002/07/owl#"
+    xmlns:foaf="http://xmlns.com/foaf/0.1/"
+    xmlns:doap="http://usefulinc.com/ns/doap#"
+    xmlns:sioc="http://rdfs.org/sioc/ns#"
+    xmlns:sioct="http://rdfs.org/sioc/types#"
+    xmlns:dc="http://purl.org/dc/elements/1.1/"
+    xmlns:dct="http://purl.org/dc/terms/"
+    xmlns:mvcb="http://webns.net/mvcb/"
+    xmlns:rss="http://purl.org/rss/1.0/"
+    xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#"
+    xmlns:contact="http://www.w3.org/2000/10/swap/pim/contact#"
+    xmlns:air="http://www.daml.org/2001/10/html/airport-ont#"
+    xmlns:wn="http://xmlns.com/wordnet/1.6/"
+    xmlns:uranai="http://kota.s12.xrea.com/vocab/uranai#"
+    xmlns:rel="http://purl.org/vocab/relationship/"
+    xmlns:session="http://redfoot.net/2005/session#"
+    xmlns:cert="http://www.w3.org/ns/auth/cert#"
+    xmlns:wot="http://xmlns.com/wot/0.1/"
+    xml:lang="en"
+>
+
+  <foaf:Document rdf:about="http://www.wikier.org/foaf.rdf">
+    <rdfs:label>Wikier's FOAF document</rdfs:label>
+    <rdfs:comment>Document with Friend-of-a-Friend description of Wikier</rdfs:comment>
+    <foaf:maker rdf:resource="http://www.wikier.org/foaf#wikier"/>
+    <dct:license rdf:resource="http://creativecommons.org/licenses/by-sa/3.0/" />
+    <foaf:primaryTopic rdf:resource="http://www.wikier.org/foaf#wikier"/>
+    <mvcb:generatorAgent rdf:resource="http://rdfohloh.wikier.org/project/emacs"/>
+    <mvcb:errorReportsTo rdf:resource="mailto:sergio@wikier.org" />
+  </foaf:Document>
+
+  <foaf:Person rdf:about="http://www.wikier.org/foaf#wikier">
+    <foaf:name xml:lang="es">Sergio Fernández</foaf:name>
+    <foaf:title>Mr</foaf:title>
+    <foaf:firstName xml:lang="es">Sergio</foaf:firstName>
+    <foaf:surname xml:lang="es">Fernández</foaf:surname>
+    <foaf:gender>male</foaf:gender>
+    <foaf:nick>wikier</foaf:nick>
+    <session:hexdigest>30e97da6ad2d5be1086a64f3fc44a03a6fecadb3</session:hexdigest>
+    <uranai:bloodtype>O-</uranai:bloodtype>
+    <rdfs:comment>This URI indentifies me as a person. Feel free to use it when making statements about me as a person</rdfs:comment>
+    <rdfs:comment xml:lang="es">Esta URI me identifica como persona. Úsala para referirte a mi como persona</rdfs:comment>
+
+    <foaf:mbox rdf:resource="mailto:sergio@wikier.org" />
+    <foaf:mbox_sha1sum>d0fd987214f56f70b4c47fb96795f348691f93ab</foaf:mbox_sha1sum>
+
+    <foaf:mbox rdf:resource="mailto:wikier@asturlinux.org" />
+    <foaf:mbox_sha1sum>119222cf3a2893a375cc4f884a0138155c771415</foaf:mbox_sha1sum>
+
+    <foaf:mbox rdf:resource="mailto:sergio.fernandez@salzburgresearch.at" />
+    <foaf:mbox_sha1sum>fe6d23dc07ca84b1c487eb20d816aa4caf12ee84</foaf:mbox_sha1sum>
+
+    <foaf:mbox rdf:resource="mailto:wikier@apache.org" />
+    <foaf:mbox_sha1sum>762842c4b57e9657fe68badcc5439d3053d85f05</foaf:mbox_sha1sum>
+
+  </foaf:Person>
+
+</rdf:RDF>
+


[4/6] git commit: query-prepasng only for get the type, not passed to the service anymore due the potential issues could cause

Posted by wi...@apache.org.
query-prepasng only for get the type, not passed to the service anymore due the potential issues could cause


Project: http://git-wip-us.apache.org/repos/asf/incubator-marmotta/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-marmotta/commit/7b99a5b7
Tree: http://git-wip-us.apache.org/repos/asf/incubator-marmotta/tree/7b99a5b7
Diff: http://git-wip-us.apache.org/repos/asf/incubator-marmotta/diff/7b99a5b7

Branch: refs/heads/master
Commit: 7b99a5b7162f21ef1b5c206d86823200209a3844
Parents: 7150b1a
Author: Sergio Fernández <wi...@apache.org>
Authored: Fri Apr 5 14:14:33 2013 +0200
Committer: Sergio Fernández <wi...@apache.org>
Committed: Fri Apr 5 14:14:33 2013 +0200

----------------------------------------------------------------------
 .../platform/sparql/api/sparql/SparqlService.java  |    2 +-
 .../sparql/services/sparql/SparqlServiceImpl.java  |    4 +-
 .../sparql/webservices/SparqlWebService.java       |   45 +++++++--------
 3 files changed, 25 insertions(+), 26 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-marmotta/blob/7b99a5b7/platform/marmotta-sparql/src/main/java/org/apache/marmotta/platform/sparql/api/sparql/SparqlService.java
----------------------------------------------------------------------
diff --git a/platform/marmotta-sparql/src/main/java/org/apache/marmotta/platform/sparql/api/sparql/SparqlService.java b/platform/marmotta-sparql/src/main/java/org/apache/marmotta/platform/sparql/api/sparql/SparqlService.java
index 3a226b3..50f10b2 100644
--- a/platform/marmotta-sparql/src/main/java/org/apache/marmotta/platform/sparql/api/sparql/SparqlService.java
+++ b/platform/marmotta-sparql/src/main/java/org/apache/marmotta/platform/sparql/api/sparql/SparqlService.java
@@ -79,7 +79,7 @@ public interface SparqlService {
 	 * @param format mimetype
 	 * @throws MarmottaException
 	 */
-	void query(Query query, OutputStream output, String format) throws MarmottaException;
+	void query(QueryLanguage language, String query, OutputStream output, String format) throws MarmottaException;
 	
     /**
      * Evaluate a SPARQL ASK query on the KiWi TripleStore

http://git-wip-us.apache.org/repos/asf/incubator-marmotta/blob/7b99a5b7/platform/marmotta-sparql/src/main/java/org/apache/marmotta/platform/sparql/services/sparql/SparqlServiceImpl.java
----------------------------------------------------------------------
diff --git a/platform/marmotta-sparql/src/main/java/org/apache/marmotta/platform/sparql/services/sparql/SparqlServiceImpl.java b/platform/marmotta-sparql/src/main/java/org/apache/marmotta/platform/sparql/services/sparql/SparqlServiceImpl.java
index 93f0bff..2fd604c 100644
--- a/platform/marmotta-sparql/src/main/java/org/apache/marmotta/platform/sparql/services/sparql/SparqlServiceImpl.java
+++ b/platform/marmotta-sparql/src/main/java/org/apache/marmotta/platform/sparql/services/sparql/SparqlServiceImpl.java
@@ -127,7 +127,7 @@ public class SparqlServiceImpl implements SparqlService {
     }
     
     @Override
-    public void query(Query query, OutputStream output, String format) throws MarmottaException {
+    public void query(QueryLanguage language, String query, OutputStream output, String format) throws MarmottaException {
         long start = System.currentTimeMillis();
 
         log.debug("executing SPARQL query:\n{}", query);
@@ -136,7 +136,7 @@ public class SparqlServiceImpl implements SparqlService {
             RepositoryConnection connection = sesameService.getConnection();
             try {
                 connection.begin();
-                Query sparqlQuery = connection.prepareQuery(QueryLanguage.SPARQL, query.toString());
+                Query sparqlQuery = connection.prepareQuery(language, query);
 
                 if (sparqlQuery instanceof TupleQuery) {
                 	query((TupleQuery)sparqlQuery, output, format);

http://git-wip-us.apache.org/repos/asf/incubator-marmotta/blob/7b99a5b7/platform/marmotta-sparql/src/main/java/org/apache/marmotta/platform/sparql/webservices/SparqlWebService.java
----------------------------------------------------------------------
diff --git a/platform/marmotta-sparql/src/main/java/org/apache/marmotta/platform/sparql/webservices/SparqlWebService.java b/platform/marmotta-sparql/src/main/java/org/apache/marmotta/platform/sparql/webservices/SparqlWebService.java
index 56dd26a..ec827e5 100644
--- a/platform/marmotta-sparql/src/main/java/org/apache/marmotta/platform/sparql/webservices/SparqlWebService.java
+++ b/platform/marmotta-sparql/src/main/java/org/apache/marmotta/platform/sparql/webservices/SparqlWebService.java
@@ -59,7 +59,6 @@ import org.openrdf.query.BooleanQuery;
 import org.openrdf.query.GraphQuery;
 import org.openrdf.query.MalformedQueryException;
 import org.openrdf.query.Query;
-import org.openrdf.query.QueryEvaluationException;
 import org.openrdf.query.QueryLanguage;
 import org.openrdf.query.TupleQuery;
 import org.openrdf.query.UpdateExecutionException;
@@ -180,7 +179,7 @@ public class SparqlWebService {
     	        	format = resultType; //FIXME: validate?
     	        }
     			
-    	        return buildQueryResponse(format, sparqlQuery);
+    	        return buildQueryResponse(format, query);
     	        
     		} catch (RepositoryException e) {
     			return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
@@ -490,38 +489,38 @@ public class SparqlWebService {
 		return params;
 	}
 
-	private Response buildQueryResponse(final String resultType, final String query) throws Exception {
-        StreamingOutput entity = new StreamingOutput() {
-            @Override
-            public void write(OutputStream output) throws IOException, WebApplicationException {
-                try {
-                    sparqlService.query(QueryLanguage.SPARQL, query, SparqlWritersHelper.getTupleResultWriter(resultType, output), SparqlWritersHelper.getBooleanResultWriter(resultType, output), SparqlWritersHelper.getGraphResultWriter(resultType, output));
-                } catch (MarmottaException ex) {
-                    throw new WebApplicationException(ex.getCause(), Response.status(Response.Status.BAD_REQUEST).entity(WebServiceUtil.jsonErrorResponse(ex)).build());
-                } catch (QueryEvaluationException e) {
-                    throw new WebApplicationException(e.getCause(), Response.status(Response.Status.BAD_REQUEST).entity(WebServiceUtil.jsonErrorResponse(e)).build());
-                } catch (MalformedQueryException e) {
-                    throw new WebApplicationException(e.getCause(), Response.status(Response.Status.BAD_REQUEST).entity(WebServiceUtil.jsonErrorResponse(e)).build());
-                }
-            }
-        };
-
-        return Response.ok().entity(entity).header("Content-Type", SparqlWritersHelper.buildSparqlContentType(resultType)).build();
-    }
+//	private Response buildQueryResponse(final String resultType, final String query) throws Exception {
+//        StreamingOutput entity = new StreamingOutput() {
+//            @Override
+//            public void write(OutputStream output) throws IOException, WebApplicationException {
+//                try {
+//                    sparqlService.query(QueryLanguage.SPARQL, query, SparqlWritersHelper.getTupleResultWriter(resultType, output), SparqlWritersHelper.getBooleanResultWriter(resultType, output), SparqlWritersHelper.getGraphResultWriter(resultType, output));
+//                } catch (MarmottaException ex) {
+//                    throw new WebApplicationException(ex.getCause(), Response.status(Response.Status.BAD_REQUEST).entity(WebServiceUtil.jsonErrorResponse(ex)).build());
+//                } catch (QueryEvaluationException e) {
+//                    throw new WebApplicationException(e.getCause(), Response.status(Response.Status.BAD_REQUEST).entity(WebServiceUtil.jsonErrorResponse(e)).build());
+//                } catch (MalformedQueryException e) {
+//                    throw new WebApplicationException(e.getCause(), Response.status(Response.Status.BAD_REQUEST).entity(WebServiceUtil.jsonErrorResponse(e)).build());
+//                }
+//            }
+//        };
+//
+//        return Response.ok().entity(entity).header("Content-Type", SparqlWritersHelper.buildSparqlContentType(resultType)).build();
+//    }
 	
-	private Response buildQueryResponse(final String resultType, final Query query) throws Exception {
+	private Response buildQueryResponse(final String format, final String query) throws Exception {
         StreamingOutput entity = new StreamingOutput() {
             @Override
             public void write(OutputStream output) throws IOException, WebApplicationException {
                 try {
-                    sparqlService.query(query, output, resultType);
+                    sparqlService.query(QueryLanguage.SPARQL, query, output, format);
                 } catch (MarmottaException e) {
                     throw new WebApplicationException(e.getCause(), Response.status(Response.Status.BAD_REQUEST).entity(WebServiceUtil.jsonErrorResponse(e)).build());
                 }
             }
         };
         
-        return Response.ok().entity(entity).header("Content-Type", SparqlWritersHelper.buildSparqlContentType(resultType)).build();
+        return Response.ok().entity(entity).header("Content-Type", SparqlWritersHelper.buildSparqlContentType(format)).build();
     }
 
 }


[6/6] git commit: refactorized sparql select endpoint to have a single actual implementation, whatever the concrete http resource is called trough

Posted by wi...@apache.org.
refactorized sparql select endpoint to have a single actual implementation, whatever the concrete http resource is called trough


Project: http://git-wip-us.apache.org/repos/asf/incubator-marmotta/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-marmotta/commit/468e810e
Tree: http://git-wip-us.apache.org/repos/asf/incubator-marmotta/tree/468e810e
Diff: http://git-wip-us.apache.org/repos/asf/incubator-marmotta/diff/468e810e

Branch: refs/heads/master
Commit: 468e810e00bd4c28e01943c7c6ee872268d3d461
Parents: f52a0dc
Author: Sergio Fernández <wi...@apache.org>
Authored: Fri Apr 5 18:05:18 2013 +0200
Committer: Sergio Fernández <wi...@apache.org>
Committed: Fri Apr 5 18:05:18 2013 +0200

----------------------------------------------------------------------
 .../sparql/webservices/SparqlWebService.java       |  219 ++++++---------
 1 files changed, 87 insertions(+), 132 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-marmotta/blob/468e810e/platform/marmotta-sparql/src/main/java/org/apache/marmotta/platform/sparql/webservices/SparqlWebService.java
----------------------------------------------------------------------
diff --git a/platform/marmotta-sparql/src/main/java/org/apache/marmotta/platform/sparql/webservices/SparqlWebService.java b/platform/marmotta-sparql/src/main/java/org/apache/marmotta/platform/sparql/webservices/SparqlWebService.java
index 26de52b..063b904 100644
--- a/platform/marmotta-sparql/src/main/java/org/apache/marmotta/platform/sparql/webservices/SparqlWebService.java
+++ b/platform/marmotta-sparql/src/main/java/org/apache/marmotta/platform/sparql/webservices/SparqlWebService.java
@@ -50,7 +50,6 @@ import org.apache.commons.lang.StringUtils;
 import org.apache.marmotta.commons.http.ContentType;
 import org.apache.marmotta.commons.http.LMFHttpUtils;
 import org.apache.marmotta.platform.core.api.config.ConfigurationService;
-import org.apache.marmotta.platform.core.exception.InvalidArgumentException;
 import org.apache.marmotta.platform.core.exception.MarmottaException;
 import org.apache.marmotta.platform.core.util.WebServiceUtil;
 import org.apache.marmotta.platform.sparql.api.sparql.SparqlService;
@@ -136,63 +135,6 @@ public class SparqlWebService {
     }
 
     /**
-     * Execute a SPARQL 1.1 tuple query on the LMF triple store using the query passed as query parameter to the
-     * GET request. Result will be formatted using the result type passed as argument (either "html", "json" or "xml").
-     * <p/>
-     * see SPARQL 1.1 Query syntax at http://www.w3.org/TR/sparql11-query/
-     *
-     * @param query       the SPARQL 1.1 Query as a string parameter
-     * @param resultType  the format for serializing the query results ("html", "json", or "xml")
-     * @HTTP 200 in case the query was executed successfully
-     * @HTTP 500 in case there was an error during the query evaluation
-     * @return the query result in the format passed as argument
-     */
-    @GET
-    @Path(SELECT)
-    public Response selectGet(@QueryParam("query") String query, @QueryParam("output") String resultType, @Context HttpServletRequest request) {
-    	 if (StringUtils.isBlank(query)) {
-             try {
-            	 return Response.temporaryRedirect(new URI(configurationService.getServerUri() + "sparql/admin/snorql/snorql.html")).build();
-			} catch (URISyntaxException e) {
-				 return Response.status(Status.NOT_FOUND).build();
-			}
-         } else {
-        	try {
-    			final Query sparqlQuery = sparqlService.parseQuery(QueryLanguage.SPARQL, query);
-    			
-				final String format;
-    	        if(StringUtils.isBlank(resultType)) {
-        			List<ContentType> offeredTypes = new ArrayList<ContentType>();
-        			if (sparqlQuery instanceof TupleQuery || sparqlQuery instanceof BooleanQuery) {
-        				offeredTypes = LMFHttpUtils.parseStringList(Lists.newArrayList("application/sparql-results+xml", "application/sparql-results+json", "text/html", "text/csv"));
-        			} else if (sparqlQuery instanceof GraphQuery) {
-        				offeredTypes = LMFHttpUtils.parseStringList(Lists.newArrayList("application/rdf+xml", "text/rdf+n3", "text/turtle", "application/json"));
-        			}
-    	        	List<ContentType> acceptedTypes = LMFHttpUtils.parseAcceptHeader(request.getHeader("Accept"));
-    	            ContentType bestType = LMFHttpUtils.bestContentType(offeredTypes,acceptedTypes);
-    	            if(bestType != null) {
-    	                format = bestType.getMime();
-    	            } else {
-    	            	format = "";
-    	            }
-    	        } else {
-    	        	format = resultType; //FIXME: validate?
-    	        }
-    			
-    	        return buildQueryResponse(format, query);
-    	        
-    		} catch (RepositoryException e) {
-    			return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
-    		} catch (MalformedQueryException e) {
-    			return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build();
-    		} catch (Exception e) {
-                log.error("query execution threw an exception",e);
-                return Response.serverError().entity("query not supported").build();
-			}	 
-         }
-    }
-
-    /**
      * For CORS operations TODO: make it more fine grained (maybe user dependent)
      * + TODO filter chain do not work properly
      * 
@@ -215,6 +157,84 @@ public class SparqlWebService {
     }
     
     /**
+     * Actual select query web service implementation
+     * 
+     * @param query query
+     * @param resultType format requested
+     * @param accept accept header
+     * @return
+     */
+    private Response select(String query, String resultType, String accept) {
+		if (StringUtils.isBlank(query)) {
+			try {
+				return Response.temporaryRedirect(
+						new URI(configurationService.getServerUri()
+								+ "sparql/admin/snorql/snorql.html")).build();
+			} catch (URISyntaxException e) {
+				return Response.status(Status.NOT_FOUND).build();
+			}
+		} else {
+			try {
+				final Query sparqlQuery = sparqlService.parseQuery(QueryLanguage.SPARQL, query);
+
+				final String format;
+				if (StringUtils.isBlank(resultType)) {
+					List<ContentType> offeredTypes = new ArrayList<ContentType>();
+					if (sparqlQuery instanceof TupleQuery
+							|| sparqlQuery instanceof BooleanQuery) {
+						offeredTypes = LMFHttpUtils.parseStringList(Lists
+								.newArrayList("application/sparql-results+xml",
+										"application/sparql-results+json",
+										"text/html", "text/csv"));
+					} else if (sparqlQuery instanceof GraphQuery) {
+						offeredTypes = LMFHttpUtils.parseStringList(Lists
+								.newArrayList("application/rdf+xml",
+										"text/rdf+n3", "text/turtle",
+										"application/json"));
+					}
+					List<ContentType> acceptedTypes = LMFHttpUtils.parseAcceptHeader(accept);
+					ContentType bestType = LMFHttpUtils.bestContentType(offeredTypes, acceptedTypes);
+					if (bestType != null) {
+						format = bestType.getMime();
+					} else {
+						format = "";
+					}
+				} else {
+					format = resultType; // FIXME: validate?
+				}
+
+				return buildQueryResponse(format, query);
+
+			} catch (RepositoryException e) {
+				return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
+			} catch (MalformedQueryException e) {
+				return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build();
+			} catch (Exception e) {
+				log.error("query execution threw an exception", e);
+				return Response.serverError().entity("query not supported").build();
+			}
+		}
+    }
+    
+    /**
+     * Execute a SPARQL 1.1 tuple query on the KiWi triple store using the query passed as query parameter to the
+     * GET request. Result will be formatted using the result type passed as argument (either "html", "json" or "xml").
+     * <p/>
+     * see SPARQL 1.1 Query syntax at http://www.w3.org/TR/sparql11-query/
+     *
+     * @param query       the SPARQL 1.1 Query as a string parameter
+     * @param resultType  the format for serializing the query results ("html", "json", or "xml")
+     * @HTTP 200 in case the query was executed successfully
+     * @HTTP 500 in case there was an error during the query evaluation
+     * @return the query result in the format passed as argument
+     */
+    @GET
+    @Path(SELECT)
+    public Response selectGet(@QueryParam("query") String query, @QueryParam("output") String resultType, @Context HttpServletRequest request) {
+    	return select(query, resultType, request.getHeader("Accept"));
+    }    
+    
+    /**
      * Execute a SPARQL 1.1 tuple query on the LMF triple store using the query passed as form parameter to the
      * POST request. Result will be formatted using the result type passed as argument (either "html", "json" or "xml").
      * <p/>
@@ -230,35 +250,11 @@ public class SparqlWebService {
     @Consumes({"application/x-www-url-form-urlencoded", "application/x-www-form-urlencoded"})
     @Path(SELECT)
     public Response selectPostForm(@FormParam("query") String query, @QueryParam("output") String resultType, @Context HttpServletRequest request) {
-        try {
-            if(resultType == null) {
-                List<ContentType> acceptedTypes = LMFHttpUtils.parseAcceptHeader(request.getHeader("Accept"));
-                List<ContentType> offeredTypes  = LMFHttpUtils.parseStringList(Lists.newArrayList("application/sparql-results+xml","application/sparql-results+json","text/html", "application/rdf+xml", "text/csv"));
-
-                ContentType bestType = LMFHttpUtils.bestContentType(offeredTypes,acceptedTypes);
-
-                if(bestType != null) {
-                    resultType = bestType.getMime();
-                }
-            }
-            if(resultType != null) {
-                if (StringUtils.isNotBlank(query))
-                    return buildQueryResponse(resultType, query);
-                else
-                    return Response.status(Response.Status.BAD_REQUEST).entity("no SPARQL query specified").build();
-            } else
-                return Response.status(Response.Status.BAD_REQUEST).entity("no result format specified or unsupported result format").build();
-        } catch (InvalidArgumentException ex) {
-            return Response.status(Response.Status.BAD_REQUEST).entity(ex.getMessage()).build();
-        } catch(Exception e) {
-            log.error("query execution threw an exception",e);
-
-            return Response.serverError().entity("query not supported").build();
-        }
+    	return select(query, resultType, request.getHeader("Accept"));
     }
 
     /**
-     * Execute a SPARQL 1.1 tuple query on the LMF triple store using the query passed in the body of the
+     * Execute a SPARQL 1.1 tuple query on the KiWi triple store using the query passed in the body of the
      * POST request. Result will be formatted using the result type passed as argument (either "html", "json" or "xml").
      * <p/>
      * see SPARQL 1.1 Query syntax at http://www.w3.org/TR/sparql11-query/
@@ -272,37 +268,16 @@ public class SparqlWebService {
     @POST
     @Path(SELECT)
     public Response selectPost(@QueryParam("output") String resultType, @Context HttpServletRequest request) {
-        try {
-            if(resultType == null) {
-                List<ContentType> acceptedTypes = LMFHttpUtils.parseAcceptHeader(request.getHeader("Accept"));
-                List<ContentType> offeredTypes  = LMFHttpUtils.parseStringList(Lists.newArrayList("application/sparql-results+xml","application/sparql-results+json","text/html", "application/rdf+xml", "text/csv"));
-
-                ContentType bestType = LMFHttpUtils.bestContentType(offeredTypes,acceptedTypes);
-
-                if(bestType != null) {
-                    resultType = bestType.getMime();
-                }
-            }
-
-            if(resultType != null) {
-                String query = CharStreams.toString(request.getReader());
-                if (query != null && !query.equals(""))
-                    return buildQueryResponse(resultType, query);
-                else
-                    return Response.status(Response.Status.BAD_REQUEST).entity("no SPARQL query specified").build();
-            } else
-                return Response.status(Response.Status.BAD_REQUEST).entity("no result format specified or unsupported result format").build();
-        } catch (InvalidArgumentException ex) {
-            return Response.status(Response.Status.BAD_REQUEST).entity(ex.getMessage()).build();
-        } catch(Exception e) {
-            log.error("query execution threw an exception",e);
-
-            return Response.serverError().entity("query not supported").build();
-        }
+    	try {
+    		String query = CharStreams.toString(request.getReader());
+    		return select(query, resultType, request.getHeader("Accept"));
+    	} catch (IOException e) {
+    		return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build();
+		}
     }
 
     /**
-     * Execute a SPARQL 1.1 tuple query on the LMF triple store using the query passed as form parameter to the
+     * Execute a SPARQL 1.1 tuple query on the KiWi triple store using the query passed as form parameter to the
      * POST request. Result will be formatted using the result type passed as argument (either "html", "json" or "xml").
      * <p/>
      * see SPARQL 1.1 Query syntax at http://www.w3.org/TR/sparql11-query/
@@ -320,7 +295,6 @@ public class SparqlWebService {
             return buildQueryResponse(resultType, query);
         } catch(Exception e) {
             log.error("query execution threw an exception",e);
-
             return Response.serverError().entity("query not supported").build();
         }
     }
@@ -488,25 +462,6 @@ public class SparqlWebService {
         }
 		return params;
 	}
-
-//	private Response buildQueryResponse(final String resultType, final String query) throws Exception {
-//        StreamingOutput entity = new StreamingOutput() {
-//            @Override
-//            public void write(OutputStream output) throws IOException, WebApplicationException {
-//                try {
-//                    sparqlService.query(QueryLanguage.SPARQL, query, SparqlWritersHelper.getTupleResultWriter(resultType, output), SparqlWritersHelper.getBooleanResultWriter(resultType, output), SparqlWritersHelper.getGraphResultWriter(resultType, output));
-//                } catch (MarmottaException ex) {
-//                    throw new WebApplicationException(ex.getCause(), Response.status(Response.Status.BAD_REQUEST).entity(WebServiceUtil.jsonErrorResponse(ex)).build());
-//                } catch (QueryEvaluationException e) {
-//                    throw new WebApplicationException(e.getCause(), Response.status(Response.Status.BAD_REQUEST).entity(WebServiceUtil.jsonErrorResponse(e)).build());
-//                } catch (MalformedQueryException e) {
-//                    throw new WebApplicationException(e.getCause(), Response.status(Response.Status.BAD_REQUEST).entity(WebServiceUtil.jsonErrorResponse(e)).build());
-//                }
-//            }
-//        };
-//
-//        return Response.ok().entity(entity).header("Content-Type", SparqlWritersHelper.buildSparqlContentType(resultType)).build();
-//    }
 	
 	private Response buildQueryResponse(final String format, final String query) throws Exception {
         StreamingOutput entity = new StreamingOutput() {


[5/6] git commit: resolving MARMOTTA-188 by removing complicated and duplicated code actually no needed

Posted by wi...@apache.org.
resolving MARMOTTA-188 by removing complicated and duplicated code actually no needed


Project: http://git-wip-us.apache.org/repos/asf/incubator-marmotta/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-marmotta/commit/f52a0dc2
Tree: http://git-wip-us.apache.org/repos/asf/incubator-marmotta/tree/f52a0dc2
Diff: http://git-wip-us.apache.org/repos/asf/incubator-marmotta/diff/f52a0dc2

Branch: refs/heads/master
Commit: f52a0dc22daed38456c4864b8fef7fefa8ac37b7
Parents: 7b99a5b
Author: Sergio Fernández <wi...@apache.org>
Authored: Fri Apr 5 17:48:12 2013 +0200
Committer: Sergio Fernández <wi...@apache.org>
Committed: Fri Apr 5 17:48:12 2013 +0200

----------------------------------------------------------------------
 .../services/sparql/SparqlWritersHelper.java       |   21 ---------------
 .../sparql/webservices/SparqlWebService.java       |    2 +-
 2 files changed, 1 insertions(+), 22 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-marmotta/blob/f52a0dc2/platform/marmotta-sparql/src/main/java/org/apache/marmotta/platform/sparql/services/sparql/SparqlWritersHelper.java
----------------------------------------------------------------------
diff --git a/platform/marmotta-sparql/src/main/java/org/apache/marmotta/platform/sparql/services/sparql/SparqlWritersHelper.java b/platform/marmotta-sparql/src/main/java/org/apache/marmotta/platform/sparql/services/sparql/SparqlWritersHelper.java
index f827c57..a5971dd 100644
--- a/platform/marmotta-sparql/src/main/java/org/apache/marmotta/platform/sparql/services/sparql/SparqlWritersHelper.java
+++ b/platform/marmotta-sparql/src/main/java/org/apache/marmotta/platform/sparql/services/sparql/SparqlWritersHelper.java
@@ -21,7 +21,6 @@ import java.io.OutputStream;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 
-import org.apache.commons.lang.StringUtils;
 import org.apache.marmotta.platform.core.exception.InvalidArgumentException;
 import org.apache.marmotta.platform.sparql.services.sparqlio.rdf.SPARQLGraphResultWriter;
 import org.apache.marmotta.platform.sparql.services.sparqlio.sparqlhtml.SPARQLBooleanHTMLWriter;
@@ -93,24 +92,4 @@ public class SparqlWritersHelper {
             return mimeType;
     }
     
-    public static String buildSparqlContentType(String resultType) {
-        if(StringUtils.isBlank(resultType)) {
-            return "application/sparql-results+xml;charset=utf-8";
-        } else if(parseSubType(resultType).equals("html") ) {
-        	return "text/html;charset=utf-8";
-        } else if(parseSubType(resultType).equals("json") ) {
-        	return "application/sparql-results+json;charset=utf-8";
-        } else if(parseSubType(resultType).equals("rdf+xml") ) {
-        	return "application/rdf+xml;charset=utf-8";
-        } else if(parseSubType(resultType).equals("rdf+n3") ) {
-        	return "text/rdf+n3;charset=utf-8";
-        } else if(parseSubType(resultType).equals("n3") ) {
-        	return "text/rdf+n3;charset=utf-8";
-        } else if(parseSubType(resultType).equals("csv") ) {
-        	return "text/csv;charset=utf-8";
-        } else {
-        	return "application/sparql-results+xml;charset=utf-8";
-        }
-    }
-
 }

http://git-wip-us.apache.org/repos/asf/incubator-marmotta/blob/f52a0dc2/platform/marmotta-sparql/src/main/java/org/apache/marmotta/platform/sparql/webservices/SparqlWebService.java
----------------------------------------------------------------------
diff --git a/platform/marmotta-sparql/src/main/java/org/apache/marmotta/platform/sparql/webservices/SparqlWebService.java b/platform/marmotta-sparql/src/main/java/org/apache/marmotta/platform/sparql/webservices/SparqlWebService.java
index ec827e5..26de52b 100644
--- a/platform/marmotta-sparql/src/main/java/org/apache/marmotta/platform/sparql/webservices/SparqlWebService.java
+++ b/platform/marmotta-sparql/src/main/java/org/apache/marmotta/platform/sparql/webservices/SparqlWebService.java
@@ -520,7 +520,7 @@ public class SparqlWebService {
             }
         };
         
-        return Response.ok().entity(entity).header("Content-Type", SparqlWritersHelper.buildSparqlContentType(format)).build();
+        return Response.ok().entity(entity).header("Content-Type", format+";charset=utf-8").build();
     }
 
 }