This is an automated email from the ASF dual-hosted git repository. hasan pushed a commit to branch reunited in repository https://gitbox.apache.org/repos/asf/clerezza.git
commit b10c9a18f3b898d6a9bc491575d94df86b181680 Author: Hasan <[email protected]> AuthorDate: Fri Feb 15 21:38:11 2019 +0100 CLEREZZA-1036: Refactor jaxrs.rdf.providers to use api and api.impl module --- jaxrs.rdf.providers/pom.xml | 81 +++-- .../jaxrs/rdf/providers/GraphNodeWriter.java | 84 +++-- .../clerezza/jaxrs/rdf/providers/GraphReader.java | 58 ++- .../clerezza/jaxrs/rdf/providers/GraphWriter.java | 67 ++-- .../jaxrs/rdf/providers/ImmutableGraphReader.java | 61 ++-- .../providers/ResultSetCsvMessageBodyWriter.java | 386 ++++++++++---------- .../providers/ResultSetJsonMessageBodyWriter.java | 258 +++++++------ .../providers/ResultSetTsvMessageBodyWriter.java | 400 ++++++++++----------- .../providers/ResultSetXmlMessageBodyWriter.java | 328 +++++++++-------- 9 files changed, 846 insertions(+), 877 deletions(-) diff --git a/jaxrs.rdf.providers/pom.xml b/jaxrs.rdf.providers/pom.xml index ac431c3..4156840 100644 --- a/jaxrs.rdf.providers/pom.xml +++ b/jaxrs.rdf.providers/pom.xml @@ -1,55 +1,57 @@ -<?xml version="1.0" encoding="UTF-8" standalone="no"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> +<?xml version="1.0" encoding="UTF-8" standalone="no"?> <!-- + 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 - 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. + 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. --> - - <modelVersion>4.0.0</modelVersion> +<project xmlns="http://maven.apache.org/POM/4.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>clerezza</artifactId> <groupId>org.apache.clerezza</groupId> <version>8-SNAPSHOT</version> - <relativePath>../parent</relativePath> + <relativePath>../parent/pom.xml</relativePath> </parent> - <groupId>org.apache.clerezza</groupId> + <modelVersion>4.0.0</modelVersion> + <artifactId>jaxrs.rdf.providers</artifactId> <packaging>bundle</packaging> - <version>1.0.1-SNAPSHOT</version> + <version>8-SNAPSHOT</version> <name>Clerezza - JAX-RS MessageBodyProviders for RDF</name> - <build> - <plugins> - <plugin> - <groupId>org.apache.felix</groupId> - <artifactId>maven-scr-plugin</artifactId> - </plugin> - </plugins> - </build> + <dependencies> <dependency> <groupId>org.apache.clerezza</groupId> - <artifactId>rdf.core</artifactId> - <version>1.0.1</version> + <artifactId>api</artifactId> + <version>8-SNAPSHOT</version> </dependency> <dependency> <groupId>org.apache.clerezza</groupId> - <artifactId>rdf.utils</artifactId> - <version>1.0.0</version> + <artifactId>api.impl</artifactId> + <version>8-SNAPSHOT</version> + </dependency> + <dependency> + <groupId>org.apache.clerezza</groupId> + <artifactId>representation</artifactId> + <version>8-SNAPSHOT</version> + </dependency> + <dependency> + <groupId>org.apache.clerezza</groupId> + <artifactId>api.utils</artifactId> + <version>8-SNAPSHOT</version> </dependency> <dependency> <groupId>com.googlecode.json-simple</groupId> @@ -65,4 +67,13 @@ <artifactId>org.osgi.service.component.annotations</artifactId> </dependency> </dependencies> -</project> + + <build> + <plugins> + <plugin> + <groupId>org.apache.felix</groupId> + <artifactId>maven-scr-plugin</artifactId> + </plugin> + </plugins> + </build> +</project> \ No newline at end of file diff --git a/jaxrs.rdf.providers/src/main/java/org/apache/clerezza/jaxrs/rdf/providers/GraphNodeWriter.java b/jaxrs.rdf.providers/src/main/java/org/apache/clerezza/jaxrs/rdf/providers/GraphNodeWriter.java index 4455ba0..27f5f7b 100644 --- a/jaxrs.rdf.providers/src/main/java/org/apache/clerezza/jaxrs/rdf/providers/GraphNodeWriter.java +++ b/jaxrs.rdf.providers/src/main/java/org/apache/clerezza/jaxrs/rdf/providers/GraphNodeWriter.java @@ -1,34 +1,32 @@ /* - * 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 + * 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. + * 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.rdf.providers; -import org.apache.clerezza.rdf.core.serializedform.Serializer; -import org.apache.clerezza.rdf.core.serializedform.SupportedFormat; - -import java.io.IOException; -import java.io.OutputStream; -import java.lang.annotation.Annotation; -import java.lang.reflect.Type; -import java.util.HashSet; -import java.util.List; -import java.util.Objects; -import java.util.Set; +import org.apache.clerezza.api.Graph; +import org.apache.clerezza.api.IRI; +import org.apache.clerezza.api.RDFTerm; +import org.apache.clerezza.api.Triple; +import org.apache.clerezza.api.impl.graph.SimpleGraph; +import org.apache.clerezza.api.utils.GraphNode; +import org.apache.clerezza.representation.Serializer; +import org.apache.clerezza.representation.SupportedFormat; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.Reference; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; @@ -38,38 +36,36 @@ import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.UriInfo; import javax.ws.rs.ext.MessageBodyWriter; import javax.ws.rs.ext.Provider; - -import org.apache.clerezza.commons.rdf.RDFTerm; -import org.apache.clerezza.commons.rdf.Triple; -import org.apache.clerezza.commons.rdf.Graph; -import org.apache.clerezza.commons.rdf.IRI; -import org.apache.clerezza.commons.rdf.impl.utils.simple.SimpleGraph; -import org.apache.clerezza.rdf.utils.GraphNode; -import org.osgi.service.component.annotations.Component; -import org.osgi.service.component.annotations.Reference; +import java.io.IOException; +import java.io.OutputStream; +import java.lang.annotation.Annotation; +import java.lang.reflect.Type; +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.Set; /** * By default this returns a serialization of the context of the GraphNode. - * + * <p> * The expansion can be widened by using the query parameters xPropObj and * xProSubj. These parameters specify property uris (both parameters might be * repeated). For the specified properties their objects respectively subjects * are expanded as if they were bnodes. * - * * @author reto */ -@Component(service=Object.class, property={"javax.ws.rs=true"}) +@Component(service = Object.class, property = {"javax.ws.rs=true"}) @Provider @Produces({SupportedFormat.N3, SupportedFormat.N_TRIPLE, - SupportedFormat.RDF_XML, SupportedFormat.TURTLE, - SupportedFormat.X_TURTLE, SupportedFormat.RDF_JSON}) + SupportedFormat.RDF_XML, SupportedFormat.TURTLE, + SupportedFormat.X_TURTLE, SupportedFormat.RDF_JSON}) public class GraphNodeWriter implements MessageBodyWriter<GraphNode> { public static final String OBJ_EXP_PARAM = "xPropObj"; public static final String SUBJ_EXP_PARAM = "xPropSubj"; - + private Serializer serializer; private UriInfo uriInfo; @@ -86,21 +82,21 @@ public class GraphNodeWriter implements MessageBodyWriter<GraphNode> { @Override public boolean isWriteable(Class<?> type, Type genericType, - Annotation[] annotations, MediaType mediaType) { + Annotation[] annotations, MediaType mediaType) { return GraphNode.class.isAssignableFrom(type); } @Override public long getSize(GraphNode n, Class<?> type, Type genericType, - Annotation[] annotations, MediaType mediaType) { + Annotation[] annotations, MediaType mediaType) { return -1; } @Override public void writeTo(GraphNode node, Class<?> type, Type genericType, - Annotation[] annotations, MediaType mediaType, - MultivaluedMap<String, Object> httpHeaders, - OutputStream entityStream) throws IOException, WebApplicationException { + Annotation[] annotations, MediaType mediaType, + MultivaluedMap<String, Object> httpHeaders, + OutputStream entityStream) throws IOException, WebApplicationException { serializer.serialize(entityStream, getExpandedContext(node), mediaType.toString()); } diff --git a/jaxrs.rdf.providers/src/main/java/org/apache/clerezza/jaxrs/rdf/providers/GraphReader.java b/jaxrs.rdf.providers/src/main/java/org/apache/clerezza/jaxrs/rdf/providers/GraphReader.java index d569c7b..dcf58bc 100644 --- a/jaxrs.rdf.providers/src/main/java/org/apache/clerezza/jaxrs/rdf/providers/GraphReader.java +++ b/jaxrs.rdf.providers/src/main/java/org/apache/clerezza/jaxrs/rdf/providers/GraphReader.java @@ -1,48 +1,46 @@ /* - * 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 + * 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. + * 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.rdf.providers; -import java.io.IOException; -import java.io.InputStream; -import java.lang.annotation.Annotation; -import java.lang.reflect.Type; -import java.util.Objects; +import org.apache.clerezza.api.Graph; +import org.apache.clerezza.api.impl.graph.SimpleGraph; +import org.apache.clerezza.representation.Parser; +import org.apache.clerezza.representation.SupportedFormat; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.Reference; + import javax.ws.rs.Consumes; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.MessageBodyReader; import javax.ws.rs.ext.Provider; +import java.io.IOException; +import java.io.InputStream; +import java.lang.annotation.Annotation; +import java.lang.reflect.Type; +import java.util.Objects; -import org.apache.clerezza.commons.rdf.Graph; -import org.apache.clerezza.commons.rdf.impl.utils.simple.SimpleGraph; -import org.apache.clerezza.rdf.core.serializedform.Parser; -import org.apache.clerezza.rdf.core.serializedform.SupportedFormat; -import org.osgi.service.component.annotations.Component; -import org.osgi.service.component.annotations.Reference; - - -@Component(service=Object.class, property={"javax.ws.rs=true"}) +@Component(service = Object.class, property = {"javax.ws.rs=true"}) @Provider @Consumes({SupportedFormat.N3, SupportedFormat.N_TRIPLE, - SupportedFormat.RDF_XML, SupportedFormat.TURTLE, - SupportedFormat.X_TURTLE, SupportedFormat.RDF_JSON}) + SupportedFormat.RDF_XML, SupportedFormat.TURTLE, + SupportedFormat.X_TURTLE, SupportedFormat.RDF_JSON}) public class GraphReader implements MessageBodyReader<Graph> { private Parser parser; @@ -60,7 +58,7 @@ public class GraphReader implements MessageBodyReader<Graph> { @Override public boolean isReadable(Class<?> type, Type genericType, - Annotation[] annotations, MediaType mediaType) { + Annotation[] annotations, MediaType mediaType) { return type.isAssignableFrom(Graph.class); } diff --git a/jaxrs.rdf.providers/src/main/java/org/apache/clerezza/jaxrs/rdf/providers/GraphWriter.java b/jaxrs.rdf.providers/src/main/java/org/apache/clerezza/jaxrs/rdf/providers/GraphWriter.java index 6f54992..a9842f3 100644 --- a/jaxrs.rdf.providers/src/main/java/org/apache/clerezza/jaxrs/rdf/providers/GraphWriter.java +++ b/jaxrs.rdf.providers/src/main/java/org/apache/clerezza/jaxrs/rdf/providers/GraphWriter.java @@ -1,48 +1,45 @@ /* - * 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 + * 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. + * 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.rdf.providers; +import org.apache.clerezza.api.Graph; +import org.apache.clerezza.representation.Serializer; +import org.apache.clerezza.representation.SupportedFormat; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.Reference; -import java.io.IOException; -import java.io.OutputStream; -import java.lang.annotation.Annotation; -import java.lang.reflect.Type; -import java.util.Objects; 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 java.io.IOException; +import java.io.OutputStream; +import java.lang.annotation.Annotation; +import java.lang.reflect.Type; +import java.util.Objects; -import org.apache.clerezza.commons.rdf.Graph; -import org.apache.clerezza.rdf.core.serializedform.Serializer; -import org.apache.clerezza.rdf.core.serializedform.SupportedFormat; -import org.osgi.service.component.annotations.Component; -import org.osgi.service.component.annotations.Reference; - - -@Component(service=Object.class, property={"javax.ws.rs=true"}) +@Component(service = Object.class, property = {"javax.ws.rs=true"}) @Provider @Produces({SupportedFormat.N3, SupportedFormat.N_TRIPLE, - SupportedFormat.RDF_XML, SupportedFormat.TURTLE, - SupportedFormat.X_TURTLE, SupportedFormat.RDF_JSON}) + SupportedFormat.RDF_XML, SupportedFormat.TURTLE, + SupportedFormat.X_TURTLE, SupportedFormat.RDF_JSON}) public class GraphWriter implements MessageBodyWriter<Graph> { private Serializer serializer; @@ -59,22 +56,22 @@ public class GraphWriter implements MessageBodyWriter<Graph> { } @Override - public boolean isWriteable(Class<?> type, Type genericType, - Annotation[] annotations, MediaType mediaType) { + public boolean isWriteable(Class<?> type, Type genericType, + Annotation[] annotations, MediaType mediaType) { return Graph.class.isAssignableFrom(type); } @Override - public long getSize(Graph t, Class<?> type, Type genericType, - Annotation[] annotations, MediaType mediaType) { + public long getSize(Graph t, Class<?> type, Type genericType, + Annotation[] annotations, MediaType mediaType) { return -1; } @Override public void writeTo(Graph t, Class<?> type, Type genericType, - Annotation[] annotations, MediaType mediaType, - MultivaluedMap<String, Object> httpHeaders, - OutputStream entityStream) throws IOException, WebApplicationException { + Annotation[] annotations, MediaType mediaType, + MultivaluedMap<String, Object> httpHeaders, + OutputStream entityStream) throws IOException, WebApplicationException { serializer.serialize(entityStream, t, mediaType.toString()); } } diff --git a/jaxrs.rdf.providers/src/main/java/org/apache/clerezza/jaxrs/rdf/providers/ImmutableGraphReader.java b/jaxrs.rdf.providers/src/main/java/org/apache/clerezza/jaxrs/rdf/providers/ImmutableGraphReader.java index eb45e52..45c28e0 100644 --- a/jaxrs.rdf.providers/src/main/java/org/apache/clerezza/jaxrs/rdf/providers/ImmutableGraphReader.java +++ b/jaxrs.rdf.providers/src/main/java/org/apache/clerezza/jaxrs/rdf/providers/ImmutableGraphReader.java @@ -1,46 +1,45 @@ /* - * 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 + * 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. + * 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.rdf.providers; -import java.io.IOException; -import java.io.InputStream; -import java.lang.annotation.Annotation; -import java.lang.reflect.Type; -import java.util.Objects; +import org.apache.clerezza.api.ImmutableGraph; +import org.apache.clerezza.representation.Parser; +import org.apache.clerezza.representation.SupportedFormat; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.Reference; + import javax.ws.rs.Consumes; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.MessageBodyReader; import javax.ws.rs.ext.Provider; -import org.apache.clerezza.rdf.core.serializedform.Parser; -import org.apache.clerezza.rdf.core.serializedform.SupportedFormat; -import org.apache.clerezza.commons.rdf.ImmutableGraph; -import org.osgi.service.component.annotations.Component; -import org.osgi.service.component.annotations.Reference; - +import java.io.IOException; +import java.io.InputStream; +import java.lang.annotation.Annotation; +import java.lang.reflect.Type; +import java.util.Objects; -@Component(service=Object.class, property={"javax.ws.rs=true"}) +@Component(service = Object.class, property = {"javax.ws.rs=true"}) @Provider @Consumes({SupportedFormat.N3, SupportedFormat.N_TRIPLE, - SupportedFormat.RDF_XML, SupportedFormat.TURTLE, - SupportedFormat.X_TURTLE, SupportedFormat.RDF_JSON}) + SupportedFormat.RDF_XML, SupportedFormat.TURTLE, + SupportedFormat.X_TURTLE, SupportedFormat.RDF_JSON}) public class ImmutableGraphReader implements MessageBodyReader<ImmutableGraph> { private Parser parser; @@ -58,15 +57,15 @@ public class ImmutableGraphReader implements MessageBodyReader<ImmutableGraph> { @Override public boolean isReadable(Class<?> type, Type genericType, - Annotation[] annotations, MediaType mediaType) { + Annotation[] annotations, MediaType mediaType) { return type.isAssignableFrom(ImmutableGraph.class); } @Override public ImmutableGraph readFrom(Class<ImmutableGraph> type, Type genericType, - Annotation[] annotations, MediaType mediaType, - MultivaluedMap<String, String> httpHeaders, - InputStream entityStream) + Annotation[] annotations, MediaType mediaType, + MultivaluedMap<String, String> httpHeaders, + InputStream entityStream) throws IOException, WebApplicationException { return parser.parse(entityStream, mediaType.toString()); } diff --git a/jaxrs.rdf.providers/src/main/java/org/apache/clerezza/jaxrs/sparql/providers/ResultSetCsvMessageBodyWriter.java b/jaxrs.rdf.providers/src/main/java/org/apache/clerezza/jaxrs/sparql/providers/ResultSetCsvMessageBodyWriter.java index 0bd3974..c215020 100644 --- a/jaxrs.rdf.providers/src/main/java/org/apache/clerezza/jaxrs/sparql/providers/ResultSetCsvMessageBodyWriter.java +++ b/jaxrs.rdf.providers/src/main/java/org/apache/clerezza/jaxrs/sparql/providers/ResultSetCsvMessageBodyWriter.java @@ -1,29 +1,31 @@ /* - * 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. - */ + * 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.io.UnsupportedEncodingException; -import java.lang.annotation.Annotation; -import java.lang.reflect.Type; -import java.util.List; +import org.apache.clerezza.api.BlankNode; +import org.apache.clerezza.api.IRI; +import org.apache.clerezza.api.Literal; +import org.apache.clerezza.api.RDFTerm; +import org.apache.clerezza.sparql.ResultSet; +import org.apache.clerezza.sparql.SolutionMapping; +import org.osgi.service.component.annotations.Component; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; @@ -31,196 +33,184 @@ 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.commons.rdf.BlankNode; -import org.apache.clerezza.commons.rdf.RDFTerm; -import org.apache.clerezza.commons.rdf.IRI; -import org.apache.clerezza.rdf.core.sparql.ResultSet; -import org.apache.clerezza.rdf.core.sparql.SolutionMapping; -import org.apache.clerezza.commons.rdf.Literal; -import org.osgi.service.component.annotations.Component; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import java.io.IOException; +import java.io.OutputStream; +import java.io.UnsupportedEncodingException; +import java.lang.annotation.Annotation; +import java.lang.reflect.Type; +import java.util.List; /** * MessageBodyWirter for <code>ResultSet</code>. Resulting output is csv and * conforms to: * http://www.w3.org/TR/2013/REC-sparql11-results-csv-tsv-20130321/#csv - * + * <p> * Also see: http://tools.ietf.org/html/rfc4180 - * + * * @author misl */ -@Component(service=Object.class, property={"javax.ws.rs=true"}) -@Produces( { "text/csv" } ) +@Component(service = Object.class, property = {"javax.ws.rs=true"}) +@Produces({"text/csv"}) @Provider public class ResultSetCsvMessageBodyWriter implements MessageBodyWriter<ResultSet> { - private static final Logger logger = LoggerFactory - .getLogger( ResultSetCsvMessageBodyWriter.class ); - - private String textEncoding = "UTF-8"; - private byte[] separator; - - public ResultSetCsvMessageBodyWriter() { - try { - buildSeparatorConformEncoding( textEncoding ); - } catch( UnsupportedEncodingException e ) { - logger.error( "Developer error", e ); + private static final Logger logger = LoggerFactory + .getLogger(ResultSetCsvMessageBodyWriter.class); + + private String textEncoding = "UTF-8"; + private byte[] separator; + + public ResultSetCsvMessageBodyWriter() { + try { + buildSeparatorConformEncoding(textEncoding); + } catch (UnsupportedEncodingException e) { + logger.error("Developer error", e); + } } - } - - // -------------------------------------------------------------------------- - // Implementing MessageBodyWriter - // -------------------------------------------------------------------------- - - @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 { - - // According to spec header is mandatory. - writeCsvHeader( entityStream, resultSet.getResultVars() ); - while( resultSet.hasNext() ) { - writeCsvLine( entityStream, resultSet.getResultVars(), resultSet.next() ); + + // -------------------------------------------------------------------------- + // Implementing MessageBodyWriter + // -------------------------------------------------------------------------- + + @Override + public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, + MediaType mediaType) { + return ResultSet.class.isAssignableFrom(type); } - } - - // -------------------------------------------------------------------------- - // Public interface - // -------------------------------------------------------------------------- - - /** - * Sets the text encoding for the resource. This setting must only used - * if the resource response represents text. - * - * @param textEncoding - * character encoding of text body - * @throws UnsupportedEncodingException when the given encoding is not supported. - */ - public void setTextEncoding(String textEncoding) throws UnsupportedEncodingException { - buildSeparatorConformEncoding( textEncoding ); - this.textEncoding = textEncoding; - } - - /** - * @return text encoding for resource - */ - protected String getTextEncoding() { - return textEncoding; - } - - // -------------------------------------------------------------------------- - // Private methods - // -------------------------------------------------------------------------- - - /** - * Builds the column separator according to the given text encoding. - * - * @param encoding the text encoding to be used. - * @throws UnsupportedEncodingException when the given encoding is not supported. - */ - private void buildSeparatorConformEncoding( String encoding ) throws UnsupportedEncodingException { - separator = ",".getBytes( encoding ); - } - - /** - * Write resultset header to the given output stream. - * - * @param outputStream - * stream to write to. - * @param headers - * the headers to write. - * @throws IOException - */ - private void writeCsvHeader( OutputStream outputStream, List<String> headers ) throws IOException { - boolean first = true; - for( String header : headers ) { - if( !first ) { - outputStream.write( separator ); - } - writeEscaped( outputStream, header ); - first = false; + + @Override + public long getSize(ResultSet t, Class<?> type, Type genericType, Annotation[] annotations, + MediaType mediaType) { + return -1; } - outputStream.write( "\n".getBytes( textEncoding ) ); - } - - /** - * Write a single csv line using the given line data. - * - * @param outputStream - * stream to write to. - * @param headers - * the headers to write line data for. - * @param lineData - * the line data to write. - * @throws IOException - */ - private void writeCsvLine( OutputStream outputStream, List<String> headers, - SolutionMapping lineData ) throws IOException { - boolean first = true; - for( String header : headers ) { - if( !first ) { - outputStream.write( separator ); - } - RDFTerm resource = lineData.get( header ); - if( resource != null ) { - writeEscaped( outputStream, getResourceValue( resource ) ); - } - first = false; + + @Override + public void writeTo(ResultSet resultSet, Class<?> type, Type genericType, + Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, + OutputStream entityStream) throws IOException, WebApplicationException { + + // According to spec header is mandatory. + writeCsvHeader(entityStream, resultSet.getResultVars()); + while (resultSet.hasNext()) { + writeCsvLine(entityStream, resultSet.getResultVars(), resultSet.next()); + } } - outputStream.write( "\n".getBytes( textEncoding ) ); - } - - /** - * Helper to get the proper string representation for the given RDFTerm. - */ - private String getResourceValue( RDFTerm resource ) { - StringBuilder value = new StringBuilder(); - if( resource instanceof IRI ) { - value.append(((IRI) resource).getUnicodeString() ); - } else if( resource instanceof Literal ) { - value.append( ((Literal) resource).getLexicalForm() ); - } else if( resource instanceof BlankNode ) { - value.append( "/" ); - } else { - value.append( resource.toString() ); + + // -------------------------------------------------------------------------- + // Public interface + // -------------------------------------------------------------------------- + + /** + * Sets the text encoding for the resource. This setting must only used + * if the resource response represents text. + * + * @param textEncoding character encoding of text body + * @throws UnsupportedEncodingException when the given encoding is not supported. + */ + public void setTextEncoding(String textEncoding) throws UnsupportedEncodingException { + buildSeparatorConformEncoding(textEncoding); + this.textEncoding = textEncoding; } - return value.toString(); - } - - /** - * Write the given string to the output stream and escape the output where - * necessary. - * - * @param outputStream - * stream to write to. - * @param text - * the text to write. - * @throws IOException - */ - private void writeEscaped( OutputStream outputStream, String text ) throws IOException { - String line = text; - if( text.contains( "\r" ) || text.contains( "\n" ) || text.contains( "," ) - || text.contains( "\"" ) ) { - StringBuilder builder = new StringBuilder(); - builder.append( '"' ); - builder.append( text.replaceAll( "\"", "\"\"" ) ); - builder.append( '"' ); - line = builder.toString(); + + /** + * @return text encoding for resource + */ + protected String getTextEncoding() { + return textEncoding; + } + + // -------------------------------------------------------------------------- + // Private methods + // -------------------------------------------------------------------------- + + /** + * Builds the column separator according to the given text encoding. + * + * @param encoding the text encoding to be used. + * @throws UnsupportedEncodingException when the given encoding is not supported. + */ + private void buildSeparatorConformEncoding(String encoding) throws UnsupportedEncodingException { + separator = ",".getBytes(encoding); + } + + /** + * Write resultset header to the given output stream. + * + * @param outputStream stream to write to. + * @param headers the headers to write. + * @throws IOException + */ + private void writeCsvHeader(OutputStream outputStream, List<String> headers) throws IOException { + boolean first = true; + for (String header : headers) { + if (!first) { + outputStream.write(separator); + } + writeEscaped(outputStream, header); + first = false; + } + outputStream.write("\n".getBytes(textEncoding)); + } + + /** + * Write a single csv line using the given line data. + * + * @param outputStream stream to write to. + * @param headers the headers to write line data for. + * @param lineData the line data to write. + * @throws IOException + */ + private void writeCsvLine(OutputStream outputStream, List<String> headers, + SolutionMapping lineData) throws IOException { + boolean first = true; + for (String header : headers) { + if (!first) { + outputStream.write(separator); + } + RDFTerm resource = lineData.get(header); + if (resource != null) { + writeEscaped(outputStream, getResourceValue(resource)); + } + first = false; + } + outputStream.write("\n".getBytes(textEncoding)); + } + + /** + * Helper to get the proper string representation for the given RDFTerm. + */ + private String getResourceValue(RDFTerm resource) { + StringBuilder value = new StringBuilder(); + if (resource instanceof IRI) { + value.append(((IRI) resource).getUnicodeString()); + } else if (resource instanceof Literal) { + value.append(((Literal) resource).getLexicalForm()); + } else if (resource instanceof BlankNode) { + value.append("/"); + } else { + value.append(resource.toString()); + } + return value.toString(); + } + + /** + * Write the given string to the output stream and escape the output where + * necessary. + * + * @param outputStream stream to write to. + * @param text the text to write. + * @throws IOException + */ + private void writeEscaped(OutputStream outputStream, String text) throws IOException { + String line = text; + if (text.contains("\r") || text.contains("\n") || text.contains(",") + || text.contains("\"")) { + StringBuilder builder = new StringBuilder(); + builder.append('"'); + builder.append(text.replaceAll("\"", "\"\"")); + builder.append('"'); + line = builder.toString(); + } + outputStream.write(line.getBytes(textEncoding)); } - outputStream.write( line.getBytes( textEncoding ) ); - } } diff --git a/jaxrs.rdf.providers/src/main/java/org/apache/clerezza/jaxrs/sparql/providers/ResultSetJsonMessageBodyWriter.java b/jaxrs.rdf.providers/src/main/java/org/apache/clerezza/jaxrs/sparql/providers/ResultSetJsonMessageBodyWriter.java index c7a2c0c..0b71d2d 100644 --- a/jaxrs.rdf.providers/src/main/java/org/apache/clerezza/jaxrs/sparql/providers/ResultSetJsonMessageBodyWriter.java +++ b/jaxrs.rdf.providers/src/main/java/org/apache/clerezza/jaxrs/sparql/providers/ResultSetJsonMessageBodyWriter.java @@ -1,29 +1,31 @@ /* - * 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. - */ + * 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.List; -import java.util.Set; +import org.apache.clerezza.api.*; +import org.apache.clerezza.sparql.ResultSet; +import org.apache.clerezza.sparql.SolutionMapping; +import org.apache.clerezza.sparql.query.Variable; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.osgi.service.component.annotations.Component; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; @@ -31,135 +33,125 @@ 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.commons.rdf.BlankNode; -import org.apache.clerezza.commons.rdf.Language; -import org.apache.clerezza.commons.rdf.RDFTerm; -import org.apache.clerezza.commons.rdf.IRI; -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.clerezza.commons.rdf.Literal; -import org.osgi.service.component.annotations.Component; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import java.io.IOException; +import java.io.OutputStream; +import java.lang.annotation.Annotation; +import java.lang.reflect.Type; +import java.util.List; +import java.util.Set; /** * 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={"javax.ws.rs=true"}) +@Component(service = Object.class, property = {"javax.ws.rs=true"}) @Produces({"application/json", "application/sparql-results+json"}) @Provider @SuppressWarnings("unchecked") public class ResultSetJsonMessageBodyWriter implements MessageBodyWriter<ResultSet> { - final Logger logger = LoggerFactory.getLogger(ResultSetJsonMessageBodyWriter.class); + 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 boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, - MediaType mediaType) { - return ResultSet.class.isAssignableFrom(type); - } + @Override + public void writeTo(ResultSet resultSet, Class<?> type, Type genericType, + Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, + Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { - @Override - public long getSize(ResultSet t, Class<?> type, Type genericType, - Annotation[] annotations, MediaType mediaType) { - return -1; - } + JSONObject json = toJsonSource(resultSet); + entityStream.write(json.toJSONString().getBytes("UTF-8")); + } - @Override - public void writeTo(ResultSet resultSet, Class<?> type, Type genericType, - Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, - Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { + /** + * 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); + createVariables(queryResult.getResultVars(), head); - JSONObject json = toJsonSource(resultSet); - entityStream.write(json.toJSONString().getBytes("UTF-8")); - } + JSONObject results = new JSONObject(); + root.put("results", results); - /** - * 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); - createVariables(queryResult.getResultVars(), head); - - JSONObject results = new JSONObject(); - root.put("results", results); - - JSONArray bindings = null; - while (queryResult.hasNext()) { - if (bindings == null) { - bindings = new JSONArray(); - results.put("bindings", bindings); - } - bindings.add(createResult(queryResult.next())); - } + JSONArray bindings = null; + while (queryResult.hasNext()) { + if (bindings == null) { + bindings = new JSONArray(); + results.put("bindings", bindings); + } + bindings.add(createResult(queryResult.next())); + } - return root; - } + return root; + } - /** - * Helper: creates value element from {@link RDFTerm} depending on its - * class - * - */ - private JSONObject createResultElement(RDFTerm resource) { - JSONObject element = new JSONObject(); - if (resource instanceof IRI) { - element.put("type", "uri"); - element.put("value", IRI.class.cast(resource).getUnicodeString()); - } else if (resource instanceof Literal) { - element.put("type", "literal"); - element.put("value", Literal.class.cast(resource).getLexicalForm()); - Language lang = Literal.class.cast(resource).getLanguage(); - if (lang != null) { - element.put("xml:lang", lang.toString()); - } - } else if (resource instanceof Literal) { - element.put("type", "typed-literal"); - element.put("datatype", Literal.class.cast(resource).getDataType().getUnicodeString()); - element.put("value", Literal.class.cast(resource).getLexicalForm()); - } else if (resource instanceof BlankNode) { - element.put("type", "bnode"); - element.put("value", "/"); - } else { - element = null; - } - return element; - } + /** + * Helper: creates value element from {@link RDFTerm} depending on its + * class + */ + private JSONObject createResultElement(RDFTerm resource) { + JSONObject element = new JSONObject(); + if (resource instanceof IRI) { + element.put("type", "uri"); + element.put("value", IRI.class.cast(resource).getUnicodeString()); + } else if (resource instanceof Literal) { + element.put("type", "literal"); + element.put("value", Literal.class.cast(resource).getLexicalForm()); + Language lang = Literal.class.cast(resource).getLanguage(); + if (lang != null) { + element.put("xml:lang", lang.toString()); + } + } else if (resource instanceof Literal) { + element.put("type", "typed-literal"); + element.put("datatype", Literal.class.cast(resource).getDataType().getUnicodeString()); + element.put("value", Literal.class.cast(resource).getLexicalForm()); + } else if (resource instanceof BlankNode) { + 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((RDFTerm) solutionMap.get(key))); - } - return result; - } + /** + * 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((RDFTerm) solutionMap.get(key))); + } + return result; + } - private void createVariables(List<String> variables, JSONObject head) { - JSONArray vars = null; - for (String variable : variables) { - if (vars == null) { - vars = new JSONArray(); - head.put("vars", vars); - } - vars.add(variable); - } - } + private void createVariables(List<String> variables, JSONObject head) { + JSONArray vars = null; + for (String variable : variables) { + if (vars == null) { + vars = new JSONArray(); + head.put("vars", vars); + } + vars.add(variable); + } + } } diff --git a/jaxrs.rdf.providers/src/main/java/org/apache/clerezza/jaxrs/sparql/providers/ResultSetTsvMessageBodyWriter.java b/jaxrs.rdf.providers/src/main/java/org/apache/clerezza/jaxrs/sparql/providers/ResultSetTsvMessageBodyWriter.java index bd53d3c..d4b4db0 100644 --- a/jaxrs.rdf.providers/src/main/java/org/apache/clerezza/jaxrs/sparql/providers/ResultSetTsvMessageBodyWriter.java +++ b/jaxrs.rdf.providers/src/main/java/org/apache/clerezza/jaxrs/sparql/providers/ResultSetTsvMessageBodyWriter.java @@ -1,29 +1,31 @@ /* - * 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. - */ + * 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.io.UnsupportedEncodingException; -import java.lang.annotation.Annotation; -import java.lang.reflect.Type; -import java.util.List; +import org.apache.clerezza.api.BlankNode; +import org.apache.clerezza.api.IRI; +import org.apache.clerezza.api.Literal; +import org.apache.clerezza.api.RDFTerm; +import org.apache.clerezza.sparql.ResultSet; +import org.apache.clerezza.sparql.SolutionMapping; +import org.osgi.service.component.annotations.Component; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; @@ -31,207 +33,195 @@ 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.commons.rdf.BlankNode; -import org.apache.clerezza.commons.rdf.RDFTerm; -import org.apache.clerezza.commons.rdf.IRI; -import org.apache.clerezza.rdf.core.sparql.ResultSet; -import org.apache.clerezza.rdf.core.sparql.SolutionMapping; -import org.apache.clerezza.commons.rdf.Literal; -import org.osgi.service.component.annotations.Component; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import java.io.IOException; +import java.io.OutputStream; +import java.io.UnsupportedEncodingException; +import java.lang.annotation.Annotation; +import java.lang.reflect.Type; +import java.util.List; /** * MessageBodyWirter for <code>ResultSet</code>. Resulting output is tsv and * conforms to: * http://www.w3.org/TR/2013/REC-sparql11-results-csv-tsv-20130321/#tsv - * + * <p> * Also see: http://www.iana.org/assignments/media-types/text/tab-separated-values - * + * * @author misl */ -@Component(service=Object.class, property={"javax.ws.rs=true"}) -@Produces( { "text/tab-separated-values" } ) +@Component(service = Object.class, property = {"javax.ws.rs=true"}) +@Produces({"text/tab-separated-values"}) @Provider public class ResultSetTsvMessageBodyWriter implements MessageBodyWriter<ResultSet> { - private static final Logger logger = LoggerFactory - .getLogger( ResultSetTsvMessageBodyWriter.class ); - - private String textEncoding = "UTF-8"; - private byte[] separator; - - public ResultSetTsvMessageBodyWriter() { - try { - buildSeparatorConformEncoding( textEncoding ); - } catch( UnsupportedEncodingException e ) { - logger.error( "Developer error", e ); + private static final Logger logger = LoggerFactory + .getLogger(ResultSetTsvMessageBodyWriter.class); + + private String textEncoding = "UTF-8"; + private byte[] separator; + + public ResultSetTsvMessageBodyWriter() { + try { + buildSeparatorConformEncoding(textEncoding); + } catch (UnsupportedEncodingException e) { + logger.error("Developer error", e); + } + } + + // -------------------------------------------------------------------------- + // Implementing MessageBodyWriter + // -------------------------------------------------------------------------- + + @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; } - } - - // -------------------------------------------------------------------------- - // Implementing MessageBodyWriter - // -------------------------------------------------------------------------- - - @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 { - - // According to spec header is mandatory. - writeTsvHeader( entityStream, resultSet.getResultVars() ); - while( resultSet.hasNext() ) { - writeTsvLine( entityStream, resultSet.getResultVars(), resultSet.next() ); + + @Override + public void writeTo(ResultSet resultSet, Class<?> type, Type genericType, + Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, + OutputStream entityStream) throws IOException, WebApplicationException { + + // According to spec header is mandatory. + writeTsvHeader(entityStream, resultSet.getResultVars()); + while (resultSet.hasNext()) { + writeTsvLine(entityStream, resultSet.getResultVars(), resultSet.next()); + } } - } - - // -------------------------------------------------------------------------- - // Public interface - // -------------------------------------------------------------------------- - - /** - * Sets the text encoding for the resource. This setting must only used - * if the resource response represents text. - * - * @param textEncoding - * character encoding of text body - * @throws UnsupportedEncodingException when the given encoding is not supported. - */ - public void setTextEncoding(String textEncoding) throws UnsupportedEncodingException { - buildSeparatorConformEncoding( textEncoding ); - this.textEncoding = textEncoding; - } - - /** - * @return text encoding for resource - */ - protected String getTextEncoding() { - return textEncoding; - } - - // -------------------------------------------------------------------------- - // Private methods - // -------------------------------------------------------------------------- - - /** - * Builds the column separator according to the given text encoding. - * - * @param encoding the text encoding to be used. - * @throws UnsupportedEncodingException when the given encoding is not supported. - */ - private void buildSeparatorConformEncoding( String encoding ) throws UnsupportedEncodingException { - separator = ",".getBytes( encoding ); - } - - /** - * Write resultset header to the given output stream. - * - * @param outputStream - * stream to write to. - * @param headers - * the headers to write. - * @throws IOException - */ - private void writeTsvHeader( OutputStream outputStream, List<String> headers ) throws IOException { - boolean first = true; - for( String header : headers ) { - if( !first ) { - outputStream.write( separator ); - } - writeEscaped( outputStream, header ); - first = false; + + // -------------------------------------------------------------------------- + // Public interface + // -------------------------------------------------------------------------- + + /** + * Sets the text encoding for the resource. This setting must only used + * if the resource response represents text. + * + * @param textEncoding character encoding of text body + * @throws UnsupportedEncodingException when the given encoding is not supported. + */ + public void setTextEncoding(String textEncoding) throws UnsupportedEncodingException { + buildSeparatorConformEncoding(textEncoding); + this.textEncoding = textEncoding; + } + + /** + * @return text encoding for resource + */ + protected String getTextEncoding() { + return textEncoding; } - outputStream.write( "\n".getBytes( textEncoding ) ); - } - - /** - * Write a single tsv line using the given line data. - * - * @param outputStream - * stream to write to. - * @param headers - * the headers to write line data for. - * @param lineData - * the line data to write. - * @throws IOException - */ - private void writeTsvLine( OutputStream outputStream, List<String> headers, - SolutionMapping lineData ) throws IOException { - boolean first = true; - for( String header : headers ) { - if( !first ) { - outputStream.write( separator ); - } - RDFTerm resource = lineData.get( header ); - if( resource != null ) { - writeEscaped( outputStream, getResourceValue( resource ) ); - } - first = false; + + // -------------------------------------------------------------------------- + // Private methods + // -------------------------------------------------------------------------- + + /** + * Builds the column separator according to the given text encoding. + * + * @param encoding the text encoding to be used. + * @throws UnsupportedEncodingException when the given encoding is not supported. + */ + private void buildSeparatorConformEncoding(String encoding) throws UnsupportedEncodingException { + separator = ",".getBytes(encoding); } - outputStream.write( "\n".getBytes( textEncoding ) ); - } - - /** - * Helper to get the proper string representation for the given RDFTerm. - */ - private String getResourceValue( RDFTerm resource ) { - StringBuilder value = new StringBuilder(); - if( resource instanceof IRI ) { - value.append( resource.toString() ); - } else if( resource instanceof Literal ) { - value.append( "\"" ); - value.append( escapedDQuotes(((Literal) resource).getLexicalForm()) ); - value.append( "\"" ); - } else if( resource instanceof BlankNode ) { - value.append( "/" ); - } else { - value.append( resource.toString() ); + + /** + * Write resultset header to the given output stream. + * + * @param outputStream stream to write to. + * @param headers the headers to write. + * @throws IOException + */ + private void writeTsvHeader(OutputStream outputStream, List<String> headers) throws IOException { + boolean first = true; + for (String header : headers) { + if (!first) { + outputStream.write(separator); + } + writeEscaped(outputStream, header); + first = false; + } + outputStream.write("\n".getBytes(textEncoding)); } - return value.toString(); - } - - /** - * Write the given string to the output stream and escape the output where - * necessary. - * - * @param outputStream - * stream to write to. - * @param text - * the text to write. - * @throws IOException - */ - private void writeEscaped( OutputStream outputStream, String text ) throws IOException { - String line = text; - if( text.contains( "\r" ) ) { - line = text.replaceAll( "\r", "\\r" ); + + /** + * Write a single tsv line using the given line data. + * + * @param outputStream stream to write to. + * @param headers the headers to write line data for. + * @param lineData the line data to write. + * @throws IOException + */ + private void writeTsvLine(OutputStream outputStream, List<String> headers, + SolutionMapping lineData) throws IOException { + boolean first = true; + for (String header : headers) { + if (!first) { + outputStream.write(separator); + } + RDFTerm resource = lineData.get(header); + if (resource != null) { + writeEscaped(outputStream, getResourceValue(resource)); + } + first = false; + } + outputStream.write("\n".getBytes(textEncoding)); } - if( text.contains( "\n" ) ) { - line = text.replaceAll( "\n", "\\n" ); + + /** + * Helper to get the proper string representation for the given RDFTerm. + */ + private String getResourceValue(RDFTerm resource) { + StringBuilder value = new StringBuilder(); + if (resource instanceof IRI) { + value.append(resource.toString()); + } else if (resource instanceof Literal) { + value.append("\""); + value.append(escapedDQuotes(((Literal) resource).getLexicalForm())); + value.append("\""); + } else if (resource instanceof BlankNode) { + value.append("/"); + } else { + value.append(resource.toString()); + } + return value.toString(); } - if( text.contains( "\t" ) ) { - line = text.replaceAll( "\t", "\\t" ); + + /** + * Write the given string to the output stream and escape the output where + * necessary. + * + * @param outputStream stream to write to. + * @param text the text to write. + * @throws IOException + */ + private void writeEscaped(OutputStream outputStream, String text) throws IOException { + String line = text; + if (text.contains("\r")) { + line = text.replaceAll("\r", "\\r"); + } + if (text.contains("\n")) { + line = text.replaceAll("\n", "\\n"); + } + if (text.contains("\t")) { + line = text.replaceAll("\t", "\\t"); + } + outputStream.write(line.getBytes(textEncoding)); } - outputStream.write( line.getBytes( textEncoding ) ); - } - private String escapedDQuotes( String text ) { - String line = text; - if( text.contains( "\"" ) ) { - line = text.replaceAll( "\"", "\"\"" ); + private String escapedDQuotes(String text) { + String line = text; + if (text.contains("\"")) { + line = text.replaceAll("\"", "\"\""); + } + return line; } - return line; - } } diff --git a/jaxrs.rdf.providers/src/main/java/org/apache/clerezza/jaxrs/sparql/providers/ResultSetXmlMessageBodyWriter.java b/jaxrs.rdf.providers/src/main/java/org/apache/clerezza/jaxrs/sparql/providers/ResultSetXmlMessageBodyWriter.java index 59a7063..1b50088 100644 --- a/jaxrs.rdf.providers/src/main/java/org/apache/clerezza/jaxrs/sparql/providers/ResultSetXmlMessageBodyWriter.java +++ b/jaxrs.rdf.providers/src/main/java/org/apache/clerezza/jaxrs/sparql/providers/ResultSetXmlMessageBodyWriter.java @@ -1,29 +1,34 @@ /* - * 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. - */ + * 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.List; -import java.util.Set; +import org.apache.clerezza.api.IRI; +import org.apache.clerezza.api.Language; +import org.apache.clerezza.api.Literal; +import org.apache.clerezza.api.RDFTerm; +import org.apache.clerezza.sparql.ResultSet; +import org.apache.clerezza.sparql.SolutionMapping; +import org.apache.clerezza.sparql.query.Variable; +import org.osgi.service.component.annotations.Component; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Document; +import org.w3c.dom.Element; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; @@ -39,158 +44,149 @@ 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.commons.rdf.Language; -import org.apache.clerezza.commons.rdf.RDFTerm; -import org.apache.clerezza.commons.rdf.IRI; -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.clerezza.commons.rdf.Literal; -import org.osgi.service.component.annotations.Component; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.w3c.dom.Document; -import org.w3c.dom.Element; +import java.io.IOException; +import java.io.OutputStream; +import java.lang.annotation.Annotation; +import java.lang.reflect.Type; +import java.util.List; +import java.util.Set; /** * 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={"javax.ws.rs=true"}) +@Component(service = Object.class, property = {"javax.ws.rs=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"); - createVariables(queryResult.getResultVars(), head, doc); - root.appendChild(head); - - Element results = doc.createElement("results"); - while (queryResult.hasNext()) { - createResultElement(queryResult.next(), results, 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("<", "<").replace("\n", - "<br/>")).build()); - } - - - /** - * Helper: creates value element from {@link RDFTerm} depending on its - * class - * - */ - private Element createValueElement(RDFTerm resource, Document doc) { - Element value = null; - if (resource instanceof IRI) { - value = doc.createElement("uri"); - value.appendChild(doc.createTextNode(((IRI) resource) - .getUnicodeString())); - } else if (resource instanceof Literal) { - value = doc.createElement("literal"); - value.appendChild(doc.createTextNode(((Literal) resource) - .getLexicalForm())); - value.setAttribute("datatype", (((Literal) resource) - .getDataType().getUnicodeString())); - Language lang = ((Literal) 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((RDFTerm) solutionMap.get(key), doc)); - result.appendChild(bindingElement); - } - } - - private void createVariables(List<String> variables, Element head, Document doc) { - for (String variable : variables) { - Element varElement = doc.createElement("variable"); - varElement.setAttribute("name", variable); - head.appendChild(varElement); - } - } + 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"); + createVariables(queryResult.getResultVars(), head, doc); + root.appendChild(head); + + Element results = doc.createElement("results"); + while (queryResult.hasNext()) { + createResultElement(queryResult.next(), results, 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("<", "<").replace("\n", + "<br/>")).build()); + } + + + /** + * Helper: creates value element from {@link RDFTerm} depending on its + * class + */ + private Element createValueElement(RDFTerm resource, Document doc) { + Element value = null; + if (resource instanceof IRI) { + value = doc.createElement("uri"); + value.appendChild(doc.createTextNode(((IRI) resource) + .getUnicodeString())); + } else if (resource instanceof Literal) { + value = doc.createElement("literal"); + value.appendChild(doc.createTextNode(((Literal) resource) + .getLexicalForm())); + value.setAttribute("datatype", (((Literal) resource) + .getDataType().getUnicodeString())); + Language lang = ((Literal) 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((RDFTerm) solutionMap.get(key), doc)); + result.appendChild(bindingElement); + } + } + + private void createVariables(List<String> variables, Element head, Document doc) { + for (String variable : variables) { + Element varElement = doc.createElement("variable"); + varElement.setAttribute("name", variable); + head.appendChild(varElement); + } + } }
