You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@marmotta.apache.org by wi...@apache.org on 2013/02/19 13:52:01 UTC
[7/52] [partial] code contribution,
initial import of relevant modules of LMF-3.0.0-SNAPSHOT based on
revision 4bf944319368 of the default branch at https://code.google.com/p/lmf/
http://git-wip-us.apache.org/repos/asf/incubator-marmotta/blob/c32963d5/lmf-core/src/main/java/kiwi/core/webservices/resource/ContentWebService.java
----------------------------------------------------------------------
diff --git a/lmf-core/src/main/java/kiwi/core/webservices/resource/ContentWebService.java b/lmf-core/src/main/java/kiwi/core/webservices/resource/ContentWebService.java
new file mode 100644
index 0000000..50ac140
--- /dev/null
+++ b/lmf-core/src/main/java/kiwi/core/webservices/resource/ContentWebService.java
@@ -0,0 +1,327 @@
+/**
+ * Copyright (C) 2013 Salzburg Research.
+ *
+ * Licensed 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 kiwi.core.webservices.resource;
+
+import at.newmedialab.sesame.commons.repository.ResourceUtils;
+import kiwi.core.api.config.ConfigurationService;
+import kiwi.core.api.content.ContentService;
+import kiwi.core.api.io.LMFIOService;
+import kiwi.core.api.triplestore.SesameService;
+import kiwi.core.events.ContentCreatedEvent;
+import kiwi.core.exception.LMFException;
+import kiwi.core.exception.WritingNotSupportedException;
+import kiwi.core.qualifiers.event.ContentCreated;
+import org.openrdf.model.Resource;
+import org.openrdf.model.URI;
+import org.openrdf.repository.RepositoryConnection;
+import org.openrdf.repository.RepositoryException;
+
+import javax.enterprise.context.ApplicationScoped;
+import javax.enterprise.event.Event;
+import javax.inject.Inject;
+import javax.servlet.http.HttpServletRequest;
+import javax.validation.constraints.NotNull;
+import javax.ws.rs.*;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.Response.Status;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.UnsupportedEncodingException;
+import java.net.URLDecoder;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/**
+ * Content Web Services
+ *
+ * @author Thomas Kurz
+ * @author Sergio Fernández
+ */
+@ApplicationScoped
+@Path("/" + ConfigurationService.CONTENT_PATH)
+public class ContentWebService {
+
+ private static final String ENHANCER_STANBOL_ENHANCER_ENABLED = "enhancer.stanbol.enhancer.enabled";
+
+ @Inject
+ private ConfigurationService configurationService;
+
+ @Inject
+ private ContentService contentService;
+
+ @Inject @ContentCreated
+ private Event<ContentCreatedEvent> afterContentCreated;
+
+ @Inject
+ private LMFIOService kiWiIOService;
+
+ @Inject
+ private SesameService sesameService;
+
+ /**
+ * Returns local resource content with the given uuid and an accepted return
+ * type (mimetype)
+ *
+ * @param uuid
+ * , a unique identifier (must not contain url specific
+ * characters like /,# etc.)
+ * @param mimetype
+ * , accepted mimetype follows the pattern .+/.+
+ * @return a local resource's content (body is the resource content in
+ * requested format)
+ * @HTTP 200 resource content found and returned
+ * @HTTP 404 resource cannot be found
+ * @HTTP 406 resource cannot be found in the given format
+ * @HTTP 500 Internal Error
+ * @ResponseHeader Content-Type (for HTTP 406) available content type (if
+ * resource has content)
+ */
+ @GET
+ @Path(ResourceWebService.MIME_PATTERN + ResourceWebService.UUID_PATTERN)
+ public Response getContentLocal(@PathParam("uuid") String uuid, @PathParam("mimetype") String mimetype, @HeaderParam("Range") String range) throws UnsupportedEncodingException {
+ String uri = configurationService.getBaseUri() + "resource/" + uuid;
+ return getContent(uri, mimetype, uuid, range);
+ }
+
+ /**
+ * Returns remote resource content with the given uri and an accepted return
+ * type (mimetype)
+ *
+ * @param uri
+ * , the fully-qualified URI of the resource to create in the
+ * triple store
+ * @param mimetype
+ * , accepted mimetype follows the pattern .+/.+
+ * @return a remote resource's content (body is the resource content in
+ * requested format)
+ * @HTTP 200 resource content found and returned
+ * @HTTP 400 bad request (maybe uri is not defined)
+ * @HTTP 404 resource cannot be found
+ * @HTTP 406 resource cannot be found in the given format
+ * @HTTP 500 Internal Error
+ * @ResponseHeader Content-Type (for HTTP 406) available content type (if
+ * resource has content)
+ */
+ @GET
+ @Path(ResourceWebService.MIME_PATTERN)
+ public Response getContentRemote(@QueryParam("uri") @NotNull String uri, @PathParam("mimetype") String mimetype, @HeaderParam("Range") String range) throws UnsupportedEncodingException {
+ return getContent(URLDecoder.decode(uri, "utf-8"), mimetype, null, range);
+ }
+
+ /**
+ * Sets content to a given locale resource
+ *
+ * @param uuid
+ * , a unique identifier (must not contain url specific
+ * characters like /,# etc.)
+ * @param mimetype
+ * content-type of the body (content) follows the pattern .+/.+
+ * @return HTTP response (success or error)
+ * @HTTP 200 put was successful
+ * @HTTP 400 bad request (e.g. body is empty)
+ * @HTTP 404 resource cannot be found
+ * @HTTP 415 Content-Type is not supported
+ * @HTTP 500 Internal Error
+ */
+ @PUT
+ @Path(ResourceWebService.MIME_PATTERN + ResourceWebService.UUID_PATTERN)
+ public Response putContentLocal(@PathParam("uuid") String uuid, @PathParam("mimetype") String mimetype, @Context HttpServletRequest request) {
+ String uri = configurationService.getBaseUri() + "resource/" + uuid;
+ return putContent(uri, mimetype, request);
+ }
+
+
+ /**
+ * Sets content to a given remote resource
+ *
+ * @param uri
+ * , the fully-qualified URI of the resource to create in the
+ * triple store
+ * @param mimetype
+ * content-type of the body (content) follows the pattern .+/.+
+ * @return HTTP response (success or error)
+ * @HTTP 200 put was successful
+ * @HTTP 400 bad request (e.g. uri is null)
+ * @HTTP 404 resource cannot be found
+ * @HTTP 415 Content-Type is not supported
+ * @HTTP 500 Internal Error
+ */
+ @PUT
+ @Path(ResourceWebService.MIME_PATTERN)
+ public Response putContentRemote(@QueryParam("uri") @NotNull String uri, @PathParam("mimetype") String mimetype, @Context HttpServletRequest request)
+ throws UnsupportedEncodingException {
+ return putContent(URLDecoder.decode(uri, "utf-8"), mimetype, request);
+ }
+
+ /**
+ * Delete content of remote resource with given uri
+ *
+ * @param uri
+ * , the fully-qualified URI of the resource to create in the
+ * triple store
+ * @return HTTP response (success or error)
+ * @HTTP 200 resource content deleted
+ * @HTTP 400 bad request (e.g, uri is null)
+ * @HTTP 404 resource or resource content not found
+ */
+ @DELETE
+ public Response deleteContentRemote(@QueryParam("uri") @NotNull String uri) throws UnsupportedEncodingException {
+ try {
+ RepositoryConnection conn = sesameService.getConnection();
+ try {
+ conn.begin();
+ Resource resource = ResourceUtils.getUriResource(conn,URLDecoder.decode(uri, "utf-8"));
+ if (resource != null) {
+ if (contentService.deleteContent(resource)) return Response.ok().build();
+ else
+ return ResourceWebServiceHelper.buildErrorPage(uri, configurationService.getBaseUri(), Response.Status.NOT_FOUND, "no content found for this resource in LMF right now, but may be available again in the future");
+ }
+ return Response.status(Response.Status.NOT_FOUND).build();
+ } finally {
+ conn.commit();
+ conn.close();
+ }
+ } catch (LMFException ex) {
+ return Response.serverError().entity(ex.getMessage()).build();
+ } catch (RepositoryException ex) {
+ return Response.serverError().entity(ex.getMessage()).build();
+ }
+ }
+
+ /**
+ * Delete content of local resource with given uuid
+ *
+ * @param uuid
+ * , a unique identifier (must not contain url specific
+ * characters like /,# etc.)
+ * @return HTTP response (success or error)
+ * @HTTP 200 resource deleted
+ * @HTTP 404 resource or resource content not found
+ */
+ @DELETE
+ @Path(ResourceWebService.UUID_PATTERN)
+ public Response deleteContentLocal(@PathParam("uuid") String uuid) throws UnsupportedEncodingException {
+ String uri = configurationService.getBaseUri() + "resource/" + uuid;
+ return deleteContentRemote(uri);
+ }
+
+ private Response getContent(String uri, String mimetype, String uuid, String range) throws UnsupportedEncodingException {
+ try {
+ // FIXME String appendix = uuid == null ? "?uri=" + URLEncoder.encode(uri, "utf-8") :
+ // "/" + uuid;
+ final RepositoryConnection conn = sesameService.getConnection();
+ try {
+ conn.begin();
+ URI resource = ResourceUtils.getUriResource(conn, uri);
+ conn.commit();
+ if (contentService.hasContent(resource, mimetype)) {
+
+ InputStream is = contentService.getContentStream(resource, mimetype);
+ long length = contentService.getContentLength(resource,mimetype);
+
+ // build response
+ Response response = null;
+ long fromL = 0;
+ if(range != null) {
+ response = Response.status(206).entity(is).build();
+ Pattern p = Pattern.compile("bytes=([0-9]+)-([0-9]+)?");
+ Matcher m = p.matcher(range);
+ if(m.matches()) {
+ String from = m.group(1);
+ try {
+ fromL = Long.parseLong(from);
+ is.skip(fromL);
+ response.getMetadata().add("Content-Range","bytes "+fromL+"-"+(length-1)+"/"+length);
+ } catch(NumberFormatException ex) {
+ response.getMetadata().add("Content-Range","bytes 0-"+(length-1)+"/"+length);
+ }
+ } else {
+ response.getMetadata().add("Content-Range","bytes 0-"+(length-1)+"/"+length);
+ }
+ response.getMetadata().add("Accept-Ranges","bytes");
+ } else {
+ response = Response.ok(is).build();
+ response.getMetadata().add("Accept-Ranges","bytes");
+ }
+
+ if(mimetype.startsWith("text") || mimetype.startsWith("application/json")) {
+ // Content-Encoding is not what it seems, known values are: gzip, compress,
+ // deflate, identity
+ // response.getMetadata().add("Content-Encoding", "utf-8");
+ response.getMetadata().add("Content-Type", mimetype + "; charset=utf-8");
+ } else {
+ response.getMetadata().add("Content-Type", mimetype);
+ }
+ if(length > 0) {
+ response.getMetadata().add("Content-Length",length-fromL);
+ }
+
+ // append data links
+ String s = ResourceWebServiceHelper.buildMetaLinks(resource, uuid, kiWiIOService.getProducedTypes(), configurationService);
+ if (s != null) {
+ response.getMetadata().add("Links", s);
+ }
+ return response;
+ } else {
+ Response response = ResourceWebServiceHelper.buildErrorPage(uri, configurationService.getBaseUri(), Status.NOT_ACCEPTABLE, "no content for mimetype " + mimetype);
+ ResourceWebServiceHelper.addHeader(response, "Content-Type", ResourceWebServiceHelper.appendContentTypes(contentService.getContentType(resource)));
+ return response;
+ }
+ } finally {
+ conn.close();
+ }
+ } catch (IOException e) {
+ return Response.serverError().entity(e.getMessage()).build();
+ } catch (RepositoryException e) {
+ return Response.serverError().entity(e.getMessage()).build();
+ }
+ }
+
+ public Response putContent(String uri, String mimetype, HttpServletRequest request) {
+ try {
+ final RepositoryConnection conn = sesameService.getConnection();
+ try {
+ conn.begin();
+ URI resource = ResourceUtils.getUriResource(conn, uri);
+ conn.commit();
+ return putContent(resource, mimetype, request);
+ } finally {
+ conn.close();
+ }
+ } catch (RepositoryException e) {
+ return Response.serverError().entity(e.getMessage()).build();
+ }
+ }
+
+ public Response putContent(URI resource, String mimetype, HttpServletRequest request) {
+ try {
+ if (request.getContentLength() == 0)
+ return ResourceWebServiceHelper.buildErrorPage(resource.stringValue(), configurationService.getBaseUri(), Status.BAD_REQUEST, "content may not be empty for writting");
+ contentService.setContentStream(resource, request.getInputStream(), mimetype); // store content
+ if(configurationService.getBooleanConfiguration(ENHANCER_STANBOL_ENHANCER_ENABLED, false)) {
+ afterContentCreated.fire(new ContentCreatedEvent(resource)); //enhancer
+ }
+ return Response.ok().build();
+ } catch (IOException e) {
+ return ResourceWebServiceHelper.buildErrorPage(resource.stringValue(), configurationService.getBaseUri(), Status.BAD_REQUEST, "could not read request body");
+ } catch (WritingNotSupportedException e) {
+ return ResourceWebServiceHelper.buildErrorPage(resource.stringValue(), configurationService.getBaseUri(), Status.FORBIDDEN, "writting this content is not supported");
+ }
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-marmotta/blob/c32963d5/lmf-core/src/main/java/kiwi/core/webservices/resource/InspectionWebService.java
----------------------------------------------------------------------
diff --git a/lmf-core/src/main/java/kiwi/core/webservices/resource/InspectionWebService.java b/lmf-core/src/main/java/kiwi/core/webservices/resource/InspectionWebService.java
new file mode 100644
index 0000000..589c646
--- /dev/null
+++ b/lmf-core/src/main/java/kiwi/core/webservices/resource/InspectionWebService.java
@@ -0,0 +1,548 @@
+/**
+ * Copyright (C) 2013 Salzburg Research.
+ *
+ * Licensed 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 kiwi.core.webservices.resource;
+
+import static at.newmedialab.sesame.commons.repository.ExceptionUtils.handleRepositoryException;
+import static at.newmedialab.sesame.commons.repository.ResourceUtils.getAnonResource;
+import static at.newmedialab.sesame.commons.repository.ResourceUtils.getLabel;
+import static at.newmedialab.sesame.commons.repository.ResourceUtils.getUriResource;
+import static at.newmedialab.sesame.commons.repository.ResourceUtils.listOutgoing;
+
+import at.newmedialab.sesame.commons.model.Namespaces;
+import kiwi.core.api.config.ConfigurationService;
+import kiwi.core.api.content.ContentService;
+import kiwi.core.api.triplestore.SesameService;
+import org.apache.marmotta.kiwi.model.rdf.KiWiResource;
+import org.apache.marmotta.kiwi.model.rdf.KiWiTriple;
+import org.openrdf.model.*;
+import org.openrdf.repository.RepositoryConnection;
+import org.openrdf.repository.RepositoryException;
+import org.openrdf.repository.RepositoryResult;
+
+import javax.inject.Inject;
+import javax.ws.rs.*;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.Response.Status;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+import java.io.UnsupportedEncodingException;
+import java.net.URLEncoder;
+import java.util.*;
+
+@Path("/" + ConfigurationService.INSPECT_PATH)
+public class InspectionWebService {
+
+ private static final String UUID_PATTERN = "/{uuid:[^#?]+}";
+ private static final String CHARSET = "utf-8";
+ private static final String DEFAULT_BATCH_SIZE = "20";
+
+ @Inject
+ private ConfigurationService configurationService;
+
+ @Inject
+ private SesameService sesameService;
+
+ @Inject
+ private ContentService contentService;
+
+ @GET
+ @Path("/subject")
+ @Produces(Namespaces.MIME_TYPE_JSON)
+ public List<TriplePoJo> listSubjectUsage(@QueryParam("uri") String uri, @QueryParam("start") @DefaultValue("0") long offset,
+ @QueryParam("limit") @DefaultValue(DEFAULT_BATCH_SIZE) int batchSize) {
+
+ try {
+ RepositoryConnection conn = sesameService.getConnection();
+ try {
+ conn.begin();
+ URI r = getUriResource(conn, uri);
+ if (r != null) return
+ buildResultList(conn, r, null, null, null, offset, batchSize);
+ else
+ return Collections.emptyList();
+ } finally {
+ conn.commit();
+ conn.close();
+ }
+ } catch(RepositoryException ex) {
+ handleRepositoryException(ex,InspectionWebService.class);
+ return Collections.emptyList();
+ }
+ }
+
+ @GET
+ @Path("/predicate")
+ @Produces(Namespaces.MIME_TYPE_JSON)
+ public List<TriplePoJo> listPredicatetUsage(@QueryParam("uri") String uri, @QueryParam("start") @DefaultValue("0") long offset,
+ @QueryParam("limit") @DefaultValue(DEFAULT_BATCH_SIZE) int batchSize) {
+ try {
+ RepositoryConnection conn = sesameService.getConnection();
+ try {
+ conn.begin();
+ URI r = getUriResource(conn, uri);
+ if (r != null)
+ return buildResultList(conn, null, r, null, null, offset, batchSize);
+ else
+ return Collections.emptyList();
+ } finally {
+ conn.commit();
+ conn.close();
+ }
+ } catch(RepositoryException ex) {
+ handleRepositoryException(ex,InspectionWebService.class);
+ return Collections.emptyList();
+ }
+ }
+
+
+ @GET
+ @Path("/object")
+ @Produces(Namespaces.MIME_TYPE_JSON)
+ public List<TriplePoJo> listObjectUsage(@QueryParam("uri") String uri, @QueryParam("start") @DefaultValue("0") long offset,
+ @QueryParam("limit") @DefaultValue(DEFAULT_BATCH_SIZE) int batchSize) {
+
+ try {
+ RepositoryConnection conn = sesameService.getConnection();
+ try {
+ conn.begin();
+ URI r = getUriResource(conn, uri);
+ if (r != null)
+ return buildResultList(conn, null, null, r, null, offset, batchSize);
+ else
+ return Collections.emptyList();
+ } finally {
+ conn.commit();
+ conn.close();
+ }
+ } catch(RepositoryException ex) {
+ handleRepositoryException(ex,InspectionWebService.class);
+ return Collections.emptyList();
+ }
+ }
+
+ @GET
+ @Path("/context")
+ @Produces(Namespaces.MIME_TYPE_JSON)
+ public List<TriplePoJo> listContextUsage(@QueryParam("uri") String uri, @QueryParam("start") @DefaultValue("0") long offset,
+ @QueryParam("limit") @DefaultValue(DEFAULT_BATCH_SIZE) int batchSize) {
+
+ try {
+ RepositoryConnection conn = sesameService.getConnection();
+ try {
+ conn.begin();
+ URI r = getUriResource(conn, uri);
+ if (r != null)
+ return buildResultList(conn, null, null, null, r, offset, batchSize);
+ else
+ return Collections.emptyList();
+ } finally {
+ conn.commit();
+ conn.close();
+ }
+ } catch(RepositoryException ex) {
+ handleRepositoryException(ex,InspectionWebService.class);
+ return Collections.emptyList();
+ }
+ }
+
+ private List<TriplePoJo> buildResultList(RepositoryConnection conn, URI s, URI p, URI o, URI c, long start, int limit) throws RepositoryException {
+ List<TriplePoJo> result = new ArrayList<InspectionWebService.TriplePoJo>();
+ RepositoryResult<Statement> triples = conn.getStatements(s,p,o,true,c);
+ // skip until start
+ for(int i = 0; i<start && triples.hasNext(); i++) {
+ triples.next();
+ }
+ // retrieve until limit
+ for(int i=0; i<limit && triples.hasNext(); i++) {
+ result.add(new TriplePoJo(triples.next()));
+ }
+ triples.close();
+ return result;
+ }
+
+ protected static class TriplePoJo {
+ private final long id;
+ private final String s, p, o, c;
+
+ public TriplePoJo(Statement t) {
+ if(t instanceof KiWiTriple) {
+ id = ((KiWiTriple)t).getId();
+ } else {
+ id = 0;
+ }
+ s = t.getSubject().toString();
+ p = t.getPredicate().toString();
+ o = t.getObject().toString();
+ c = t.getContext().toString();
+ }
+
+ public long getId() {
+ return id;
+ }
+
+ public String getS() {
+ return s;
+ }
+
+ public String getP() {
+ return p;
+ }
+
+ public String getO() {
+ return o;
+ }
+
+ public String getC() {
+ return c;
+ }
+ }
+
+ @GET
+ @Path(UUID_PATTERN)
+ @Produces("text/html")
+ public Response inspectLocalResource(@PathParam("uuid") String uuid, @QueryParam("sOffset") @DefaultValue("0") long sOffset,
+ @QueryParam("pOffset") @DefaultValue("0") long pOffset, @QueryParam("oOffset") @DefaultValue("0") long oOffset,
+ @QueryParam("cOffset") @DefaultValue("0") long cOffset, @QueryParam("limit") @DefaultValue(DEFAULT_BATCH_SIZE) int batchSize)
+ throws UnsupportedEncodingException {
+ String uri = configurationService.getBaseUri() + ConfigurationService.RESOURCE_PATH + "/" + uuid;
+ try {
+ RepositoryConnection conn = sesameService.getConnection();
+ try {
+ conn.begin();
+ Resource rsc = getUriResource(conn, uri);
+ if (rsc == null) {
+ rsc = getAnonResource(conn, uuid);
+ }
+ if (rsc == null)
+ return Response.status(Status.NOT_FOUND).entity("Not found: " + uuid).build();
+ else
+ return inspectResource(conn, rsc, sOffset, pOffset, oOffset, cOffset, batchSize);
+ } finally {
+ conn.commit();
+ conn.close();
+ }
+ } catch(RepositoryException ex) {
+ handleRepositoryException(ex,InspectionWebService.class);
+ return Response.serverError().entity(ex.getMessage()).build();
+ }
+ }
+
+ @GET
+ @Path("/")
+ @Produces("text/html")
+ public Response inspectRemoteResource(@QueryParam("uri") String uri, @QueryParam("sOffset") @DefaultValue("0") long sOffset,
+ @QueryParam("pOffset") @DefaultValue("0") long pOffset, @QueryParam("oOffset") @DefaultValue("0") long oOffset,
+ @QueryParam("cOffset") @DefaultValue("0") long cOffset, @QueryParam("limit") @DefaultValue(DEFAULT_BATCH_SIZE) int batchSize)
+ throws UnsupportedEncodingException {
+ try {
+ RepositoryConnection conn = sesameService.getConnection();
+ try {
+ conn.begin();
+ Resource rsc = getUriResource(conn, uri);
+ if (rsc == null)
+ return Response.status(Status.NOT_FOUND).entity("Not found: " + uri).build();
+ else
+ return inspectResource(conn, rsc, sOffset, pOffset, oOffset, cOffset, batchSize);
+ } finally {
+ conn.commit();
+ conn.close();
+ }
+ } catch(RepositoryException ex) {
+ handleRepositoryException(ex,InspectionWebService.class);
+ return Response.serverError().entity(ex.getMessage()).build();
+ }
+ }
+
+ private Response inspectResource(RepositoryConnection conn, Resource rsc, long subjOffset, long propOffset, long objOffset, long ctxOffset, int limit)
+ throws UnsupportedEncodingException, RepositoryException {
+ if (rsc == null)
+ return Response.status(Status.NOT_FOUND).entity("Not found").build();
+ URI uri = null;
+ if (rsc instanceof URI) {
+ uri = (URI) rsc;
+ }
+ // Well, this is rather hacky...
+ ByteArrayOutputStream os = new ByteArrayOutputStream();
+ PrintStream ps = new PrintStream(os);
+
+ ps.println("<!DOCTYPE HTML><html><head>");
+
+ ps.printf("<title>Inspect %s</title>%n", rsc.stringValue());
+ ps.println("<style type='text/css'>");
+ ps.println("table {border: 2px solid #006d8f;width: 100%;border-collapse: collapse;}"
+ + "html, body{font-family: sans-serif;}"
+ + "table th {background-color: #006d8f;color: white;}"
+ + "table tr {}"
+ + "table tr.even {background-color: #dff7ff;}"
+ + "table tr.odd {background-color: lightBlue;}"
+ + "table th, table td {padding: 2px;}"
+ + "table tr:hover {background-color: white;}"
+ + ".isDeleted { color: red; font-style: italic; }"
+ + ".deleted {width: 20px; height: 20px; display: inline-block; border-radius: 10px; float: right}"
+ + ".deleted.true {background-color: red;}"
+ + ".deleted.false {background-color: darkGreen;}"
+ + ".reasoned a { border-radius: 10px; display: inline-block; float: right; background-color: orange; width: 20px; height: 20px; color: white; text-decoration: none; margin-right: 5px; text-align: center; font-family: serif; font-weight: bolder;}"
+ + ".info-dialog { border:1px solid black; width:50%; position:absolute; top:100px; left:25%; background-color:white; z-index:2; padding-top:10px; min-height:100px; overflow:auto; display:none;}"
+ + ".info-dialog button.close-button { position:absolute; top:5px; right:5px; } "
+ + ".info-dialog iframe { border:none; width:100%; }");
+
+ ps.println("</style>");
+
+ ps.println();
+ ps.println("</head><body>");
+
+ ps.printf("<h1>Inspect %s</h1>%n<div>ShortName: %s<span class='%s'>%<s</span></div>%n", rsc.stringValue(), getLabel(conn,rsc), "");
+ if(rsc instanceof KiWiResource) {
+ ps.printf("<div>Created: <span>%tF %<tT</span> by <span>%s</span></div>%n", ((KiWiResource)rsc).getCreated(), createInspectLink(conn, null, null, ""));
+ }
+ ps.printf("<div>Last Modified: <span>%tF %<tT</span></div>%n", lastModified(conn, rsc));
+
+ // Outgoing
+ printOutgoing(conn, rsc, ps, subjOffset, limit);
+
+ // Incoming
+ printIncoming(conn, rsc, ps, objOffset, limit);
+
+ // Links
+ printLinks(conn, uri, ps, propOffset, limit);
+
+ // Context
+ printContext(conn, uri, ps, ctxOffset, limit);
+
+ ps.println();
+ ps.println("</body></html>");
+ return Response.ok().header("Content-Type", "text/html;charset=" + CHARSET).header("Last-Modified", lastModified(conn, rsc))
+ .entity(os.toString(CHARSET)).build();
+ }
+
+ protected void printLinks(RepositoryConnection conn, URI rsc, PrintStream ps, long offset, int limit) throws UnsupportedEncodingException, RepositoryException {
+ if (rsc == null) return;
+ int i = 0;
+ RepositoryResult<Statement> ts = conn.getStatements(null, rsc, null, true);
+
+ // skip until start
+ for(int j = 0; j<offset && ts.hasNext(); j++) {
+ ts.next();
+ }
+ if (ts.hasNext()) {
+ Set<Statement> triples = new HashSet<Statement>();
+ for(int j = 0; j<limit && ts.hasNext(); j++) {
+ triples.add(ts.next());
+ }
+
+ ps.printf("<h2>Connections</h2>%n");
+ ps.printf("<span class='count'>Showing %d links:</span> %s%n", triples.size(), createInspectLink(conn, rsc, "next", "&pOffset=" + (offset + limit)));
+
+ ps.printf("<table>%n <thead><tr><th>Source</th><th>Target</th><th>Context</th><th></th><th></th></tr></thead>%n <tbody>%n");
+ for (Statement t : triples) {
+ ps.printf(" <tr class='%s'><td>%s</td><td>%s</td><td>%s</td><td><span class='reasoned'>%s</span></td><td><span class='deleted %b'></span></td></tr>%n",
+ i++ % 2 == 0 ? "even" : "odd", createInspectLink(conn, t.getSubject()), createInspectLink(conn,t.getObject()), createInspectLink(conn,t.getContext()),
+ t instanceof KiWiTriple && ((KiWiTriple)t).isInferred() ? createInfo(((KiWiTriple)t).getId()) : "", t instanceof KiWiTriple && ((KiWiTriple)t).isDeleted());
+ }
+ ps.printf(" </tbody>%n</table>");
+ } else if (offset > 0) {
+ ps.printf("<h2>Connections</h2>%n");
+ ps.printf("<span class='count'>Less than %d links, reset offset</span>%n", offset);
+ }
+ ts.close();
+ }
+
+ protected void printIncoming(RepositoryConnection conn, Resource rsc, PrintStream ps, long offset, int limit) throws UnsupportedEncodingException, RepositoryException {
+ int i = 0;
+ RepositoryResult<Statement> ts = conn.getStatements(null, null, rsc, true);
+
+ // skip until start
+ for(int j = 0; j<offset && ts.hasNext(); j++) {
+ ts.next();
+ }
+ if (ts.hasNext()) {
+ Set<Statement> triples = new HashSet<Statement>();
+ for(int j = 0; j<limit && ts.hasNext(); j++) {
+ triples.add(ts.next());
+ }
+
+ ps.printf("<h2>Incoming Links</h2>%n");
+ ps.printf("<span class='count'>Showing %d incoming links:</span> %s%n", triples.size(), createInspectLink(conn,rsc, "next", "&oOffset=" + (offset + limit)));
+ ps.printf("<table>%n <thead><tr><th>Source</th><th>Link</th><th>Context</th><th></th><th></th></tr></thead>%n <tbody>%n");
+ for (Statement t : triples) {
+ ps.printf(
+ " <tr class='%s'><td>%s</td><td>%s</td><td>%s</td><td><span class='reasoned'>%s</span></td><td><span class='deleted %b'></span></td></tr>%n",
+ i++ % 2 == 0 ? "even" : "odd", createInspectLink(conn, t.getSubject()), createInspectLink(conn,t.getObject()), createInspectLink(conn,t.getContext()),
+ t instanceof KiWiTriple && ((KiWiTriple)t).isInferred() ? createInfo(((KiWiTriple)t).getId()) : "", t instanceof KiWiTriple && ((KiWiTriple)t).isDeleted());
+ }
+ ps.printf(" </tbody>%n</table>");
+ } else if (offset > 0) {
+ ps.printf("<h2>Incoming Links</h2>%n");
+ ps.printf("<span class='count'>No more incoming links at offset %d</span>%n", offset);
+ }
+ ts.close();
+ }
+
+ protected void printOutgoing(RepositoryConnection conn, Resource rsc, PrintStream ps, long offset, int limit) throws UnsupportedEncodingException, RepositoryException {
+ int i = 0;
+ RepositoryResult<Statement> ts = conn.getStatements(rsc, null, null, true);
+
+ // skip until start
+ for(int j = 0; j<offset && ts.hasNext(); j++) {
+ ts.next();
+ }
+ if (ts.hasNext()) {
+ Set<Statement> triples = new HashSet<Statement>();
+ for(int j = 0; j<limit && ts.hasNext(); j++) {
+ triples.add(ts.next());
+ }
+ ps.printf("<h2>Outgoing Links</h2>%n");
+ ps.printf("<span class='count'>Showing %d outgoing links:</span> %s%n", triples.size(),
+ createInspectLink(conn, rsc, "next", "&sOffset=" + (offset + limit)));
+ ps.printf("<table>%n <thead><tr><th>Link</th><th>Target</th><th>Context</th><th></th><th></th></tr></thead>%n <tbody>%n");
+ for (Statement t : triples) {
+ ps.printf(
+ " <tr class='%s'><td>%s</td><td>%s</td><td>%s</td><td><span class='reasoned'>%s</span></td><td><span class='deleted %b'></span></td></tr>%n",
+ i++ % 2 == 0 ? "even" : "odd", createInspectLink(conn, t.getSubject()), createInspectLink(conn,t.getObject()), createInspectLink(conn,t.getContext()),
+ t instanceof KiWiTriple && ((KiWiTriple)t).isInferred() ? createInfo(((KiWiTriple)t).getId()) : "", t instanceof KiWiTriple && ((KiWiTriple)t).isDeleted());
+ }
+ ps.printf(" </tbody>%n</table>");
+ } else if (offset > 0) {
+ ps.printf("<h2>Outgoing Links</h2>%n");
+ ps.printf("<span class='count'>No more outgoing links at offset %d</span>%n", offset);
+ }
+ ts.close();
+ }
+
+ protected void printContext(RepositoryConnection conn, Resource rsc, PrintStream ps, long offset, int limit) throws UnsupportedEncodingException, RepositoryException {
+ if (rsc == null) return;
+ int i = 0;
+ RepositoryResult<Statement> ts = conn.getStatements(null, null, null, true, rsc);
+
+ // skip until start
+ for(int j = 0; j<offset && ts.hasNext(); j++) {
+ ts.next();
+ }
+ if (ts.hasNext()) {
+ Set<Statement> triples = new HashSet<Statement>();
+ for(int j = 0; j<limit && ts.hasNext(); j++) {
+ triples.add(ts.next());
+ }
+ ps.printf("<h2>Context</h2>%n");
+ ps.printf("<span class='count'>Showing %d triples in Context:</span> %s%n", triples.size(),
+ createInspectLink(conn, rsc, "next", "&cOffset=" + (offset + limit)));
+ ps.printf("<table>%n <thead><tr><th>Subject</th><th>Property</th><th>Object</th><th></th><th></th></tr></thead>%n <tbody>%n");
+ for (Statement t : triples) {
+ ps.printf(
+ " <tr class='%s'><td>%s</td><td>%s</td><td>%s</td><td><span class='reasoned'>%s</span></td><td><span class='deleted %b'></span></td></tr>%n",
+ i++ % 2 == 0 ? "even" : "odd", createInspectLink(conn, t.getSubject()), createInspectLink(conn,t.getObject()), createInspectLink(conn,t.getContext()),
+ t instanceof KiWiTriple && ((KiWiTriple)t).isInferred() ? createInfo(((KiWiTriple)t).getId()) : "", t instanceof KiWiTriple && ((KiWiTriple)t).isDeleted());
+ }
+ ps.printf(" </tbody>%n</table>");
+ } else if (offset > 0) {
+ ps.printf("<h2>Context</h2>%n");
+ ps.printf("<span class='count'>Less than %d triples in context, reset offset.</span>%n", offset);
+ }
+
+ }
+
+ private String createInspectLink(RepositoryConnection conn, Value node) throws UnsupportedEncodingException {
+ return createInspectLink(conn, node, null, "");
+ }
+
+ private String createInspectLink(RepositoryConnection conn, Value node, String linkText, String extraQS) throws UnsupportedEncodingException {
+ if(node == null) return "undefined";
+ if (extraQS == null) {
+ extraQS = "";
+ }
+ if (node instanceof Literal) {
+ Literal lit = (Literal) node;
+ if (linkText == null) {
+ linkText = lit.getDatatype().stringValue();
+ }
+ StringBuilder sb = new StringBuilder("\"" + lit.getLabel().replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">")
+ + "\"");
+ if (lit.getLanguage() != null) {
+ sb.append("@").append(lit.getLanguage());
+ } else if (lit.getDatatype() != null) {
+ sb.append("^^").append(
+ String.format("<a href='%s?uri=%s%s'>%s</a>", configurationService.getServerUri() + "inspect",
+ URLEncoder.encode(lit.getDatatype().stringValue(), CHARSET), extraQS, linkText));
+ }
+ return sb.toString();
+ }
+ if (node instanceof BNode) {
+ BNode rsc = (BNode) node;
+ if (linkText == null) {
+ linkText = rsc.toString();
+ }
+ return String.format("<a href='%s/%s%s'>%s</a>", configurationService.getServerUri() + "inspect", rsc.getID(),
+ extraQS.replaceFirst("^&", "?"), linkText);
+ }
+ if (node instanceof URI) {
+ URI rsc = (URI) node;
+ if (linkText == null) {
+ linkText = rsc.toString();
+ }
+ return String.format("<a href='%s?uri=%s%s'>%s</a>", configurationService.getServerUri() + "inspect",
+ URLEncoder.encode(rsc.toString(), CHARSET), extraQS, linkText);
+ }
+ return "UNKNOWN";
+ }
+
+ private String buildResourceLink(RepositoryConnection conn, URI resource, String rel, String mime) {
+ final String src = configurationService.getServerUri(), base = configurationService.getBaseUri();
+
+ if (src.equals(base) && resource.toString().startsWith(base + ConfigurationService.RESOURCE_PATH + "/")) {
+ final String uuid;
+ uuid = resource.toString().substring((base + ConfigurationService.RESOURCE_PATH + "/").length());
+ return String.format("%s%s/%s/%s", base, rel, mime, uuid);
+ } else {
+ try {
+ return String.format("%s%s/%s?uri=%s", src, rel, mime, URLEncoder.encode(resource.toString(), CHARSET));
+ } catch (UnsupportedEncodingException e) {
+ return String.format("%s%s/%s?uri=%s", src, rel, mime, resource.toString());
+ }
+ }
+ }
+
+ private String createInfo(long id) {
+ StringBuilder b = new StringBuilder();
+ String closer = "<button onclick='document.getElementById(\"info" + id + "\").style.display = \"none\"' class='close-button'>X</button>";
+ String iframe = "<iframe id='iframe" + id + "' src='' style=''></iframe>";
+ b.append("<a href='#' title='justify this triple' onclick='document.getElementById(\"iframe").append(id).append("\").src=\"").append(configurationService.getServerUri()).append("core/public/html/reasoning.html#").append(id).append("\";document.getElementById(\"info").append(id).append("\").style.display = \"block\";'>i</a>");
+ b.append("<div id='info").append(id).append("' class='info-dialog'>");
+ b.append(iframe).append(closer);
+ b.append("</div>");
+ return b.toString();
+ }
+
+ /**
+ * Get the last modification of the set of triples passed as argument.
+ *
+ * @return
+ */
+ private Date lastModified(RepositoryConnection conn, Resource resource) throws RepositoryException {
+ Date last_modified = new Date(0);
+ for (Statement triple : listOutgoing(conn, resource)) {
+ if(triple instanceof KiWiTriple) {
+ KiWiTriple t = (KiWiTriple)triple;
+ if (t.getCreated().getTime() > last_modified.getTime()) {
+ last_modified = t.getCreated();
+ }
+ }
+ }
+ return last_modified;
+
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-marmotta/blob/c32963d5/lmf-core/src/main/java/kiwi/core/webservices/resource/MetaWebService.java
----------------------------------------------------------------------
diff --git a/lmf-core/src/main/java/kiwi/core/webservices/resource/MetaWebService.java b/lmf-core/src/main/java/kiwi/core/webservices/resource/MetaWebService.java
new file mode 100644
index 0000000..53bfc6e
--- /dev/null
+++ b/lmf-core/src/main/java/kiwi/core/webservices/resource/MetaWebService.java
@@ -0,0 +1,362 @@
+/**
+ * Copyright (C) 2013 Salzburg Research.
+ *
+ * Licensed 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 kiwi.core.webservices.resource;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.UnsupportedEncodingException;
+import java.net.URLDecoder;
+import java.util.LinkedList;
+import java.util.List;
+
+import javax.enterprise.context.ApplicationScoped;
+import javax.inject.Inject;
+import javax.servlet.http.HttpServletRequest;
+import javax.validation.constraints.NotNull;
+import javax.ws.rs.DELETE;
+import javax.ws.rs.GET;
+import javax.ws.rs.PUT;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.QueryParam;
+import javax.ws.rs.WebApplicationException;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.Response.Status;
+import javax.ws.rs.core.StreamingOutput;
+
+import kiwi.core.api.config.ConfigurationService;
+import kiwi.core.api.content.ContentService;
+import kiwi.core.api.io.LMFIOService;
+import kiwi.core.api.triplestore.ContextService;
+import kiwi.core.api.triplestore.SesameService;
+import kiwi.core.services.sesame.KiWiSesameUtil;
+import kiwi.core.services.sesame.ResourceSubjectMetadata;
+
+import org.apache.marmotta.commons.collections.CollectionUtils;
+import org.openrdf.model.Resource;
+import org.openrdf.model.URI;
+import org.openrdf.repository.RepositoryConnection;
+import org.openrdf.repository.RepositoryException;
+import org.openrdf.repository.event.InterceptingRepositoryConnection;
+import org.openrdf.repository.event.base.InterceptingRepositoryConnectionWrapper;
+import org.openrdf.rio.RDFFormat;
+import org.openrdf.rio.RDFHandlerException;
+import org.openrdf.rio.RDFParseException;
+import org.openrdf.rio.RDFWriter;
+import org.openrdf.rio.Rio;
+
+import at.newmedialab.sesame.commons.http.ETagGenerator;
+
+/**
+ * Meta Web Services
+ *
+ * @author Thomas Kurz
+ * @author Sergio Fernández
+ */
+@ApplicationScoped
+@Path("/" + ConfigurationService.META_PATH)
+public class MetaWebService {
+
+ @Inject
+ private ConfigurationService configurationService;
+
+ @Inject
+ private ContextService contextService;
+
+ @Inject
+ private ContentService contentService;
+
+ @Inject
+ private SesameService sesameService;
+
+ @Inject
+ private LMFIOService kiWiIOService;
+
+ /**
+ * Returns remote resource metadata with the given uri and an accepted
+ * return type (mimetype)
+ *
+ * @param uri
+ * , the fully-qualified URI of the resource to create in the
+ * triple store
+ * @param mimetype
+ * , accepted mimetype follows the pattern .+/.+
+ * @return a remote resource's metadata (body is the resource data in
+ * requested format)
+ * @HTTP 200 resource metadata found and returned
+ * @HTTP 400 bad request (maybe uri is not defined)
+ * @HTTP 404 resource cannot be found
+ * @HTTP 406 resource cannot be found in the given format
+ * @HTTP 500 Internal Error
+ * @ResponseHeader Content-Type (for HTTP 406) a list of available metadata
+ * types
+ */
+ @GET
+ @Path(ResourceWebService.MIME_PATTERN)
+ public Response getMetaRemote(@QueryParam("uri") @NotNull String uri, @PathParam("mimetype") String mimetype) throws UnsupportedEncodingException {
+ return getMeta(URLDecoder.decode(uri, "utf-8"), mimetype, null);
+ }
+
+ /**
+ * Returns local resource data with the given uuid and an accepted return
+ * type (mimetype)
+ *
+ * @param uuid
+ * , a unique identifier (must not contain url specific
+ * characters like /,# etc.)
+ * @param mimetype
+ * , accepted mimetype follows the pattern .+/.+
+ * @return a local resource's metadata (body is the resource data in
+ * requested format)
+ * @HTTP 200 resource data found and returned
+ * @HTTP 404 resource cannot be found
+ * @HTTP 406 resource cannot be found in the given format
+ * @HTTP 500 Internal Error
+ * @ResponseHeader Content-Type (for HTTP 406) a list of available metadata
+ * types
+ */
+ @GET
+ @Path(ResourceWebService.MIME_PATTERN + ResourceWebService.UUID_PATTERN)
+ public Response getMetaLocal(@PathParam("uuid") String uuid, @PathParam("mimetype") String mimetype) throws UnsupportedEncodingException {
+ String uri = configurationService.getBaseUri() + "resource/" + uuid;
+ return getMeta(uri, mimetype, uuid);
+ }
+
+ /**
+ * Sets metadata to a given locale resource
+ *
+ * @param uuid
+ * , a unique identifier (must not contain url specific
+ * characters like /,# etc.)
+ * @param mimetype
+ * content-type of the body (metadata) follows the pattern .+/.+
+ * @return HTTP response (success or error)
+ * @HTTP 200 put was successful
+ * @HTTP 400 bad request (e.g. body is empty)
+ * @HTTP 404 resource cannot be found
+ * @HTTP 415 Content-Type is not supported
+ * @HTTP 500 Internal Error
+ * @ResponseHeader Content-Type (for HTTP 415) a list of available types for
+ * metadata
+ */
+ @PUT
+ @Path(ResourceWebService.MIME_PATTERN + ResourceWebService.UUID_PATTERN)
+ public Response putMetaLocal(@PathParam("uuid") String uuid, @PathParam("mimetype") String mimetype, @Context HttpServletRequest request) {
+ String uri = configurationService.getBaseUri() + "resource/" + uuid;
+ return putMeta(uri, mimetype, request);
+ }
+
+ /**
+ * Sets metadata to a given locale resource
+ *
+ * @param uri
+ * , the fully-qualified URI of the resource to create in the
+ * triple store
+ * @param mimetype
+ * content-type of the body (metadata) follows the pattern .+/.+
+ * @return HTTP response (success or error)
+ * @HTTP 200 put was successful
+ * @HTTP 400 bad request (e.g. uri is null)
+ * @HTTP 404 resource cannot be found
+ * @HTTP 415 Content-Type is not supported
+ * @HTTP 500 Internal Error
+ * @ResponseHeader Content-Type (for HTTP 415) a list of available types for
+ * metadata
+ */
+ @PUT
+ @Path(ResourceWebService.MIME_PATTERN)
+ public Response putMetaRemote(@QueryParam("uri") @NotNull String uri, @PathParam("mimetype") String mimetype, @Context HttpServletRequest request)
+ throws UnsupportedEncodingException {
+ return putMeta(URLDecoder.decode(uri, "utf-8"), mimetype, request);
+ }
+
+ /**
+ * Delete metadata of remote resource with given uri
+ *
+ * @param uri
+ * , the fully-qualified URI of the resource to create in the
+ * triple store
+ * @return HTTP response (success or error)
+ * @HTTP 200 resource content deleted
+ * @HTTP 400 bad request (e.g, uri is null)
+ * @HTTP 404 resource or resource metadata not found
+ */
+ @DELETE
+ public Response deleteMetaRemote(@QueryParam("uri") @NotNull String uri) throws UnsupportedEncodingException {
+ try {
+ InterceptingRepositoryConnection connection = new InterceptingRepositoryConnectionWrapper(sesameService.getRepository(), sesameService.getConnection());
+ connection.begin();
+ final Resource subject = connection.getValueFactory().createURI(uri);
+
+ try {
+ connection.addRepositoryConnectionInterceptor(new ResourceSubjectMetadata(subject));
+
+ // delete all triples for given subject
+ connection.remove(subject,null,null);
+
+ return Response.ok().build();
+ } finally {
+ connection.commit();
+ connection.close();
+ }
+
+ } catch (RepositoryException e) {
+ return ResourceWebServiceHelper.buildErrorPage(uri, configurationService.getBaseUri(), Status.INTERNAL_SERVER_ERROR, e.getMessage());
+ }
+ }
+
+ /**
+ * Delete metadata of local resource with given uuid
+ *
+ * @param uuid
+ * , a unique identifier (must not contain url specific
+ * characters like /,# etc.)
+ * @return HTTP response (success or error)
+ * @HTTP 200 resource content deleted
+ * @HTTP 404 resource or resource metadata not found
+ */
+ @DELETE
+ @Path(ResourceWebService.UUID_PATTERN)
+ public Response deleteMetaLocal(@PathParam("uuid") String uuid) throws UnsupportedEncodingException {
+ String uri = configurationService.getBaseUri() + "resource/" + uuid;
+ return deleteMetaRemote(uri);
+ }
+
+ private Response getMeta(String uri, String mimetype, String uuid) throws UnsupportedEncodingException {
+ try {
+ RepositoryConnection conn = sesameService.getConnection();
+
+ try {
+ conn.begin();
+ // FIXME String appendix = uuid == null ? "?uri=" + URLEncoder.encode(uri, "utf-8") :
+ // "/" + uuid;
+ URI resource = conn.getValueFactory().createURI(uri);
+ // create parser
+ final RDFFormat serializer = kiWiIOService.getSerializer(mimetype);
+ if (serializer == null) {
+ Response response = Response.status(406).entity("mimetype can not be processed").build();
+ ResourceWebServiceHelper.addHeader(response, "Content-Type", ResourceWebServiceHelper.appendMetaTypes(kiWiIOService.getProducedTypes()));
+ return response;
+ }
+
+ if(resource != null) {
+
+ final Resource subject = resource;
+
+ StreamingOutput entity = new StreamingOutput() {
+ @Override
+ public void write(OutputStream output) throws IOException, WebApplicationException {
+ // FIXME: This method is executed AFTER the @Transactional!
+ RDFWriter writer = Rio.createWriter(serializer,output);
+ try {
+ RepositoryConnection connection = sesameService.getConnection();
+ try {
+ connection.begin();
+ connection.exportStatements(subject,null,null,true,writer);
+ } finally {
+ connection.commit();
+ connection.close();
+ }
+ } catch (RepositoryException e) {
+ throw new WebApplicationException(e, Status.INTERNAL_SERVER_ERROR);
+ } catch (RDFHandlerException e) {
+ throw new IOException("error while writing RDF data to stream", e);
+ }
+
+ }
+ };
+
+ // build response
+ Response response = Response.ok(entity).lastModified(KiWiSesameUtil.lastModified(resource, conn)).build();
+ response.getMetadata().add("ETag", "W/\"" + ETagGenerator.getWeakETag(conn, resource) + "\"");
+
+ // create the Content-Type header for the response
+ if (mimetype.startsWith("text/") || mimetype.startsWith("application/")) {
+ response.getMetadata().add("Content-Type", mimetype + "; charset=" + ResourceWebService.CHARSET);
+ } else {
+ response.getMetadata().add("Content-Type", mimetype);
+ }
+
+ // create the Link headers for the response
+ List<String> links = new LinkedList<String>();
+
+ // build the link to the human readable content of this resource (if it exists)
+ String contentLink = ResourceWebServiceHelper.buildContentLink(resource, uuid, contentService.getContentType(resource), configurationService);
+ if(!"".equals(contentLink)) {
+ links.add(contentLink);
+ }
+
+ if (links.size() > 0) {
+ response.getMetadata().add("Link", CollectionUtils.fold(links, ", "));
+ }
+ return response;
+ } else {
+ return Response.status(Response.Status.NOT_FOUND).entity("resource with URI "+uri+" does not exist").build();
+ }
+ } finally {
+ if (conn.isOpen()) {
+ conn.commit();
+ conn.close();
+ }
+ }
+ } catch (RepositoryException e) {
+ return ResourceWebServiceHelper.buildErrorPage(uri, configurationService.getBaseUri(), Status.INTERNAL_SERVER_ERROR, e.getMessage());
+ }
+ }
+
+ public Response putMeta(String uri, String mimetype, HttpServletRequest request) {
+ try {
+ // create parser
+ RDFFormat parser = kiWiIOService.getParser(mimetype);
+ if (parser == null) {
+ Response response = Response.status(Status.UNSUPPORTED_MEDIA_TYPE).entity("media type " + mimetype + " not supported").build();
+ ResourceWebServiceHelper.addHeader(response, "Content-Type", ResourceWebServiceHelper.appendMetaTypes(kiWiIOService.getProducedTypes()));
+ return response;
+ }
+ if (request.getContentLength() == 0)
+ return ResourceWebServiceHelper.buildErrorPage(uri, configurationService.getBaseUri(), Status.BAD_REQUEST, "content may not be empty in resource update");
+
+ // a intercepting connection that filters out all triples that have
+ // the wrong subject
+ InterceptingRepositoryConnection connection = new InterceptingRepositoryConnectionWrapper(sesameService.getRepository(), sesameService.getConnection());
+ //RepositoryConnection connection = sesameService.getConnection();
+ try {
+ connection.begin();
+ final Resource subject = connection.getValueFactory().createURI(uri);
+
+ connection.addRepositoryConnectionInterceptor(new ResourceSubjectMetadata(subject));
+
+ // delete all triples for given subject
+ connection.remove(subject, null, null, (Resource)null);
+
+ // add RDF data from input to the suject
+ connection.add(request.getReader(), configurationService.getBaseUri(), parser, contextService.getDefaultContext());
+ } finally {
+ connection.commit();
+ connection.close();
+ }
+ return Response.ok().build();
+ } catch (RepositoryException e) {
+ return ResourceWebServiceHelper.buildErrorPage(uri, configurationService.getBaseUri(), Status.INTERNAL_SERVER_ERROR, e.getMessage());
+ } catch (IOException e) {
+ return ResourceWebServiceHelper.buildErrorPage(uri, configurationService.getBaseUri(), Status.INTERNAL_SERVER_ERROR, "could not read request body");
+ } catch (RDFParseException e) {
+ return ResourceWebServiceHelper.buildErrorPage(uri, configurationService.getBaseUri(), Status.UNSUPPORTED_MEDIA_TYPE, "could not parse request body");
+ }
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-marmotta/blob/c32963d5/lmf-core/src/main/java/kiwi/core/webservices/resource/ResourceWebService.java
----------------------------------------------------------------------
diff --git a/lmf-core/src/main/java/kiwi/core/webservices/resource/ResourceWebService.java b/lmf-core/src/main/java/kiwi/core/webservices/resource/ResourceWebService.java
new file mode 100644
index 0000000..b433554
--- /dev/null
+++ b/lmf-core/src/main/java/kiwi/core/webservices/resource/ResourceWebService.java
@@ -0,0 +1,613 @@
+/**
+ * Copyright (C) 2013 Salzburg Research.
+ *
+ * Licensed 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 kiwi.core.webservices.resource;
+
+import static javax.ws.rs.core.Response.status;
+
+import at.newmedialab.sesame.commons.http.ETagGenerator;
+import at.newmedialab.sesame.commons.repository.ResourceUtils;
+import kiwi.core.api.config.ConfigurationService;
+import kiwi.core.api.content.ContentService;
+import kiwi.core.api.io.LMFIOService;
+import kiwi.core.api.triplestore.SesameService;
+import kiwi.core.services.sesame.KiWiSesameUtil;
+import org.apache.commons.lang.StringUtils;
+import org.apache.marmotta.commons.http.ContentType;
+import org.apache.marmotta.commons.http.LMFHttpUtils;
+import org.openrdf.model.Resource;
+import org.openrdf.model.URI;
+import org.openrdf.repository.RepositoryConnection;
+import org.openrdf.repository.RepositoryException;
+import org.slf4j.Logger;
+
+import javax.enterprise.context.ApplicationScoped;
+import javax.inject.Inject;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.*;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.Response.ResponseBuilder;
+import javax.ws.rs.core.Response.Status;
+
+import java.io.UnsupportedEncodingException;
+import java.net.URISyntaxException;
+import java.net.URLDecoder;
+import java.util.Collections;
+import java.util.List;
+import java.util.UUID;
+
+/**
+ * Resource Web Services
+ *
+ * @author Thomas Kurz
+ * @author Sergio Fernández
+ */
+@ApplicationScoped
+@Path("/" + ConfigurationService.RESOURCE_PATH)
+public class ResourceWebService {
+
+ @Inject
+ private Logger log;
+
+ public static final String CHARSET = "utf-8";
+
+ public static final String MIME_PATTERN = "/{mimetype:[^/]+/[^/]+}";
+
+ public static final String UUID_PATTERN = "/{uuid:[^#?]+}";
+
+ @Inject
+ private ConfigurationService configurationService;
+
+ @Inject
+ private ContentService contentService;
+
+ @Inject
+ private LMFIOService kiWiIOService;
+
+ @Inject
+ private SesameService sesameService;
+
+ @Inject
+ private ContentWebService contentWebService;
+
+ @Inject
+ private MetaWebService metaWebService;
+
+ /**
+ * Return the options that are available for a resource with the given URI.
+ *
+ * @param uri
+ * , the fully-qualified URI of the resource to create in the
+ * triple store
+ * @return HTTP response (empty body)
+ * @ResponseHeader Access-Control-Allow-Methods the HTTP methods that are allowable for the given resource
+ * @ResponseHeader Access-Control-Allow-Origin the origins that are allowable for cross-site scripting on this resource
+ */
+ @OPTIONS
+ public Response optionsResourceRemote(@QueryParam("uri") String uri, @HeaderParam("Access-Control-Request-Headers") String reqHeaders) {
+ if(reqHeaders == null) {
+ reqHeaders = "Accept, Content-Type";
+ }
+
+ if(uri == null)
+ return Response.ok()
+ .header("Allow", "POST")
+ .header("Access-Control-Allow-Methods","POST")
+ .header("Access-Control-Allow-Headers", reqHeaders)
+ .header("Access-Control-Allow-Origin", configurationService.getStringConfiguration("kiwi.allow_origin","*"))
+ .build();
+ else {
+ try {
+ uri = URLDecoder.decode(uri, "utf-8");
+
+ RepositoryConnection conn = sesameService.getConnection();
+ try {
+ conn.begin();
+ URI resource = ResourceUtils.getUriResource(conn,uri);
+ conn.commit();
+
+ if(resource != null) return Response.ok()
+ .header("Allow","PUT, GET, DELETE")
+ .header("Access-Control-Allow-Methods","PUT, GET, DELETE")
+ .header("Access-Control-Allow-Headers",reqHeaders)
+ .header("Access-Control-Allow-Origin",configurationService.getStringConfiguration("kiwi.allow_origin","*"))
+ .build();
+ else
+ return Response.ok()
+ .header("Allow", "POST")
+ .header("Access-Control-Allow-Methods","POST")
+ .header("Access-Control-Allow-Headers",reqHeaders)
+ .header("Access-Control-Allow-Origin",configurationService.getStringConfiguration("kiwi.allow_origin","*"))
+ .build();
+ } finally {
+ conn.close();
+ }
+
+ } catch(UnsupportedEncodingException ex) {
+ return Response.serverError().entity(ex.getMessage()).build();
+ } catch (RepositoryException ex) {
+ return Response.serverError().entity(ex.getMessage()).build();
+ }
+ }
+
+ }
+
+ /**
+ * Return the options that are available for a resource with the given URI.
+ *
+ * @param uuid
+ * , a unique identifier (must not contain url specific
+ * characters like /,# etc.)
+ * @return HTTP response (empty body)
+ * @ResponseHeader Access-Control-Allow-Methods the HTTP methods that are allowable for the given resource
+ * @ResponseHeader Access-Control-Allow-Origin the origins that are allowable for cross-site scripting on this resource
+ */
+ @OPTIONS
+ @Path(UUID_PATTERN)
+ public Response optionsResourceLocal(@PathParam("uuid") String uuid, @HeaderParam("Access-Control-Request-Headers") String reqHeaders) {
+ String uri = configurationService.getBaseUri() + "resource/" + uuid;
+
+ if(reqHeaders == null) {
+ reqHeaders = "Accept, Content-Type";
+ }
+
+ if(uuid == null)
+ return Response.status(Status.NOT_FOUND).build();
+ else {
+ try {
+ uri = URLDecoder.decode(uri, "utf-8");
+ RepositoryConnection conn = sesameService.getConnection();
+ try {
+ conn.begin();
+ URI resource = ResourceUtils.getUriResource(conn,uri);
+ conn.commit();
+
+
+ if(resource != null) return Response.ok()
+ .header("Allow","PUT, GET, DELETE")
+ .header("Access-Control-Allow-Methods","PUT, GET, DELETE")
+ .header("Access-Control-Allow-Headers",reqHeaders)
+ .header("Access-Control-Allow-Origin",configurationService.getStringConfiguration("kiwi.allow_origin","*"))
+ .build();
+ else
+ return Response.ok()
+ .header("Allow","POST")
+ .header("Access-Control-Allow-Methods","POST")
+ .header("Access-Control-Allow-Headers",reqHeaders)
+ .header("Access-Control-Allow-Origin",configurationService.getStringConfiguration("kiwi.allow_origin","*"))
+ .build();
+
+ } finally {
+ conn.close();
+ }
+ } catch(UnsupportedEncodingException ex) {
+ return Response.serverError().entity(ex.getMessage()).build();
+ } catch (RepositoryException ex) {
+ return Response.serverError().entity(ex.getMessage()).build();
+ }
+ }
+
+ }
+
+ // ******************************************* P O S T
+ // ***********************************
+ // **************** POST (New or Remote)
+
+ /**
+ * Creates new resource with given uri. If no uri is defined it creates a
+ * local uri with random uuid
+ *
+ * @param uri
+ * , the fully-qualified URI of the resource to create in the
+ * triple store
+ * @return HTTP response (body is a String message)
+ * @HTTP 201 new resource created
+ * @HTTP 302 resource already exists
+ * @HTTP 500 Internal Error
+ * @ResponseHeader Location the url of the new/found resource
+ */
+ @POST
+ public Response postNewOrRemote(@QueryParam("uri") String uri) throws UnsupportedEncodingException {
+ if (uri == null)
+ return post(configurationService.getBaseUri() + "resource/" + UUID.randomUUID().toString(), false);
+ else
+ return post(uri, true);
+ }
+
+ // **************** POST (Locale)
+
+ /**
+ * Creates new local resource with given uuid.
+ *
+ * @param uuid a unique identifier (must not contain url specific characters like /,# etc.)
+ * @return HTTP response (body is a String message)
+ * @HTTP 201 new resource created
+ * @HTTP 200 resource already exists
+ * @HTTP 500 Internal Error
+ * @ResponseHeader Location the url of the new/found resource
+ */
+ @POST
+ @Path(UUID_PATTERN)
+ public Response postLocal(@PathParam("uuid") String uuid) throws UnsupportedEncodingException {
+ return post(configurationService.getBaseUri() + "resource/" + uuid, false);
+ }
+
+ // **************** POST (Generic)
+ private Response post(String uri, boolean remote) throws UnsupportedEncodingException {
+ try {
+ RepositoryConnection conn = sesameService.getConnection();
+ try {
+ conn.begin();
+ String location = remote ? configurationService.getServerUri() + ConfigurationService.RESOURCE_PATH + "?uri=" + uri : uri;
+ Response.Status status;
+ if (ResourceUtils.getUriResource(conn,uri) != null) {
+ status = Status.OK;
+ } else {
+ conn.getValueFactory().createURI(uri);
+ status = Status.CREATED;
+ }
+ Response response = status(status).entity(uri).build();
+ response.getMetadata().add("Location", location);
+ response.getMetadata().add("Vary", "Content-Type");
+ return response;
+ } finally {
+ conn.commit();
+ conn.close();
+ }
+ } catch (RepositoryException ex) {
+ return Response.serverError().entity(ex.getMessage()).build();
+ }
+ }
+
+ /**
+ * Returns a link to a local resource (data or content) with the given uuid
+ * and an accepted return type
+ *
+ * @param uuid
+ * , a unique identifier (must not contain url specific
+ * characters like /,# etc.)
+ * @return a link to a local resource's data or content
+ * @HTTP 303 resource can be found in the requested format under Location
+ * @HTTP 404 resource cannot be found
+ * @HTTP 406 resource cannot be found in the given format
+ * @HTTP 500 Internal Error
+ * @RequestHeader Accept accepted mimetypes; value must follow the pattern
+ * (.+/.+(;rel=(content|meta))?,)+
+ * @ResponseHeader Location (for HTTP 303) the url of the resource in the
+ * requested format
+ * @ResponseHeader Content-Type (for HTTP 406) a list of available types
+ * (content and meta)
+ */
+ @GET
+ @Path(UUID_PATTERN)
+ public Response getLocal(@PathParam("uuid") String uuid, @HeaderParam("Accept") String types) throws UnsupportedEncodingException {
+ String uri = configurationService.getBaseUri() + "resource/" + uuid;
+ try {
+ return get(uri, types, uuid);
+ } catch (URISyntaxException e) {
+ return Response.serverError().entity(e.getMessage()).build();
+ }
+ }
+
+ // **************** GET REMOTE (eq. generic) ***********************
+
+ /**
+ * Returns a link to a remote resource (data or content) with the given uri
+ * and an accepted return type
+ *
+ * @param uri the fully-qualified URI of the resource to create in the triple store
+ * @param format forces representation format (optional, normal content negotiation performed if empty)
+ * @HTTP 303 resource can be found in the requested format under Location
+ * @HTTP 400 bad request (maybe uri is not defined)
+ * @HTTP 404 resource cannot be found
+ * @HTTP 406 resource cannot be found in the given format
+ * @HTTP 500 Internal Error
+ * @RequestHeader Accept accepted mimetypes; value must follow the pattern
+ * (.+/.+(;rel=(content|meta))?,)+
+ * @ResponseHeader Location the url of the resource in the requested format
+ * @ResponseHeader Content-Type (for HTTP 406) a list of available types
+ * (content and meta)
+ */
+ @GET
+ public Response getRemote(@QueryParam("uri") String uri, @QueryParam("format") String format, @HeaderParam("Accept") String types)
+ throws UnsupportedEncodingException {
+ try {
+ if (uri != null) {
+ if (format != null && StringUtils.isNotBlank(format)) {
+ types = format;
+ }
+ //TODO: add 'If-None-Match' support, sending a '304 Not Modified' when the ETag matches
+ return get(uri, types, null);
+ } else
+ return Response.status(400).entity("uri may not be null").build();
+ } catch (URISyntaxException e) {
+ return Response.serverError().entity(e.getMessage()).build();
+ }
+ }
+
+ private Response get(String uri, String types, String uuid) throws URISyntaxException, UnsupportedEncodingException {
+ try {
+
+ RepositoryConnection conn = sesameService.getConnection();
+ try {
+ conn.begin();
+ URI resource = ResourceUtils.getUriResource(conn, uri);
+ if (resource == null) return ResourceWebServiceHelper.buildErrorPage(uri, configurationService.getBaseUri(), Response.Status.NOT_FOUND, "the requested resource could not be found in LMF right now, but may be available again in the future");
+ // FIXME String appendix = uuid == null ? "?uri=" + URLEncoder.encode(uri, "utf-8") :
+ // "/" + uuid;
+
+ List<ContentType> offeredTypes = LMFHttpUtils.parseStringList(kiWiIOService.getProducedTypes());
+ for(ContentType t : offeredTypes) {
+ t.setParameter("rel", "meta");
+ }
+ String contentmime = contentService.getContentType(resource);
+ if(contentmime != null) {
+ ContentType tContent = LMFHttpUtils.parseContentType(contentmime);
+ tContent.setParameter("rel", "content");
+ offeredTypes.add(0,tContent);
+ }
+
+ if (types == null || types.equals("")) {
+ return build406(Collections.<ContentType>emptyList(), offeredTypes);
+ }
+
+ List<ContentType> acceptedTypes = LMFHttpUtils.parseAcceptHeader(types);
+ ContentType bestType = LMFHttpUtils.bestContentType(offeredTypes,acceptedTypes);
+
+ log.debug("identified best type: {}",bestType);
+
+ if(bestType != null) {
+ Response response = buildGetResponse(resource, uuid, bestType);
+ response.getMetadata().add("Last-Modified", KiWiSesameUtil.lastModified(resource, conn));
+ response.getMetadata().add("ETag", "W/\"" + ETagGenerator.getWeakETag(conn, resource) + "\"");
+ return response;
+ } else {
+ return build406(acceptedTypes, offeredTypes);
+ }
+ } finally {
+ conn.commit();
+ conn.close();
+ }
+ } catch (IllegalArgumentException e) {
+ return Response.status(Response.Status.NOT_FOUND).entity(e.getMessage()).build();
+ } catch (RepositoryException e) {
+ return Response.serverError().entity(e.getMessage()).build();
+ }
+ }
+
+ private Response build406(List<ContentType> acceptedTypes, List<ContentType> offeredTypes) {
+ ResponseBuilder response = Response.status(Status.NOT_ACCEPTABLE);
+ response.header("Content-Type", "text/plain; charset=UTF-8");
+
+ StringBuilder entity = new StringBuilder();
+ entity.append("Could not find matching type for "+acceptedTypes+"\n");
+ entity.append("choose one of the following:");
+ for (ContentType contentType : offeredTypes) {
+ entity.append(" ").append(contentType).append("\n");
+ }
+ entity.append("\n");
+ response.entity(entity.toString());
+ return response.build();
+ }
+
+
+
+
+ // ******************************************* P U T
+ // ***********************************
+ // **************** PUT LOCALE ***********************
+
+ /**
+ * Returns a Link where the given data (metadata or content) can be put to
+ * the local resource
+ *
+ * @param uuid
+ * , a unique identifier (must not contain url specific
+ * characters like /,# etc.)
+ * @return a link where the data can be put (depends on Content-Type)
+ * @HTTP 303 resource in given format can be put under Location
+ * @HTTP 404 resource cannot be found
+ * @HTTP 415 Content-Type is not supported
+ * @HTTP 500 Internal Error
+ * @RequestHeader Content-Type type of the body; value must follow the
+ * pattern .+/.+(;rel=(content|meta))?
+ * @ResponseHeader Location (for HTTP 303) the url where data can be put
+ */
+ @PUT
+ @Path(UUID_PATTERN)
+ public Response putLocal(@PathParam("uuid") String uuid, @HeaderParam("Content-Type") String type, @Context HttpServletRequest request) throws UnsupportedEncodingException {
+ String uri = configurationService.getBaseUri() + "resource/" + uuid;
+ try {
+ return put(uri, type, uuid,request);
+ } catch (URISyntaxException e) {
+ return Response.serverError().entity(e.getMessage()).build();
+ }
+ }
+
+ // **************** PUT REMOTE (eq. generic) ***********************
+
+ /**
+ * Returns a Link where the given data (metadata or content) can be put to
+ * the remote resource
+ *
+ * @param uri
+ * , the fully-qualified URI of the resource to create in the
+ * triple store
+ * @return a link where the data can be put (depends on Content-Type)
+ * @HTTP 303 resource in given format can be put under Location
+ * @HTTP 400 bad request (e.g. uri is null)
+ * @HTTP 404 resource cannot be found
+ * @HTTP 415 Content-Type is not supported
+ * @HTTP 500 Internal Error
+ * @RequestHeader Content-Type type of the body; value must follow the
+ * pattern .+/.+(;rel=(content|meta))?
+ * @ResponseHeader Location (for HTTP 303) the url where data can be put
+ */
+ @PUT
+ public Response putRemote(@QueryParam("uri") String uri, @HeaderParam("Content-Type") String type, @Context HttpServletRequest request) throws UnsupportedEncodingException {
+ try {
+ if (uri != null) return put(URLDecoder.decode(uri, "utf-8"), type, null, request);
+ else
+ return Response.status(400).entity("uri may not be null").build();
+ } catch (URISyntaxException e) {
+ return Response.serverError().entity(e.getMessage()).build();
+ }
+ }
+
+ private Response put(String uri, String mimetype, String uuid, HttpServletRequest request) throws URISyntaxException, UnsupportedEncodingException {
+ try {
+ // FIXME String appendix = uuid == null ? "?uri=" + URLEncoder.encode(uri, "utf-8") :
+ // "/" + uuid;
+ if (mimetype == null) return Response.status(400).entity("content-type may not be null").build();
+
+
+ // the offered types are those sent by the client in the Content-Type header; if the rel attribute is not
+ // given, we add the default rel value
+ List<ContentType> types = LMFHttpUtils.parseAcceptHeader(mimetype);
+ for(ContentType type : types) {
+ if(type.getParameter("rel") == null) {
+ type.setParameter("rel",configurationService.getStringConfiguration("linkeddata.mime.rel.default", "meta"));
+ }
+ }
+
+ // the acceptable types are all types for content and the meta types we have parsers for; we do not care so
+ // much about the order ...
+ List<ContentType> acceptable = LMFHttpUtils.parseStringList(kiWiIOService.getProducedTypes());
+ for(ContentType a : acceptable) {
+ a.setParameter("rel", "meta");
+ }
+ ContentType allContent = new ContentType("*","*");
+ allContent.setParameter("rel", "content");
+ acceptable.add(0,allContent);
+
+ // determine the best match between the offered types and the acceptable types
+ ContentType bestType = LMFHttpUtils.bestContentType(types,acceptable);
+
+ if (bestType != null) {
+ if (configurationService.getBooleanConfiguration("linkeddata.redirect.put", true)) {
+ final RepositoryConnection con = sesameService.getConnection();
+ try {
+ con.begin();
+ URI resource = ResourceUtils.getUriResource(con, uri);
+ con.commit();
+ return Response
+ .status(configurationService.getIntConfiguration("linkeddata.redirect.status", 303))
+ // .location(new URI(configurationService.getBaseUri() +
+ // bestType.getParameter("rel") + "/" + bestType.getMime() + appendix))
+ .location(new java.net.URI(ResourceWebServiceHelper.buildResourceLink(resource, bestType, configurationService)))
+ .build();
+ } finally {
+ con.close();
+ }
+ } else {
+ if("content".equalsIgnoreCase(bestType.getParameter("rel")))
+ return contentWebService.putContent(uri, bestType.getMime(), request);
+ else if ("meta".equalsIgnoreCase(bestType.getParameter("rel")))
+ return metaWebService.putMeta(uri, bestType.getMime(), request);
+ else
+ return Response.serverError().entity("request did not specify whether it uploads content or metadata; use rel=content|meta attribute in Content-Type header").build();
+ }
+ } else {
+ Response response = Response.status(415).entity("type " + mimetype + " not supported").build();
+ ResourceWebServiceHelper.addHeader(response, "Content-Type", ResourceWebServiceHelper.appendMetaTypes(kiWiIOService.getAcceptTypes()));
+ return response;
+ }
+ } catch (RepositoryException e) {
+ return Response.serverError().entity(e.getMessage()).build();
+ }
+ }
+
+ // ******************************************* D E L E T E
+ // ***********************************
+ // **************** DELETE RESOURCE ***********************
+
+ /**
+ * Delete remote resource with given uri
+ *
+ * @param uri
+ * , the fully-qualified URI of the resource to create in the
+ * triple store
+ * @return HTTP response (success or error)
+ * @HTTP 200 resource deleted
+ * @HTTP 400 bad request (e.g, uri is null)
+ * @HTTP 404 resource not found
+ */
+ @DELETE
+ public Response deleteResourceRemote(@QueryParam("uri") String uri) throws UnsupportedEncodingException {
+
+ if (uri != null) {
+ try {
+ RepositoryConnection conn = sesameService.getConnection();
+ try {
+ conn.begin();
+ Resource resource = ResourceUtils.getUriResource(conn,URLDecoder.decode(uri, "utf-8"));
+ if (resource != null) {
+ ResourceUtils.removeResource(conn,resource);
+ return Response.ok().build();
+ } else
+ return Response.status(Response.Status.NOT_FOUND).build();
+ } finally {
+ conn.commit();
+ conn.close();
+ }
+ } catch (RepositoryException ex) {
+ return Response.serverError().entity(ex.getMessage()).build();
+ }
+ } else
+ return Response.status(400).entity("uri may not be null").build();
+ }
+
+ /**
+ * Delete local resource with given uuid
+ *
+ * @param uuid
+ * , a unique identifier (must not contain url specific
+ * characters like /,# etc.)
+ * @return HTTP response (success or error)
+ * @HTTP 200 resource deleted
+ * @HTTP 404 resource not found
+ */
+ @DELETE
+ @Path(UUID_PATTERN)
+ public Response deleteResourceLocal(@PathParam("uuid") String uuid) throws UnsupportedEncodingException {
+ String uri = configurationService.getBaseUri() + "resource/" + uuid;
+ return deleteResourceRemote(uri);
+ }
+
+ private Response buildGetResponse(URI resource, String uuid,
+ ContentType type) {
+ try {
+
+ return Response
+ .status(configurationService.getIntConfiguration(
+ "linkeddata.redirect.status", 303))
+ .header("Vary", "Accept")
+ .header("Content-Type", type.toString())
+ // .location(new URI(configurationService.getBaseUri() +
+ // type.getParameter("rel") + "/" + type.getType() + "/"
+ // +type.getSubtype() +
+ // appendix))
+ .location(
+ new java.net.URI(ResourceWebServiceHelper.buildResourceLink(resource,
+ type.getParameter("rel"), type.getMime(), configurationService)))
+ .build();
+
+ } catch (Exception e) {
+ return Response.serverError().build();
+ }
+ }
+
+}