clerezza-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From m...@apache.org
Subject svn commit: r1475756 - in /clerezza/trunk/jaxrs.rdf.providers: ./ src/main/java/org/apache/clerezza/jaxrs/sparql/ src/main/java/org/apache/clerezza/jaxrs/sparql/providers/
Date Thu, 25 Apr 2013 13:20:42 GMT
Author: misl
Date: Thu Apr 25 13:20:41 2013
New Revision: 1475756

URL: http://svn.apache.org/r1475756
Log:
Fixed CLEREZZA-756
- copied ResultSetXmlMessageBodyWriter.java to jaxrs.rdf.providers/pom.xml
- added ResultSetJsonMessageBodyWriter.java to support W3C rdf-sparql-json-res-20070618

Added:
    clerezza/trunk/jaxrs.rdf.providers/src/main/java/org/apache/clerezza/jaxrs/sparql/
    clerezza/trunk/jaxrs.rdf.providers/src/main/java/org/apache/clerezza/jaxrs/sparql/providers/
    clerezza/trunk/jaxrs.rdf.providers/src/main/java/org/apache/clerezza/jaxrs/sparql/providers/ResultSetJsonMessageBodyWriter.java
    clerezza/trunk/jaxrs.rdf.providers/src/main/java/org/apache/clerezza/jaxrs/sparql/providers/ResultSetXmlMessageBodyWriter.java
Modified:
    clerezza/trunk/jaxrs.rdf.providers/pom.xml

Modified: clerezza/trunk/jaxrs.rdf.providers/pom.xml
URL: http://svn.apache.org/viewvc/clerezza/trunk/jaxrs.rdf.providers/pom.xml?rev=1475756&r1=1475755&r2=1475756&view=diff
==============================================================================
--- clerezza/trunk/jaxrs.rdf.providers/pom.xml (original)
+++ clerezza/trunk/jaxrs.rdf.providers/pom.xml Thu Apr 25 13:20:41 2013
@@ -44,6 +44,11 @@
             <version>0.14-SNAPSHOT</version>
         </dependency>
         <dependency>
+            <groupId>com.googlecode.json-simple</groupId>
+            <artifactId>json-simple</artifactId>
+            <optional>true</optional>
+        </dependency>
+        <dependency>
             <groupId>javax.ws.rs</groupId>
             <artifactId>jsr311-api</artifactId>
         </dependency>

Added: clerezza/trunk/jaxrs.rdf.providers/src/main/java/org/apache/clerezza/jaxrs/sparql/providers/ResultSetJsonMessageBodyWriter.java
URL: http://svn.apache.org/viewvc/clerezza/trunk/jaxrs.rdf.providers/src/main/java/org/apache/clerezza/jaxrs/sparql/providers/ResultSetJsonMessageBodyWriter.java?rev=1475756&view=auto
==============================================================================
--- clerezza/trunk/jaxrs.rdf.providers/src/main/java/org/apache/clerezza/jaxrs/sparql/providers/ResultSetJsonMessageBodyWriter.java
(added)
+++ clerezza/trunk/jaxrs.rdf.providers/src/main/java/org/apache/clerezza/jaxrs/sparql/providers/ResultSetJsonMessageBodyWriter.java
Thu Apr 25 13:20:41 2013
@@ -0,0 +1,174 @@
+/*
+ * 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.clerezza.jaxrs.sparql.providers;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.lang.annotation.Annotation;
+import java.lang.reflect.Type;
+import java.util.Set;
+
+import javax.ws.rs.Produces;
+import javax.ws.rs.WebApplicationException;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.MultivaluedMap;
+import javax.ws.rs.ext.MessageBodyWriter;
+import javax.ws.rs.ext.Provider;
+
+import org.apache.clerezza.rdf.core.BNode;
+import org.apache.clerezza.rdf.core.Language;
+import org.apache.clerezza.rdf.core.PlainLiteral;
+import org.apache.clerezza.rdf.core.Resource;
+import org.apache.clerezza.rdf.core.TypedLiteral;
+import org.apache.clerezza.rdf.core.UriRef;
+import org.apache.clerezza.rdf.core.sparql.ResultSet;
+import org.apache.clerezza.rdf.core.sparql.SolutionMapping;
+import org.apache.clerezza.rdf.core.sparql.query.Variable;
+import org.apache.felix.scr.annotations.Component;
+import org.apache.felix.scr.annotations.Property;
+import org.apache.felix.scr.annotations.Service;
+import org.json.simple.JSONArray;
+import org.json.simple.JSONObject;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * MessageBodyWirter for <code>ResultSet</code>.
+ * Resulting output conforms to:
+ * http://www.w3.org/TR/2007/NOTE-rdf-sparql-json-res-20070618/
+ * 
+ * @author misl
+ */
+@Component
+@Service(Object.class)
+@Property(name="javax.ws.rs", boolValue=true)
+@Produces({"application/json", "application/sparql-results+json"})
+@Provider
+@SuppressWarnings("unchecked")
+public class ResultSetJsonMessageBodyWriter implements MessageBodyWriter<ResultSet>
{
+
+	final Logger logger = LoggerFactory.getLogger(ResultSetJsonMessageBodyWriter.class);
+
+	@Override
+	public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations,
+			MediaType mediaType) {
+		return ResultSet.class.isAssignableFrom(type);
+	}
+
+	@Override
+	public long getSize(ResultSet t, Class<?> type, Type genericType,
+			Annotation[] annotations, MediaType mediaType) {
+		return -1;
+	}
+
+	@Override
+	public void writeTo(ResultSet resultSet, Class<?> type, Type genericType,
+			Annotation[] annotations, MediaType mediaType, MultivaluedMap<String,
+			Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException
{
+
+		JSONObject json = toJsonSource(resultSet);
+		entityStream.write(json.toJSONString().getBytes("UTF-8"));
+	}
+
+	/**
+	 * Helper: transforms a {@link ResultSet} or a {@link Boolean} to a
+	 * json object.
+	 *
+	 * @param queryResult
+	 */
+	private JSONObject toJsonSource(ResultSet queryResult) {
+		JSONObject root = new JSONObject();
+		JSONObject head = new JSONObject();
+		root.put("head", head);
+		
+		JSONObject results = new JSONObject();
+		root.put("results", results);
+		
+		JSONArray bindings = null;
+		SolutionMapping solutionMapping = null;
+		while (queryResult.hasNext()) {
+			if (bindings == null) {
+				bindings = new JSONArray();
+				results.put("bindings", bindings);
+			}
+			solutionMapping = queryResult.next();				
+			bindings.add(createResult(solutionMapping));				
+		}
+		if (solutionMapping != null) {
+			createVariable(solutionMapping, head);
+		}
+
+		return root;
+	}
+
+	/**
+	 * Helper: creates value element from {@link Resource} depending on its
+	 * class
+	 *
+	 */
+	private JSONObject createResultElement(Resource resource) {
+		JSONObject element = new JSONObject();
+		if (resource instanceof UriRef) {
+			element.put("type", "uri");
+			element.put("value", UriRef.class.cast(resource).getUnicodeString());
+		} else if (resource instanceof PlainLiteral) {
+			element.put("type", "literal");
+			element.put("value", PlainLiteral.class.cast(resource).getLexicalForm());
+			Language lang = PlainLiteral.class.cast(resource).getLanguage();
+			if (lang != null) {
+				element.put("xml:lang", lang.toString());
+			}
+		} else if (resource instanceof TypedLiteral) {
+			element.put("type", "typed-literal");
+			element.put("datatype", TypedLiteral.class.cast(resource).getDataType().getUnicodeString());
+			element.put("value", TypedLiteral.class.cast(resource).getLexicalForm());
+		} else if (resource instanceof BNode) {
+			element.put("type", "bnode");
+			element.put("value", "/");
+		} else {
+			element = null;
+		}
+		return element;
+	}
+
+	/**
+	 * Helper: creates results element from ResultSet
+	 *
+	 */
+	private JSONObject createResult(SolutionMapping solutionMap) {
+		JSONObject result = new JSONObject();
+		Set<Variable> keys = solutionMap.keySet();
+		for (Variable key : keys) {
+			result.put(key.getName(), createResultElement((Resource) solutionMap.get(key)));
+		}
+		return result;
+	}
+
+	private void createVariable(SolutionMapping solutionMap, JSONObject head) {
+		Set<Variable> keys = solutionMap.keySet();
+		JSONArray vars = null;
+		for (Variable key : keys) {
+			if (vars == null) {
+				vars = new JSONArray();
+				head.put("vars", vars);
+			}
+			vars.add(key.getName());
+		}
+	}
+}

Added: clerezza/trunk/jaxrs.rdf.providers/src/main/java/org/apache/clerezza/jaxrs/sparql/providers/ResultSetXmlMessageBodyWriter.java
URL: http://svn.apache.org/viewvc/clerezza/trunk/jaxrs.rdf.providers/src/main/java/org/apache/clerezza/jaxrs/sparql/providers/ResultSetXmlMessageBodyWriter.java?rev=1475756&view=auto
==============================================================================
--- clerezza/trunk/jaxrs.rdf.providers/src/main/java/org/apache/clerezza/jaxrs/sparql/providers/ResultSetXmlMessageBodyWriter.java
(added)
+++ clerezza/trunk/jaxrs.rdf.providers/src/main/java/org/apache/clerezza/jaxrs/sparql/providers/ResultSetXmlMessageBodyWriter.java
Thu Apr 25 13:20:41 2013
@@ -0,0 +1,209 @@
+/*
+ * 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.clerezza.jaxrs.sparql.providers;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.lang.annotation.Annotation;
+import java.lang.reflect.Type;
+import java.util.Set;
+
+import javax.ws.rs.Produces;
+import javax.ws.rs.WebApplicationException;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.MultivaluedMap;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.Response.Status;
+import javax.ws.rs.ext.MessageBodyWriter;
+import javax.ws.rs.ext.Provider;
+import javax.ws.rs.ext.Providers;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.transform.Source;
+import javax.xml.transform.dom.DOMSource;
+
+import org.apache.clerezza.rdf.core.Language;
+import org.apache.clerezza.rdf.core.PlainLiteral;
+import org.apache.clerezza.rdf.core.Resource;
+import org.apache.clerezza.rdf.core.TypedLiteral;
+import org.apache.clerezza.rdf.core.UriRef;
+import org.apache.clerezza.rdf.core.sparql.ResultSet;
+import org.apache.clerezza.rdf.core.sparql.SolutionMapping;
+import org.apache.clerezza.rdf.core.sparql.query.Variable;
+import org.apache.felix.scr.annotations.Component;
+import org.apache.felix.scr.annotations.Property;
+import org.apache.felix.scr.annotations.Service;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+
+/**
+ * MessageBodyWirter for <code>ResultSet</code>.
+ * Resulting output conforms to:
+ * http://www.w3.org/TR/2008/REC-rdf-sparql-XMLres-20080115/
+ * 
+ * @author mir, reto
+ */
+@Component
+@Service(Object.class)
+@Property(name="javax.ws.rs", boolValue=true)
+@Produces({"application/xml", "text/xml", "application/sparql-results+xml"})
+@Provider
+public class ResultSetXmlMessageBodyWriter implements MessageBodyWriter<ResultSet>
{
+
+	private Providers providers;
+
+	final Logger logger = LoggerFactory.getLogger(ResultSetXmlMessageBodyWriter.class);
+
+	@Override
+	public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations,
+			MediaType mediaType) {
+		return ResultSet.class.isAssignableFrom(type);
+	}
+
+	@Override
+	public long getSize(ResultSet t, Class<?> type, Type genericType,
+			Annotation[] annotations, MediaType mediaType) {
+		return -1;
+	}
+
+	@Override
+	public void writeTo(ResultSet resultSet, Class<?> type, Type genericType,
+			Annotation[] annotations, MediaType mediaType, MultivaluedMap<String,
+			Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException
{
+
+		Source source = toXmlSource(resultSet);
+		MessageBodyWriter<Source> sourceMessageBodyWriter = 
+				providers.getMessageBodyWriter(Source.class, null, null, mediaType);
+		sourceMessageBodyWriter.writeTo(source, Source.class, null, null, mediaType,
+				httpHeaders, entityStream);
+	}
+
+	@Context
+	public void setProviders(Providers providers) {
+		this.providers = providers;
+	}
+
+	/**
+	 * Helper: transforms a {@link ResultSet} or a {@link Boolean} to a
+	 * {@link DOMSource}
+	 *
+	 * @param queryResult
+	 * @param query
+	 * @param applyStyle
+	 */
+	private Source toXmlSource(ResultSet queryResult) {
+		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
+		try {
+			Document doc = dbf.newDocumentBuilder().newDocument();
+			// adding root element
+			Element root = doc.createElement("sparql");
+			root.setAttribute("xmlns", "http://www.w3.org/2005/sparql-results#");
+			doc.appendChild(root);
+			Element head = doc.createElement("head");
+			root.appendChild(head);
+			Element results = doc.createElement("results");
+			SolutionMapping solutionMapping = null;
+			while (queryResult.hasNext()) {
+				solutionMapping = queryResult.next();				
+				createResultElement(solutionMapping, results, doc);				
+			}
+			if (solutionMapping != null) {
+				createVariable(solutionMapping, head, doc);
+			}
+			root.appendChild(results);
+
+			DOMSource source = new DOMSource(doc);
+			return source;
+
+		} catch (ParserConfigurationException e) {
+			throw createWebApplicationException(e);
+		}
+	}
+
+	/**
+	 * Creates a WebApplicationexception and prints a logger entry
+	 */
+	private WebApplicationException createWebApplicationException(Exception e) {
+		return new WebApplicationException(Response.status(Status.BAD_REQUEST)
+				.entity(e.getMessage().replace("<", "&lt;").replace("\n",
+						"<br/>")).build());
+	}
+
+
+	/**
+	 * Helper: creates value element from {@link Resource} depending on its
+	 * class
+	 *
+	 */
+	private Element createValueElement(Resource resource, Document doc) {
+		Element value = null;
+		if (resource instanceof UriRef) {
+			value = doc.createElement("uri");
+			value.appendChild(doc.createTextNode(((UriRef) resource)
+					.getUnicodeString()));
+		} else if (resource instanceof TypedLiteral) {
+			value = doc.createElement("literal");
+			value.appendChild(doc.createTextNode(((TypedLiteral) resource)
+					.getLexicalForm()));
+			value.setAttribute("datatype", (((TypedLiteral) resource)
+					.getDataType().getUnicodeString()));
+		} else if (resource instanceof PlainLiteral) {
+			value = doc.createElement("literal");
+			value.appendChild(doc.createTextNode(((PlainLiteral) resource)
+					.getLexicalForm()));
+			Language lang = ((PlainLiteral) resource).getLanguage();
+			if (lang != null) {
+				value.setAttribute("xml:lang", (lang.toString()));
+			}
+		} else {
+			value = doc.createElement("bnode");
+			value.appendChild(doc.createTextNode("/"));
+		}
+		return value;
+	}
+
+	/**
+	 * Helper: creates results element from ResultSet
+	 *
+	 */
+	private void createResultElement(SolutionMapping solutionMap, Element results, Document
doc) {
+		Set<Variable> keys = solutionMap.keySet();
+		Element result = doc.createElement("result");
+		results.appendChild(result);
+		for (Variable key : keys) {
+			Element bindingElement = doc.createElement("binding");
+			bindingElement.setAttribute("name", key.getName());
+			bindingElement.appendChild(createValueElement(
+					(Resource) solutionMap.get(key), doc));
+			result.appendChild(bindingElement);
+		}
+	}
+
+	private void createVariable(SolutionMapping solutionMap, Element head, Document doc) {
+		Set<Variable> keys = solutionMap.keySet();
+		for (Variable key : keys) {
+			Element varElement = doc.createElement("variable");
+			varElement.setAttribute("name", key.getName());
+			head.appendChild(varElement);
+		}
+	}
+}



Mime
View raw message