You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@marmotta.apache.org by ja...@apache.org on 2013/02/21 16:30:45 UTC
[11/55] MARMOTTA-106: renamed packages in marmotta-commons
http://git-wip-us.apache.org/repos/asf/incubator-marmotta/blob/5f62ec33/commons/marmotta-commons/src/main/java/at/newmedialab/sesame/commons/repository/ResourceUtils.java
----------------------------------------------------------------------
diff --git a/commons/marmotta-commons/src/main/java/at/newmedialab/sesame/commons/repository/ResourceUtils.java b/commons/marmotta-commons/src/main/java/at/newmedialab/sesame/commons/repository/ResourceUtils.java
deleted file mode 100644
index d7e865c..0000000
--- a/commons/marmotta-commons/src/main/java/at/newmedialab/sesame/commons/repository/ResourceUtils.java
+++ /dev/null
@@ -1,1299 +0,0 @@
-/**
- * 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 at.newmedialab.sesame.commons.repository;
-
-import at.newmedialab.sesame.commons.model.Namespaces;
-import com.google.common.base.Function;
-import com.google.common.base.Predicate;
-import com.google.common.collect.Iterables;
-import com.google.common.collect.Iterators;
-import org.openrdf.model.*;
-import org.openrdf.repository.RepositoryConnection;
-import org.openrdf.repository.RepositoryException;
-import org.openrdf.repository.RepositoryResult;
-import org.openrdf.repository.sail.SailRepositoryConnection;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.*;
-
-/**
- * Utility methods for simplifying certain common tasks. All methods are static and take as first argument a
- * RepositoryConnection that needs to be managed by the caller (i.e. requested from the repository and closed after use).
- *
- * <p/>
- * Author: Sebastian Schaffert
- */
-public class ResourceUtils {
-
- private static Logger log = LoggerFactory.getLogger(ResourceUtils.class);
-
- // *****************************************************************************************************
- // methods for retrieving resources
- // *****************************************************************************************************
-
- /**
- * Check whenever the resource actually exists. Since this could be under different
- * interpretations, this implementation only checks for outgoing triples.
- *
- * @param conn connection with the repository
- * @param uri uri of the resource to check
- * @return resource exists or not
- * @deprecated the name of this method is missleading. use {@link #isSubject(RepositoryConnection, String)}.
- */
- public static boolean existsResource(RepositoryConnection conn, String uri) {
- return existsStatement(conn, conn.getValueFactory().createURI(uri), null, null, null);
- }
-
- /**
- * Check whether the uri is ever used as subject.
- * @param conn connection with the repository
- * @param uri uri of the resource to check
- * @return true if the uri is ever used as subject.
- */
- public static boolean isSubject(RepositoryConnection conn, String uri) {
- return existsStatement(conn, conn.getValueFactory().createURI(uri), null, null, null);
- }
-
- /**
- * Check whether the uri is ever used as context.
- * @param conn connection with the repository
- * @param uri uri of the resource to check
- * @return true if the uri is ever used as context.
- */
- public static boolean isContext(RepositoryConnection conn, String uri) {
- return existsStatement(conn, null, null, null, conn.getValueFactory().createURI(uri));
- }
-
- public static boolean existsStatement(RepositoryConnection conn, Resource subj, URI pred, Value object, Resource ctx) {
- try {
- RepositoryResult<Statement> stmts = conn.getStatements(subj, pred, object, true, ctx);
- try {
- return stmts.hasNext();
- } finally {
- stmts.close();
- }
- } catch (RepositoryException e) {
- log.error(e.getMessage());
- return false;
- }
- }
-
- /**
- * Retrieve the KiWiUriResource with the given URI if it exists, or return null if it doesn't exist.
- * A Resource exists if and only if it is used in a Statement, i.e. it is uses either as Subject, Context, Predicate or Object.
- * @param uri
- * @return the URI or null if the Resource is not used.
- * @deprecated this method does not work as promised. <b>DO NOT USE IT</b>
- */
- @Deprecated
- public static URI getUriResource(RepositoryConnection con, String uri) {
- URI r = con.getValueFactory().createURI(uri);
- if (isSubject(con, uri) || isContext(con, uri) || existsStatement(con, null, r, null, null) || existsStatement(con, null, null, r, null)) {
- return r;
- } else {
- return null;
- }
-// if(con instanceof SailRepositoryConnection && ((SailRepositoryConnection)con).getSailConnection() instanceof ResourceConnection) {
-// return ((ResourceConnection) ((SailRepositoryConnection) con).getSailConnection()).getURI(uri);
-// } else {
-// return r;
-// }
- }
-
- /**
- * Retrieve the KiWiAnonResource with the given ID if it exists, or return null if it doesn't exist.
- * @param id
- * @return
- */
- public static BNode getAnonResource(RepositoryConnection con, String id) {
- if(con instanceof SailRepositoryConnection && ((SailRepositoryConnection)con).getSailConnection() instanceof ResourceConnection) {
- return ((ResourceConnection) ((SailRepositoryConnection) con).getSailConnection()).getBNode(id);
- } else {
- return con.getValueFactory().createBNode(id);
- }
- }
-
- /**
- * Remove the resource given as argument from the triple store and resource repository. This method will
- * remove all triples where the resource appears as subject, predicate, object or context.
- *
- * @param con
- * @param resource
- */
- public static void removeResource(RepositoryConnection con, Resource resource) throws RepositoryException {
- if(con instanceof SailRepositoryConnection && ((SailRepositoryConnection)con).getSailConnection() instanceof ResourceConnection) {
- ((ResourceConnection) ((SailRepositoryConnection) con).getSailConnection()).removeResource(resource);
- } else {
- con.remove(resource,null,null);
- if(resource instanceof URI) {
- con.remove((Resource)null,(URI)resource,null);
- }
- con.remove((Resource)null,null,resource);
- con.remove((Resource)null,null,null,resource);
- }
- }
-
- /**
- * List all resources contained in the KiWi System, regardless of knowledge space or type. Since this
- * operation works directly on the triple store, there is no guarantee the result is free of duplicates.
- * In case the underlying connection does not directly support listing resources (i.e. is not an instance of
- * ResourceConnection), the method will iterate over all triples and return their subjects
- *
- * @return
- */
- public static Iterable<Resource> listResources(final RepositoryConnection con) {
- if(con instanceof SailRepositoryConnection && ((SailRepositoryConnection)con).getSailConnection() instanceof ResourceConnection) {
- return new Iterable<Resource>() {
- @Override
- public Iterator<Resource> iterator() {
- try {
- return ResultUtils.unwrap(((ResourceConnection) ((SailRepositoryConnection) con).getSailConnection()).getResources());
- } catch (RepositoryException e) {
- ExceptionUtils.handleRepositoryException(e,ResourceUtils.class);
- return Iterators.emptyIterator();
- }
- }
- };
- } else {
- return listResourcesInternal(con,null,null,null);
- }
- }
-
- /**
- * List all resources of a specific type in the KiWi system.
- *
- * @param type the type of the resources to list
- * @return
- */
- public static Iterable<Resource> listResources(final RepositoryConnection con, Resource type) {
- return listResources(con,type,null);
- }
-
- /**
- * List all resources of a specific type contained in a certain knowledge space in the KiWi system
- *
- * @param context the resource identifying the knowledge space
- * @param type the type of the resources to list
- * @return
- */
- public static Iterable<Resource> listResources(final RepositoryConnection con, final Resource type, final URI context) {
- URI rdf_type = con.getValueFactory().createURI(Namespaces.NS_RDF + "type");
-
- return listResourcesInternal(con,rdf_type,type,context);
- }
-
- /**
- * List all resources that have a specific property set to the given value
- *
- * @param propertyUri
- * @param value the literal value to query for
- * @return
- */
- public static Iterable<Resource> listResourcesByProperty(final RepositoryConnection con, String propertyUri, String value) {
- return listResourcesByProperty(con,propertyUri,value,null);
- }
-
- /**
- * List all resources that have a specific property set to the given value and context
- *
- * @param propertyUri
- * @param value the literal value to query for
- * @return
- */
- public static Iterable<Resource> listResourcesByProperty(final RepositoryConnection con, String propertyUri, String value, URI context) {
- URI property = getUriResource(con,propertyUri);
- Value object = con.getValueFactory().createLiteral(value);
-
- if(property != null) {
- return listResourcesInternal(con,property,object,context);
- } else {
- return Collections.emptySet();
- }
-
- }
-
- /**
- * List resources with the given prefix
- *
- * @param prefix the prefix
- * @param offset
- * @param limit
- */
- public static Iterable<URI> listResourcesByPrefix(final RepositoryConnection con, final String prefix, final int offset, final int limit) {
- if(con instanceof SailRepositoryConnection && ((SailRepositoryConnection)con).getSailConnection() instanceof ResourceConnection) {
- return new Iterable<URI>() {
- @Override
- public Iterator<URI> iterator() {
- try {
- Iterator<URI> result = ResultUtils.unwrap(((ResourceConnection) ((SailRepositoryConnection) con).getSailConnection()).getResources(prefix));
-
- Iterators.advance(result,offset);
-
- if(limit > 0) {
- return Iterators.limit(result,limit);
- } else {
- return result;
- }
- } catch (RepositoryException e) {
- ExceptionUtils.handleRepositoryException(e,ResourceUtils.class);
- return Iterators.emptyIterator();
- }
-
- }
- };
- } else {
- // no direct prefix listing support, need to filter the listResources result
- return new Iterable<URI>() {
- @Override
- public Iterator<URI> iterator() {
- Iterator<URI> result = Iterators.transform(
- Iterators.filter(
- listResources(con).iterator(),
- new Predicate<Resource>() {
- @Override
- public boolean apply(Resource input) {
- return input instanceof URI && input.stringValue().startsWith(prefix);
- }
- }
- ),
- new Function<Resource, URI>() {
- @Override
- public URI apply(Resource input) {
- return (URI)input;
- }
- }
- );
-
- Iterators.advance(result,offset);
-
- if(limit > 0) {
- return Iterators.limit(result,limit);
- } else {
- return result;
- }
- }
- };
- }
- }
-
- /**
- * List resources with the given prefix
- *
- * @param prefix the prefix
- */
- public static Iterable<URI> listResourcesByPrefix(final RepositoryConnection con, String prefix) {
- return listResourcesByPrefix(con,prefix,0,0);
- }
-
- private static Iterable<Resource> listResourcesInternal(final RepositoryConnection con, final URI property, final Value value, final URI context) {
- final Resource[] contexts;
- if(context != null) {
- contexts = new Resource[] { context };
- } else {
- contexts = new Resource[0];
- }
-
- return new Iterable<Resource>() {
- @Override
- public Iterator<Resource> iterator() {
- try {
- return Iterators.filter(
- Iterators.transform(
- ResultUtils.unwrap(con.getStatements(null, property, value, true, contexts)),
- new Function<Statement, Resource>() {
- @Override
- public Resource apply(Statement input) {
- return input.getSubject();
- }
- }),
- new Predicate<Resource>() {
- // filter duplicates by remembering hash codes of visited resources
- private HashSet<Integer> visited = new HashSet<Integer>();
-
- @Override
- public boolean apply(Resource input) {
- if(!visited.contains(input.hashCode())) {
- visited.add(input.hashCode());
- return true;
- } else {
- return false;
- }
- }
- });
- } catch (RepositoryException e) {
- ExceptionUtils.handleRepositoryException(e,ResourceUtils.class);
- return Iterators.emptyIterator();
- }
- }
- };
-
- }
-
- // *****************************************************************************************************
- // methods for working with properties
- // *****************************************************************************************************
-
-
- /**
- * Generic method to query for literal values related to this resource with the property
- * identified by "propLabel" (SeRQL/SPARQL short or long notation). Returns only literal
- * values for which no language has been assigned. For all Spaces!!!
- *
- * @param r
- * @param propLabel
- * @return
- */
- public static String getProperty(RepositoryConnection con, Resource r, String propLabel) throws RepositoryException {
- return getProperty(con,r,propLabel,null, null);
- }
-
- /**
- * Generic method to query for literal values related to this resource with the property
- * identified by "propLabel" (SeRQL/SPARQL short or long notation). Returns only literal
- * values for which no language has been assigned. Only for properties in the given context.
- *
- * @param r
- * @param propLabel
- * @param context
- * @return
- */
- public static String getProperty(RepositoryConnection con, Resource r, String propLabel, URI context) throws RepositoryException {
- return getProperty(con, r, propLabel, null, context);
- }
-
- /**
- * Generic method to query for literal values related to this resource with the property
- * identified by "propLabel" (SeRQL/SPARQL short or long notation) and the given locale. For all spaces!!!
- *
- * @param propLabel label of the property; either RDF short form (e.g. "foaf:mbox") or long form (e.g. <http://xmlns.com/foaf/0.1/mbox>)
- * @param loc
- * @return
- */
- public static String getProperty(RepositoryConnection con, Resource r, String propLabel, Locale loc) throws RepositoryException {
- return getProperty(con, r, propLabel, loc, null);
- }
-
- /**
- * Generic method to query for literal values related to this resource with the property
- * identified by "propLabel" (SeRQL/SPARQL short or long notation) and the given locale. Just for the given context.
- *
- * @param propLabel label of the property; either RDF short form (e.g. "foaf:mbox") or long form (e.g. <http://xmlns.com/foaf/0.1/mbox>)
- * @param loc
- * @return
- */
- public static String getProperty(RepositoryConnection con, Resource r, String propLabel, Locale loc, URI context) throws RepositoryException {
- Literal l = getLiteral(con, r,propLabel,loc, context);
- if (l == null) {
- return null;
- } else {
- return l.stringValue();
- }
- }
-
- /**
- * Generic method to query for literal values related to this resource with the property
- * identified by "propLabel" (SeRQL/SPARQL short or long notation) and the given locale.
- *
- * @param propLabel label of the property; either RDF short form (e.g. "foaf:mbox") or long form (e.g. <http://xmlns.com/foaf/0.1/mbox>)
- * @param loc
- * @return
- */
- private static Literal getLiteral(RepositoryConnection con, Resource r, String propLabel, Locale loc, URI context) throws RepositoryException {
- for(Value node : listOutgoingNodes(con,r,propLabel,context)) {
- if(node instanceof Literal) {
- if(loc == null && ((Literal)node).getLanguage() == null) {
- return (Literal)node;
- } else if(loc != null && ((Literal)node).getLanguage() != null && ((Literal)node).getLanguage().equals(loc.getLanguage().toLowerCase()) ) {
- return (Literal)node;
- }
- }
- }
- return null;
- }
-
- /**
- * Generic method to query for literal values related to this resource with the property
- * identified by "propLabel" (SeRQL/SPARQL short or long notation) and the given locale. For all Spaces!!
- *
- * @param propLabel label of the property; either RDF short form (e.g. "foaf:mbox") or long form (e.g. <http://xmlns.com/foaf/0.1/mbox>)
- * @return
- *
- */
- public static Iterable<String> getProperties(RepositoryConnection con, Resource r, String propLabel) throws RepositoryException {
- return getProperties(con,r,propLabel,null, null);
- }
-
- /**
- * Generic method to query for literal values related to this resource with the property
- * identified by "propLabel" (SeRQL/SPARQL short or long notation) and the given locale. Just for the given space !!
- *
- * @param propLabel label of the property; either RDF short form (e.g. "foaf:mbox") or long form (e.g. <http://xmlns.com/foaf/0.1/mbox>)
- * @return
- *
- */
- public static Iterable<String> getProperties(RepositoryConnection con, Resource r, String propLabel, URI context) throws RepositoryException {
- return getProperties(con, r, propLabel, null, context);
- }
-
- /**
- * Generic method to query for literal values related to this resource with the property
- * identified by "propLabel" (SeRQL/SPARQL short or long notation) and the given locale.
- *
- * @param propLabel label of the property; either RDF short form (e.g. "foaf:mbox") or long
- * form (e.g. <http://xmlns.com/foaf/0.1/mbox>)
- * @param loc
- * @return
- */
- public static Iterable<String> getProperties(RepositoryConnection con, Resource r, String propLabel, Locale loc) throws RepositoryException {
- return getProperties(con, r, propLabel, loc, null);
- }
-
- /**
- * Generic method to query for literal values related to this resource with the property
- * identified by "propLabel" (SeRQL/SPARQL short or long notation) and the given locale.
- * Just for the given space !!
- *
- * @param propLabel label of the property; either RDF short form (e.g. "foaf:mbox") or long
- * form (e.g. <http://xmlns.com/foaf/0.1/mbox>)
- * @param loc
- * @return
- */
- public static Iterable<String> getProperties(RepositoryConnection con, Resource r, String propLabel, Locale loc, URI context) throws RepositoryException {
- return Iterables.transform(listLiterals(con, r,propLabel, loc,context), new Function<Literal, String>() {
- @Override
- public String apply(Literal input) {
- return input.getLabel();
- }
- });
- }
-
- /**
- * Generic method to query for literal values related to this resource with the property
- * identified by "propLabel" (SeRQL/SPARQL short or long notation) and the given locale.
- *
- * @param propLabel label of the property; either RDF short form (e.g. "foaf:mbox") or long form (e.g. <http://xmlns.com/foaf/0.1/mbox>)
- * @param loc
- * @return
- */
- private static Iterable<Literal> listLiterals(RepositoryConnection con, Resource r, String propLabel, final Locale loc, URI context) throws RepositoryException {
- return Iterables.filter(
- Iterables.filter(listOutgoingNodes(con, r, propLabel, context), Literal.class),
- new Predicate<Literal>() {
- @Override
- public boolean apply(Literal input) {
- return input.getLanguage() == null && loc == null ||
- input.getLanguage() != null && input.getLanguage().equals(loc.getLanguage().toLowerCase());
- }
- }
- );
- }
-
- /**
- * Generic method to set the literal value of a property of this resource to the provided
- * value without setting a language. For the given context.
- *
- * @param propLabel the SeRQL or SPARQL short or long notation for the property
- * @param propValue the String value of this property
- * @throws NamespaceResolvingException
- */
- //public static void setProperty(RepositoryConnection con, Resource r, String propLabel, String propValue, URI context) throws RepositoryException;
-
- /**
- * Generic method to set the literal value of a property of this resource to the provided
- * value without setting a language. For all spaces!!!
- *
- * @param propLabel the SeRQL or SPARQL short or long notation for the property
- * @param propValue the String value of this property
- */
- public static void setProperty(RepositoryConnection con, Resource r, String propLabel, String propValue) throws RepositoryException {
- setProperty(con,r,propLabel,propValue,(URI)null);
- }
-
- /**
- * Generic method to set the literal value of a property of this resource to the provided
- * value in the provided language. For all spaces.
- *
- * @param propLabel the SeRQL or SPARQL short or long notation for the property
- * @param propValue the String value of this property
- * @param context a context
- */
- public static <T> void setProperty(RepositoryConnection con, Resource r, String propLabel, String propValue, URI context) throws RepositoryException {
- setProperty(con,r,propLabel,propValue,null, context);
- }
-
- /**
- * Generic method to set the literal value of a property of this resource to the provided
- * value in the provided language. For all spaces.
- *
- * @param propLabel the SeRQL or SPARQL short or long notation for the property
- * @param propValue the String value of this property
- * @param loc the Locale representing the language of this property
- */
- public static <T> void setProperty(RepositoryConnection con, Resource r, String propLabel, String propValue, Locale loc) throws RepositoryException {
- setProperty(con, r,propLabel,propValue,null, null);
- }
-
- /**
- * Generic method to query for literal values related to this resource with the property
- * identified by "propLabel" (SeRQL/SPARQL short or long notation) and the given locale.
- * context define the knowledgespace in which this operation is. For the given context.
- *
- * @param propLabel label of the property; either RDF short form (e.g. "foaf:mbox") or long
- * form (e.g. <http://xmlns.com/foaf/0.1/mbox>)
- * @param loc
- * @param context context in which this property will set
- * @return
- */
- public static <T> void setProperty(RepositoryConnection con, Resource r, String propLabel, String propValue, Locale loc, URI context) throws RepositoryException {
- if(propValue != null) {
- Resource[] contexts;
- if(context != null) {
- contexts = new Resource[] { context };
- } else {
- contexts = new Resource[0];
- }
-
- // remove previous property setting
- removeProperty(con,r,propLabel,loc,context);
-
- String prop_uri = resolvePropLabel(con, propLabel);
-
- // then set the new property value
- Literal value = con.getValueFactory().createLiteral(propValue, loc != null ? loc.getLanguage().toLowerCase() : null);
- URI prop = con.getValueFactory().createURI(prop_uri);
- con.add(r, prop, value, contexts);
-
- } else {
- removeProperty(con,r, propLabel,loc,context);
-
- }
- }
-
- /**
- * Remove a property from the RepositoryConnection con, Resource.
- *
- * @param propLabel the property label in SeRQL syntax to remove
- * @return true if the property existed and was removed
- */
- public static boolean removeProperty(RepositoryConnection con, Resource r, String propLabel) throws RepositoryException {
- return removeProperty(con,r,propLabel,(Locale) null);
- }
-
- /**
- * Remove a property from the RepositoryConnection con, Resource. Just for the given space!!!
- *
- * @param propLabel the property label in SeRQL syntax to remove
- * @return true if the property existed and was removed
- */
- public static boolean removeProperty(RepositoryConnection con, Resource r, String propLabel, URI context) throws RepositoryException {
- return removeProperty(con,r,propLabel, null, context);
- }
-
- /**
- * Remove a property from the RepositoryConnection con, Resource. for all spaces !!!
- *
- * @param propLabel the property label in SeRQL syntax to remove
- * @param loc the locale of the property to remove
- * @return true if the property existed and was removed
- */
- public static boolean removeProperty(RepositoryConnection con, Resource r, String propLabel, Locale loc) throws RepositoryException {
- return removeProperty(con,r, propLabel, loc, null);
- }
-
- /**
- * Remove a property from the RepositoryConnection con, Resource. Just for the given space!!!
- *
- * @param propLabel the property label in SeRQL syntax to remove
- * @return true if the property existed and was removed
- */
- public static boolean removeProperty(RepositoryConnection con, Resource r, String propLabel, Locale loc, URI context) throws RepositoryException {
- String uri = resolvePropLabel(con, propLabel);
-
- URI property = con.getValueFactory().createURI(uri);
-
- if(property != null) {
-
- // look up triple that corresponds to property and filter by locale
- List<Statement> remove = new ArrayList<Statement>();
- for(RepositoryResult<Statement> triples = con.getStatements(r,property,null,false,context); triples.hasNext(); ) {
- Statement t = triples.next();
- if(t.getObject() instanceof Literal) {
- if(loc == null || ((Literal)t.getObject()).getLanguage().equals(loc.getLanguage().toLowerCase())) {
- remove.add(t);
- }
- }
- }
-
- // if triple exists, call TripleStore.remove on it
- if(remove.size() > 0) {
- for(Statement triple : remove) {
- con.remove(triple);
- }
- return true;
- }
- }
- return false;
- }
-
- /* incoming and outgoing edges (Statement) */
-
- /**
- * List all outgoing edges from this resource to other resources. Shortcut for listOutgoing(null).
- * For all spaces!!!
- *
- * @return all outgoing edges from this resource
- */
- public static Iterable<? extends Statement> listOutgoing(RepositoryConnection con, Resource r) throws RepositoryException {
- return listOutgoing(con, r, (URI) null);
- }
-
- /**
- * List all outgoing edges from this resource to other resources. Shortcut for listOutgoing(null).
- * Just for the given space
- *
- * @return all outgoing edges from this resource
- */
- public static Iterable<? extends Statement> listOutgoing(RepositoryConnection con, Resource r, URI context) throws RepositoryException {
- return listOutgoing(con, r,null,context);
- }
-
- /**
- * List outgoing edges from this resource to other resources, using the property label passed
- * as argument. If limit is bigger than 0, then a maximum of limit triples will be returned.
- * Otherwise, all triples will be returned.
- * <p/>
- * The parameter propLabel is in the form of a SeRQL or SPARQL id. It can take one of the following
- * values:
- * <ul>
- * <li>a URI enclosed in < >, e.g. <http://www.example.com/myProp></li>
- * <li>a uri prefix, followed by a colon and the property name, e.g. ex:myProp</li>
- * <li>the value "null", in which case all outgoing edges are listed regardless of their label
- * (wildcard)</li>
- * </ul>
- * The result will be an iterable that allows to iterate over Statements.
- *
- * @param propLabel the label of the property to be queried, or null for wildcard
- * @return an iterable over the Statements that are outgoing edges of this resource
- */
- public static Iterable<? extends Statement> listOutgoing(RepositoryConnection con, Resource r, String propLabel) throws RepositoryException {
- return listOutgoing(con, r, propLabel, null);
- }
-
- /**
- * List outgoing edges from this resource to other resources, using the property label passed
- * as argument. If limit is bigger than 0, then a maximum of limit triples will be returned.
- * Otherwise, all triples will be returned.
- * <p/>
- * The parameter propLabel is in the form of a SeRQL or SPARQL id. It can take one of the following
- * values:
- * <ul>
- * <li>a URI enclosed in < >, e.g. <http://www.example.com/myProp></li>
- * <li>a uri prefix, followed by a colon and the property name, e.g. ex:myProp</li>
- * <li>the value "null", in which case all outgoing edges are listed regardless of their label
- * (wildcard)</li>
- * </ul>
- * The result will be an iterable that allows to iterate over Statements. The underlying ClosableIteration will be closed when the last element has
- * been consumed.
- *
- * @param propLabel the label of the property to be queried, or null for wildcard
- * @param context outgoing triples just for the given space
- * @return an iterable over the Statements that are outgoing edges of this resource
- */
- public static Iterable<? extends Statement> listOutgoing(final RepositoryConnection con, final Resource r, final String propLabel, final URI context) throws RepositoryException {
- final URI property;
- if(propLabel != null) {
- String prop_uri = resolvePropLabel(con, propLabel);
- if(prop_uri == null) {
- return Collections.emptySet();
- } else {
- property = con.getValueFactory().createURI(prop_uri);
- }
- } else {
- property = null;
- }
-
- final Resource[] contexts;
- if(context != null) {
- contexts = new Resource[] { context };
- } else {
- contexts = new Resource[0];
- }
-
- return new Iterable<Statement>() {
- @Override
- public Iterator<Statement> iterator() {
- try {
- return ResultUtils.unwrap(con.getStatements(r, property, null, true, contexts));
- } catch (RepositoryException ex) {
- ExceptionUtils.handleRepositoryException(ex, ResourceUtils.class);
- return Iterators.emptyIterator();
- }
- }
- };
- }
-
- /**
- * List the objects that are related to this resource through a certain property
- *
- * @return a list of all outgoingnodes independent of a space
- */
- public static Iterable<? extends Value> listOutgoingNodes(RepositoryConnection con, Resource r, String propLabel) throws RepositoryException {
- return listOutgoingNodes(con, r, propLabel, null);
- }
-
- /**
- * List the objects that are related to this resource through a certain property
- *
- * @return a list of all outgoingnodes dependent of a space
- */
- public static Iterable<? extends Value> listOutgoingNodes(RepositoryConnection con, Resource r, String propLabel, URI context) throws RepositoryException {
- return Iterables.transform(
- listOutgoing(con,r,propLabel,context),
- new Function<Statement, Value>() {
- @Override
- public Value apply(Statement input) {
- return input.getObject();
- }
- }
- );
- }
-
-
- public static void addOutgoingNode(RepositoryConnection con, Resource r, String propLabel, Value target, URI context) throws RepositoryException {
- final Resource[] contexts;
- if(context != null) {
- contexts = new Resource[] { context };
- } else {
- contexts = new Resource[0];
- }
-
-
- String property_uri = resolvePropLabel(con,propLabel);
- URI prop = con.getValueFactory().createURI(property_uri);
- con.add(r,prop,target,contexts);
- }
-
- /**
- * Add an outgoing node to the resource in the given context using the given property
- * @param con
- * @param r
- * @param prop
- * @param target
- * @param context
- * @throws RepositoryException
- * @deprecated use con.add directly instead
- */
- @Deprecated
- public static void addOutgoingNode(RepositoryConnection con, Resource r, URI prop, Value target, URI context) throws RepositoryException {
- final Resource[] contexts;
- if(context != null) {
- contexts = new Resource[] { context };
- } else {
- contexts = new Resource[0];
- }
-
-
- con.add(r,prop,target,contexts);
- }
-
- /**
- * Remove an outgoing node from the resource reachable via the given property label in the given context
- * @param con
- * @param r
- * @param propLabel
- * @param target
- * @param context
- * @throws RepositoryException
- */
- public static void removeOutgoingNode(RepositoryConnection con, Resource r, String propLabel, Resource target, URI context) throws RepositoryException {
- final Resource[] contexts;
- if(context != null) {
- contexts = new Resource[] { context };
- } else {
- contexts = new Resource[0];
- }
-
-
- String property_uri = resolvePropLabel(con,propLabel);
- URI prop = con.getValueFactory().createURI(property_uri);
- con.remove(r, prop, target, contexts);
- }
-
- /**
- * List all incoming edges from other resources to this resource
- *
- * @return
- */
- public static Iterable<? extends Statement> listIncoming(RepositoryConnection con, Resource r) throws RepositoryException {
- return listIncoming(con, r, (URI) null);
- }
-
- /**
- * List all incoming edges from other resources to this resource. Just for the given space(context)
- *
- * @return
- */
- public static Iterable<? extends Statement> listIncoming(RepositoryConnection con, Resource r, URI context) throws RepositoryException {
- return listIncoming(con, r, null, context);
- }
-
-
- /**
- * List incoming edges from other resources to this resource, using the property label passed
- * as argument. If limit is bigger than 0, then a maximum of limit triples will be returned.
- * Otherwise, all triples will be returned.
- * <p/>
- * The parameter propLabel is in the form of a SeRQL or SPARQL id. It can take one of the following
- * values:
- * <ul>
- * <li>a URI enclosed in < >, e.g. <http://www.example.com/myProp></li>
- * <li>a uri prefix, followed by a colon and the property name, e.g. ex:myProp</li>
- * <li>the value "null", in which case all outgoing edges are listed regardless of their label
- * (wildcard)</li>
- * </ul>
- * The result will be an iterable that allows to iterate over Statements.
- *
- *
- * @param r the maximum number of triples to retrieve
- * @param propLabel the label of the property to be queried, or null for wildcard
- * @return an iterable over the Statements that are incoming edges of this resource
- */
- public static Iterable<? extends Statement> listIncoming(RepositoryConnection con, Resource r, String propLabel) throws RepositoryException {
- return listIncoming(con, r, propLabel, null);
- }
-
- /**
- * List incoming edges from other resources to this resource, using the property label passed
- * as argument. If limit is bigger than 0, then a maximum of limit triples will be returned.
- * Otherwise, all triples will be returned.
- * <p/>
- * The parameter propLabel is in the form of a SeRQL or SPARQL id. It can take one of the following
- * values:
- * <ul>
- * <li>a URI enclosed in < >, e.g. <http://www.example.com/myProp></li>
- * <li>a uri prefix, followed by a colon and the property name, e.g. ex:myProp</li>
- * <li>the value "null", in which case all outgoing edges are listed regardless of their label
- * (wildcard)</li>
- * </ul>
- * The result will be an iterable that allows to iterate over Statements.
- *
- * @param propLabel the label of the property to be queried, or null for wildcard
- * @param r the maximum number of triples to retrieve
- * @param context incoming resources just for the given context/space
- * @return an iterable over the Statements that are incoming edges of this resource
- */
- public static Iterable<? extends Statement> listIncoming(final RepositoryConnection con, final Resource r, final String propLabel, final URI context) throws RepositoryException {
- final URI property;
- if(propLabel != null) {
- String prop_uri = resolvePropLabel(con, propLabel);
- if(prop_uri == null) {
- return Collections.emptySet();
- } else {
- property = con.getValueFactory().createURI(prop_uri);
- }
- } else {
- property = null;
- }
-
- final Resource[] contexts;
- if(context != null) {
- contexts = new Resource[] { context };
- } else {
- contexts = new Resource[0];
- }
-
- return new Iterable<Statement>() {
- @Override
- public Iterator<Statement> iterator() {
- try {
- return ResultUtils.unwrap(con.getStatements(null, property, r, true, contexts));
- } catch (RepositoryException ex) {
- ExceptionUtils.handleRepositoryException(ex, ResourceUtils.class);
- return Iterators.emptyIterator();
- }
- }
- };
- }
-
- /**
- * Return a list of nodes that are the sources for edges with propLabel that have this resource
- * as endpoint. This is mostly a convenience method that wraps listIncoming(propLabel).
- *
- * @param propLabel the label that all edges listed must have, or null for wildcard
- * @return a list of resources that are sources of edges that have this resource as endpoint
- */
- public static Iterable<? extends Resource> listIncomingNodes(RepositoryConnection con, Resource r, String propLabel) throws RepositoryException {
- return listIncomingNodes(con, r, propLabel, null);
- }
-
- /**
- * Return a list of nodes that are the sources for edges with propLabel that have this resource
- * as endpoint. This is mostly a convenience method that wraps listIncoming(propLabel).
- *
- * @param propLabel the label that all edges listed must have, or null for wildcard
- * @param context the context of the incoming nodes
- * @return a list of resources that are sources of edges that have this resource as endpoint
- */
- public static Iterable<? extends Resource> listIncomingNodes(RepositoryConnection con, Resource r, String propLabel, URI context) throws RepositoryException {
- return Iterables.transform(
- listIncoming(con, r, propLabel, context),
- new Function<Statement, Resource>() {
- @Override
- public Resource apply(Statement input) {
- return input.getSubject();
- }
- }
- );
- }
-
-
- /* convenience wrappers around common RDF properties */
-
- /**
- * Return the label of this resource in the language provided as parameter
- * <p/>
- * If no label is available for the given language, returns the identifier.
- *
- * @return
- */
- public static String getLabel(RepositoryConnection con, Resource r) throws RepositoryException {
- return getLabel(con, r,(Locale)null);
- }
-
- /**
- * Return the label of this resource in the language provided as parameter
- * <p/>
- * If no label is available for the given language, returns the identifier.
- *
- * @param context the space of the label
- * @return
- */
- public static String getLabel(RepositoryConnection con, Resource r, URI context) throws RepositoryException {
- return getLabel(con, r, null,context);
- }
-
-
- /**
- * Return the label of this resource in the language provided as parameter
- * within the getTripleStore().knowledge space of this Resource.
- * <p/>
- * If no label is available for the given language, returns the identifier.
- * Looking in all spaces!!!
- *
- * @param loc
- * @return
- */
- public static String getLabel(RepositoryConnection con, Resource r, Locale loc) throws RepositoryException {
- return getLabel(con, r,loc,null);
- }
-
- /**
- * Return the label of this resource in the language provided as parameter
- * within the getTripleStore().knowledge space of this Resource.
- * <p/>
- * If no label is available for the given language, returns the identifier.
- *
- * @param context space of the given label
- * @param loc
- * @return
- */
- public static String getLabel(RepositoryConnection con, Resource r, Locale loc, URI context) throws RepositoryException {
- String label = null;
- // check kiwi:title, rdfs:label, dc:title in this order ...
- String[] properties = { Namespaces.NS_RDFS+"label", Namespaces.NS_DC+"title", Namespaces.NS_DC_TERMS+"title", Namespaces.NS_SKOS+"prefLabel" };
-
- for(String property : properties) {
- label = getProperty(con, r,property,loc,context);
- if(label != null) {
- break;
- }
- }
-
- if(label == null && loc == null) {
- // try some common languages as well
- langloop: for(Locale loc2 : new Locale[] {Locale.ENGLISH, Locale.GERMAN}) {
- for(String property : properties) {
- label = getProperty(con, r,property,loc2,context);
- if(label != null) {
- break langloop;
- }
- }
- }
- }
-
- // still no label available, try to get last part from uri
- if(label == null && r instanceof URI) {
- String uri = r.stringValue();
- if(uri.lastIndexOf("#") > 0) {
- label = uri.substring(uri.lastIndexOf("#")+1);
- } else {
- label = uri.substring(uri.lastIndexOf("/")+1);
- }
- } else if(label == null && r instanceof BNode){
- label = r.stringValue();
- }
- return label;
- }
-
-
- /**
- * Set the rdfs:label of this Resource in the configured getTripleStore().TripleStore
- * for the given Locale. Looking in all spaces!!!
- *
- * @param label
- */
- public static void setLabel(RepositoryConnection con, Resource r, String label) throws RepositoryException {
- setLabel(con, r,null,label,null);
- }
-
- /**
- * Set the rdfs:label of this Resource in the configured getTripleStore().TripleStore
- * for the given Locale. Looking in all spaces!!!
- *
- * @param label
- */
- public static void setLabel(RepositoryConnection con, Resource r, String label, URI context) throws RepositoryException {
- setLabel(con, r,null,label,context);
- }
-
- /**
- * Set the rdfs:label of this Resource in the configured getTripleStore().TripleStore
- * for the given Locale. Looking in all spaces!!!
- *
- * @param loc
- * @param label
- */
- public static void setLabel(RepositoryConnection con, Resource r, Locale loc, String label) throws RepositoryException {
- setLabel(con, r,loc,label,null);
- }
-
- /**
- * Set the rdfs:label of this Resource in the configured getTripleStore().TripleStore
- * for the given Locale. Just for the given space !!!
- *
- * @param loc
- * @param label
- * @param context
- */
- public static void setLabel(RepositoryConnection con, Resource r, Locale loc, String label, URI context) throws RepositoryException {
- setProperty(con, r,"<"+ Namespaces.NS_RDFS+"label>", label, loc,context);
- }
-
-
- /**
- * Return the list of types as Resources that are associated with this resource using the
- * rdf:type RDF property.
- *
- * @return an iterable of Resource instances that represent the RDF types of this resource
- */
- public static Iterable<? extends Resource> getTypes(RepositoryConnection con, Resource r) throws RepositoryException {
- return getTypes(con,r,null);
- }
-
- /**
- * Return the list of types as Resources that are associated with this resource using the
- * rdf:type RDF property.
- *
- * @return an iterable of Resource instances that represent the RDF types of this resource
- */
- public static Iterable<? extends Resource> getTypes(final RepositoryConnection con, final Resource r, Resource context) throws RepositoryException {
- final URI rdf_type = con.getValueFactory().createURI(Namespaces.NS_RDF+"type");
-
- if(rdf_type != null) {
- final Resource[] contexts;
- if(context != null) {
- contexts = new Resource[] { context };
- } else {
- contexts = new Resource[0];
- }
-
- return Iterables.transform(
- Iterables.filter(
- new Iterable<Statement>() {
- @Override
- public Iterator<Statement> iterator() {
- try {
- return ResultUtils.unwrap(con.getStatements(r,rdf_type,null,true,contexts));
- } catch (RepositoryException e) {
- ExceptionUtils.handleRepositoryException(e, ResourceUtils.class);
- return Iterators.emptyIterator();
- }
- }
- },
- new Predicate<Statement>() {
- @Override
- public boolean apply(Statement input) {
- return input.getObject() instanceof Resource;
- }
- }
- ),
- new Function<Statement, Resource>() {
- @Override
- public Resource apply(Statement input) {
- return (Resource)input.getObject();
- }
- }
- );
- } else {
- return Collections.emptyList();
- }
- }
-
-
- /**
- * Remove one of the RDF types of this Resource. For all spaces/context
- *
- * @param typeUri a URI resource representing the type of this Resource
- */
- public static boolean hasType(RepositoryConnection con, Resource r, String typeUri) throws RepositoryException {
- return hasType(con,r,con.getValueFactory().createURI(typeUri));
- }
-
-
- /**
- * Check whether this Resource has a certain RDF type
- *
- * @param type the resource representing the type to check for
- * @return true if the type is in the list of RDF types of this resource, false otherwise
- */
- public static boolean hasType(RepositoryConnection con, Resource r, URI type) throws RepositoryException {
- return hasType(con,r,type,null);
- }
-
- /**
- * Check whether this Resource has a certain RDF type in the given context/space
- *
- * @param type the resource representing the type to check for
- * @return true if the type is in the list of RDF types of this resource, false otherwise
- */
- public static boolean hasType(RepositoryConnection con, Resource r, URI type, URI context) throws RepositoryException {
- if(type != null) {
- URI rdf_type = con.getValueFactory().createURI(Namespaces.NS_RDF + "type");
-
- if(rdf_type != null) {
- return con.hasStatement(r,rdf_type,type,true,context);
- }
- }
- return false;
- }
-
- /**
- * Add the RDF type to the provided Resource in the given contexts/spaces.
- * <p/>
- * This is basically a shortcut to crate <br>
- * <code><r> a <type></code> <br>
- * in all provided contexts.
- * <p/>
- * If no context is provided, the type is added without context information.
- *
- * @param con the Connection to use
- * @param r the Resource
- * @param type the Type (the Object of the triple)
- * @param context the contexts to store in
- */
- public static void addType(RepositoryConnection con, Resource r, URI type, URI... context) throws RepositoryException {
- if (type != null) {
- URI rdf_type = con.getValueFactory().createURI(Namespaces.NS_RDF + "type");
-
- if (rdf_type != null) {
- con.add(r, rdf_type, type, context);
- }
-
- }
- }
-
-
- private static String resolvePropLabel(RepositoryConnection con, String propLabel) throws RepositoryException {
- String uri = propLabel;
-
- // find out which kind of propLabel we got passed
- if(uri.startsWith("<") && uri.endsWith(">")) {
- // uri is a real uri enclosed in < >
- uri = uri.substring(1,uri.length()-1);
- } else if(!uri.contains("://") && uri.contains(":")) {
- // uri is a SeQRQL/SPARQL identifier with abbreviated namespace, we need to lookup the namespace...
- String[] components = uri.split(":");
- if(components.length == 2) {
- String ns_prefix = components[0];
- String ns_local = components[1];
-
- String ns = con.getNamespace(ns_prefix);
- if(ns == null) {
- log.error("could not find namespace with the given prefix");
- } else {
- uri = ns + ns_local;
- }
- } else {
- log.error("could not properly split property identifier #0, as it contained more than one ':'",uri);
- }
- }
- return uri;
- }
-
- /**
- * Check whether the provided argument is a Resource (an URI or BNode).
- * <p/>
- * Equivalent to <code>(v instanceof Resource)</code>.
- *
- * @param v
- * the Value to check.
- * @return <code>true</code> if it is a {@link Resource}
- */
- public static boolean isResource(Value v) {
- return v instanceof Resource;
- }
-
- /**
- * Check whether the provided argument is an URI.
- * <p/>
- * Equivalent to <code>(v instanceof URI)</code>.
- *
- * @param v
- * the Value to check.
- * @return <code>true</code> if it is a {@link URI}
- */
- public static boolean isURI(Value v) {
- return v instanceof URI;
- }
-
- /**
- * Check whether the provided argument is a BNode.
- * <p/>
- * Equivalent to <code>(v instanceof BNode)</code>.
- *
- * @param v
- * the Value to check.
- * @return <code>true</code> if it is a {@link BNode}
- */
- public static boolean isBNode(Value v) {
- return v instanceof BNode;
- }
-
- /**
- * Check whether the provided argument is a Literal.
- * <p/>
- * Equivalent to <code>(v instanceof Literal)</code>.
- *
- * @param v
- * the Value to check.
- * @return <code>true</code> if it is a {@link Literal}
- */
- public static boolean isLiteral(Value v) {
- return v instanceof Literal;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-marmotta/blob/5f62ec33/commons/marmotta-commons/src/main/java/at/newmedialab/sesame/commons/repository/ResultUtils.java
----------------------------------------------------------------------
diff --git a/commons/marmotta-commons/src/main/java/at/newmedialab/sesame/commons/repository/ResultUtils.java b/commons/marmotta-commons/src/main/java/at/newmedialab/sesame/commons/repository/ResultUtils.java
deleted file mode 100644
index e00fc99..0000000
--- a/commons/marmotta-commons/src/main/java/at/newmedialab/sesame/commons/repository/ResultUtils.java
+++ /dev/null
@@ -1,137 +0,0 @@
-/**
- * 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 at.newmedialab.sesame.commons.repository;
-
-import org.openrdf.repository.RepositoryException;
-import org.openrdf.repository.RepositoryResult;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import static at.newmedialab.sesame.commons.repository.ExceptionUtils.handleRepositoryException;
-
-/**
- * Some static utility methods for working with RepositoryResults
- * <p/>
- * Author: Sebastian Schaffert
- */
-public class ResultUtils {
-
- /**
- * Unwrap a repository result, providing a standard Java iterator that can be used e.g. in foreach loops.
- * <p/>
- * The underlying repository result will be closed automatically when the last result element has been consumed.
- * For this reason it is mandatory that the iteration is performed completely by the caller.
- * <p/>
- * In case an exception occurs while iterating, an error message is logged and the next() method will return null,
- * the hasNext() method will return false.
- *
- * @param result
- * @param <T>
- * @return
- */
- public static <T> Iterator<T> unwrap(final RepositoryResult<T> result) {
- return new Iterator<T>() {
- @Override
- public boolean hasNext() {
- if(result.isClosed()) {
- return false;
- }
- try {
- return result.hasNext();
- } catch (RepositoryException e) {
- ExceptionUtils.handleRepositoryException(e, ResourceUtils.class);
- return false;
- }
- }
-
- @Override
- public T next() {
- try {
- T next = result.next();
- if(!result.hasNext()) {
- result.close();
- }
- return next;
- } catch (RepositoryException e) {
- handleRepositoryException(e, ResourceUtils.class);
- return null;
- }
- }
-
- @Override
- public void remove() {
- try {
- result.remove();
- } catch (RepositoryException e) {
- handleRepositoryException(e, ResourceUtils.class);
- }
- }
-
- @Override
- protected void finalize() throws Throwable {
- if(!result.isClosed())
- result.close();
- super.finalize();
- }
- };
-
- }
-
- /**
- * Unwrap a repository result, providing a standard Java iterable that can be used e.g. in foreach loops.
- * <p/>
- * The underlying repository result will be closed automatically when the last result element has been consumed.
- * For this reason it is mandatory that the iteration is performed completely by the caller.
- * <p/>
- * In case an exception occurs while iterating, an error message is logged and the next() method will return null,
- * the hasNext() method will return false.
- *
- * @param result
- * @param <T>
- * @return
- */
- public static <T> Iterable<T> iterable(final RepositoryResult<T> result) {
- return new Iterable<T>() {
- @Override
- public Iterator<T> iterator() {
- return unwrap(result);
- }
- };
- }
-
-
- /**
- * Workaround for https://openrdf.atlassian.net/browse/SES-1702 in Sesame 2.7.0-beta1
- * @param <E>
- * @return
- */
- public static <E> List<E> asList(RepositoryResult<E> result) throws RepositoryException {
- ArrayList<E> collection = new ArrayList<E>();
- try {
- while (result.hasNext()) {
- collection.add(result.next());
- }
-
- return collection;
- }
- finally {
- result.close();
- }
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-marmotta/blob/5f62ec33/commons/marmotta-commons/src/main/java/at/newmedialab/sesame/commons/util/DateUtils.java
----------------------------------------------------------------------
diff --git a/commons/marmotta-commons/src/main/java/at/newmedialab/sesame/commons/util/DateUtils.java b/commons/marmotta-commons/src/main/java/at/newmedialab/sesame/commons/util/DateUtils.java
deleted file mode 100644
index dd48f08..0000000
--- a/commons/marmotta-commons/src/main/java/at/newmedialab/sesame/commons/util/DateUtils.java
+++ /dev/null
@@ -1,162 +0,0 @@
-/**
- * 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 at.newmedialab.sesame.commons.util;
-
-import javax.xml.datatype.DatatypeConfigurationException;
-import javax.xml.datatype.DatatypeFactory;
-import javax.xml.datatype.XMLGregorianCalendar;
-
-import java.text.DateFormat;
-import java.text.DateFormatSymbols;
-import java.text.ParseException;
-import java.text.SimpleDateFormat;
-import java.util.Date;
-import java.util.GregorianCalendar;
-import java.util.Locale;
-import java.util.TimeZone;
-
-/**
- * @author Sebastian Schaffert
- *
- */
-public class DateUtils {
-
-
- public static final SimpleDateFormat ISO8601FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
-
- public static final SimpleDateFormat ISO8601FORMAT_TIME = new SimpleDateFormat("HH:mm:ss.SSS'Z'");
- public static final SimpleDateFormat ISO8601FORMAT_DATE = new SimpleDateFormat("yyyy-MM-dd");
-
- public static final SimpleDateFormat FILENAME_FORMAT = new SimpleDateFormat("yyyyMMdd-HHmmss");
-
-
- public static final SimpleDateFormat GMTFORMAT = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", new DateFormatSymbols(Locale.US));
- static {
- ISO8601FORMAT.setTimeZone(TimeZone.getTimeZone("UTC"));
- ISO8601FORMAT_TIME.setTimeZone(TimeZone.getTimeZone("UTC"));
- ISO8601FORMAT_DATE.setTimeZone(TimeZone.getTimeZone("UTC"));
- GMTFORMAT.setTimeZone(TimeZone.getTimeZone("GMT"));
- }
-
- /**
- * Some parsers will have the date as a ISO-8601 string
- * already, and will set that into the Metadata object.
- * So we can return Date objects for these, this is the
- * list (in preference order) of the various ISO-8601
- * variants that we try when processing a date based
- * property.
- */
- private static final DateFormat[] iso8601InputFormats = new DateFormat[] {
- // GMT
- createDateFormat("EEE, dd MMM yyyy HH:mm:ss'Z'","GMT"),
- GMTFORMAT,
-
- // yyyy-mm-ddThh...
- createDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ",null),
- createDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", "UTF"),
- createDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", null), // With timezone
- createDateFormat("yyyy-MM-dd'T'HH:mm:ss", null), // Without timezone
- // yyyy-mm-dd hh...
- createDateFormat("yyyy-MM-dd' 'HH:mm:ss'Z'", "UTF"), // UTC/Zulu
- createDateFormat("yyyy-MM-dd' 'HH:mm:ssZ", null), // With timezone
- createDateFormat("yyyy-MM-dd' 'HH:mm:ss.SZ", null), // With timezone
- createDateFormat("yyyy-MM-dd' 'HH:mm:ss", null), // Without timezone
- createDateFormat("EEE MMM dd HH:mm:ss z yyyy", null), // Word documents
- createDateFormat("EEE MMM d HH:mm:ss z yyyy", null), // Word documents
- createDateFormat("dd.MM.yyy' 'HH:mm:ss", null), // German
- createDateFormat("dd.MM.yyy' 'HH:mm", null), // German
- };
-
- private static DateFormat createDateFormat(String format, String timezone) {
- SimpleDateFormat sdf =
- new SimpleDateFormat(format, new DateFormatSymbols(Locale.US));
- if (timezone != null) {
- sdf.setTimeZone(TimeZone.getTimeZone(timezone));
- }
- return sdf;
- }
-
-
- /**
- * Parses the given date string. This method is synchronized to prevent
- * concurrent access to the thread-unsafe date formats.
- *
- * Stolen from TIKA to workaround a bug there ...
- *
- * @see <a href="https://issues.apache.org/jira/browse/TIKA-495">TIKA-495</a>
- * @param date date string
- * @return parsed date, or <code>null</code> if the date can't be parsed
- */
- public static synchronized Date parseDate(String date) {
- if(date == null) {
- return null;
- }
-
- // Java doesn't like timezones in the form ss+hh:mm
- // It only likes the hhmm form, without the colon
- int n = date.length();
- if (n > 2 && date.charAt(n - 3) == ':'
- && (date.charAt(n - 6) == '+' || date.charAt(n - 6) == '-')) {
- date = date.substring(0, n - 3) + date.substring(n - 2);
- }
-
- // Try several different ISO-8601 variants
- for (DateFormat format : iso8601InputFormats) {
- try {
- return format.parse(date);
- } catch (ParseException ignore) {
- }
- }
- return null;
- }
-
- /**
- * Transform an XML calendar into a Java date. Useful for working with date literals.
- * @param calendar
- * @return
- */
- public static Date getDate(XMLGregorianCalendar calendar) {
- return calendar.toGregorianCalendar().getTime();
- }
-
-
- /**
- * Transform a Java date into a XML calendar. Useful for working with date literals.
- * @param date
- * @return
- */
- public static XMLGregorianCalendar getXMLCalendar(Date date) {
- GregorianCalendar c = new GregorianCalendar();
- c.setTimeZone(TimeZone.getTimeZone("UTC"));
- c.setTime(date);
- try {
- return DatatypeFactory.newInstance().newXMLGregorianCalendar(c).normalize();
- } catch (DatatypeConfigurationException e) {
- return null;
- }
- }
-
-
- /**
- * Cut the fraction part of a date object, since some database systems do not support nanoseconds.
- * @param date
- * @return
- */
- public static Date getDateWithoutFraction(Date date) {
- long seconds = date.getTime() / 1000L;
- return new Date(seconds * 1000L);
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-marmotta/blob/5f62ec33/commons/marmotta-commons/src/main/java/at/newmedialab/sesame/commons/util/HashUtils.java
----------------------------------------------------------------------
diff --git a/commons/marmotta-commons/src/main/java/at/newmedialab/sesame/commons/util/HashUtils.java b/commons/marmotta-commons/src/main/java/at/newmedialab/sesame/commons/util/HashUtils.java
deleted file mode 100644
index 205ed5b..0000000
--- a/commons/marmotta-commons/src/main/java/at/newmedialab/sesame/commons/util/HashUtils.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/**
- * 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 at.newmedialab.sesame.commons.util;
-
-import java.io.UnsupportedEncodingException;
-import java.math.BigInteger;
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
-
-/**
- * A static class for generating hash-sums (MD5, SHA-1) out of strings
- *
- * @author Sebastian Schaffert
- *
- */
-public class HashUtils {
-
- public static final String md5sum(String string) {
- return calcHash(string, "MD5");
- }
-
- public static final String md5sum(byte[] bytes) {
- return calcHash(bytes, "MD5");
- }
-
- public static final String sha1(String string) {
- return calcHash(string, "SHA-1");
- }
-
- public static final String sha1(byte[] bytes) {
- return calcHash(bytes, "SHA-1");
- }
-
- private static String calcHash(String string, String algorithm) {
- try {
- return calcHash(string.getBytes("UTF-8"), algorithm);
- } catch (UnsupportedEncodingException e) {
- return string;
- }
- }
-
- private static String calcHash(byte[] bytes, String algorithm) {
- try {
- MessageDigest m = MessageDigest.getInstance(algorithm);
- m.update(bytes);
- return new BigInteger(1,m.digest()).toString(16);
- } catch(NoSuchAlgorithmException ex) {
- return "";
- }
- }
-
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-marmotta/blob/5f62ec33/commons/marmotta-commons/src/main/java/at/newmedialab/sesame/commons/util/JSONUtils.java
----------------------------------------------------------------------
diff --git a/commons/marmotta-commons/src/main/java/at/newmedialab/sesame/commons/util/JSONUtils.java b/commons/marmotta-commons/src/main/java/at/newmedialab/sesame/commons/util/JSONUtils.java
deleted file mode 100644
index 2696d1e..0000000
--- a/commons/marmotta-commons/src/main/java/at/newmedialab/sesame/commons/util/JSONUtils.java
+++ /dev/null
@@ -1,172 +0,0 @@
-/**
- * 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 at.newmedialab.sesame.commons.util;
-
-import org.openrdf.model.BNode;
-import org.openrdf.model.Literal;
-import org.openrdf.model.Statement;
-import org.openrdf.model.URI;
-import org.openrdf.model.Value;
-
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Set;
-
-/**
- * Utility methods for transforming Sesame objects into in-memory RDF/JSON format using maps and sets.
- */
-public class JSONUtils {
-
- private static final String VALUE = "value";
- private static final String TYPE = "type";
- private static final String BNODE = "bnode";
- private static final String URI = "uri";
- private static final String LITERAL = "literal";
- private static final String LANG = "lang";
- private static final String DATATYPE = "datatype";
-
- /**
- * Transform node into an in-memory RDF/JSON representation that can be serialised using e.g. the
- * Jackson ObjectMapper.
- *
- * @param node
- * @return
- */
- public static Map<String, String> serializeNodeAsJson(Value node) {
- Map<String,String> nodeRep = new HashMap<String, String>();
- if(node instanceof Literal) {
- Literal literal = (Literal)node;
- nodeRep.put(TYPE,LITERAL);
- nodeRep.put(VALUE, literal.stringValue());
- if(literal.getDatatype() != null) {
- nodeRep.put(DATATYPE,literal.getDatatype().stringValue());
- }
- if(literal.getLanguage() != null) {
- nodeRep.put(LANG,literal.getLanguage());
- }
- } else if(node instanceof URI) {
- nodeRep.put(TYPE,URI);
- nodeRep.put(VALUE,node.stringValue());
- } else if(node instanceof BNode) {
- nodeRep.put(TYPE,BNODE);
- nodeRep.put(VALUE,node.stringValue());
- }
- return nodeRep;
-
- }
-
- /**
- * Turn a list of nodes into a dataformat serializable by Jackson (maps and sets)
- *
- *
- * @param nodes
- * @return
- */
- public static Set<Map<String,String>> serializeNodesAsJson(Iterable<? extends Value> nodes) {
- Set<Map<String,String>> result = new HashSet<Map<String, String>>();
-
- for(Value objectNode : nodes) {
- result.add(serializeNodeAsJson(objectNode));
- }
- return result;
- }
-
- /**
- * This method wraps triples (Subject,Property,Object) in a dataformat that is serializable
- * by Jackson (namely maps and sets).
- *
- * @param triple
- * @return
- */
- public static Map<String,?> serializeTripleAsJson(Statement triple) {
-
- Map<String,Map<String,Set<Map<String,String>>>> subjects = new HashMap<String,Map<String,Set<Map<String,String>>>>();
-
- // get subject key
- String subjectKey = triple.getSubject().stringValue();
-
- //add or get predicate map
- Map<String,Set<Map<String,String>>> predicates;
- if( subjects.containsKey(subjectKey)) {
- predicates = subjects.get(subjectKey);
- } else {
- predicates = new HashMap<String,Set<Map<String,String>>>();
- subjects.put(subjectKey,predicates);
- }
-
- //get predicate key
- String predicateKey = triple.getPredicate().stringValue();
-
- //add or get object set
- Set<Map<String,String>> objects;
- if( predicates.containsKey(predicateKey) ) {
- objects = predicates.get(predicateKey);
- } else {
- objects = new HashSet<Map<String,String>>();
- predicates.put(predicateKey,objects);
- }
-
- //add objects
- objects.add(serializeNodeAsJson(triple.getObject()));
-
- return subjects;
- }
-
-
- /**
- * This method wraps triples (Subject,Property,Object) in a dataformat that is serializable
- * by Jackson (namely maps and sets).
- *
- * @param triples
- * @return
- */
- public static Map<String,?> serializeTriplesAsJson(Iterable<? extends Statement> triples) {
-
- Map<String,Map<String,Set<Map<String,String>>>> subjects = new HashMap<String,Map<String,Set<Map<String,String>>>>();
- for( Statement triple : triples ) {
-
- // get subject key
- String subjectKey = triple.getSubject().stringValue();
-
- //add or get predicate map
- Map<String,Set<Map<String,String>>> predicates;
- if( subjects.containsKey(subjectKey)) {
- predicates = subjects.get(subjectKey);
- } else {
- predicates = new HashMap<String,Set<Map<String,String>>>();
- subjects.put(subjectKey,predicates);
- }
-
- //get predicate key
- String predicateKey = triple.getPredicate().stringValue();
-
- //add or get object set
- Set<Map<String,String>> objects;
- if( predicates.containsKey(predicateKey) ) {
- objects = predicates.get(predicateKey);
- } else {
- objects = new HashSet<Map<String,String>>();
- predicates.put(predicateKey,objects);
- }
-
- //add objects
- objects.add(serializeNodeAsJson(triple.getObject()));
-
- }
- return subjects;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-marmotta/blob/5f62ec33/commons/marmotta-commons/src/main/java/org/apache/marmotta/commons/http/ETagGenerator.java
----------------------------------------------------------------------
diff --git a/commons/marmotta-commons/src/main/java/org/apache/marmotta/commons/http/ETagGenerator.java b/commons/marmotta-commons/src/main/java/org/apache/marmotta/commons/http/ETagGenerator.java
new file mode 100644
index 0000000..0508dd4
--- /dev/null
+++ b/commons/marmotta-commons/src/main/java/org/apache/marmotta/commons/http/ETagGenerator.java
@@ -0,0 +1,105 @@
+/**
+ * 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 org.apache.marmotta.commons.http;
+
+import org.apache.marmotta.commons.sesame.repository.ResourceUtils;
+import org.openrdf.model.Statement;
+import org.openrdf.model.URI;
+import org.openrdf.repository.RepositoryConnection;
+import org.openrdf.repository.RepositoryException;
+import org.openrdf.repository.RepositoryResult;
+
+
+import com.google.common.hash.HashFunction;
+import com.google.common.hash.Hasher;
+import com.google.common.hash.Hashing;
+
+/**
+ * HTTP ETag generator for Sesame
+ *
+ * @author Sergio Fernández
+ *
+ */
+public class ETagGenerator {
+
+ public static String getETag(RepositoryConnection conn, String uri) throws RepositoryException {
+ URI resource = ResourceUtils.getUriResource(conn, uri);
+ return getETag(conn, resource);
+ }
+
+ public static String getETag(RepositoryConnection conn, URI resource) throws RepositoryException {
+ if (resource == null) return "";
+
+ Hasher hasher = buildHasher();
+ hasher.putString(resource.stringValue());
+ //FIXME: The order of the statements is not defined -> might result in different hash!
+ RepositoryResult<Statement> outgoing = conn.getStatements(resource, null, null, true);
+ try {
+ while (outgoing.hasNext()) {
+ Statement statement = outgoing.next();
+ hasher.putString(statement.getPredicate().stringValue());
+ hasher.putString(statement.getObject().stringValue());
+ //TODO: statement modification date?
+ }
+ } finally {
+ outgoing.close();
+ }
+ RepositoryResult<Statement> incoming = conn.getStatements(null, null, resource, true);
+ try {
+ while (incoming.hasNext()) {
+ Statement statement = incoming.next();
+ hasher.putString(statement.getSubject().stringValue());
+ hasher.putString(statement.getPredicate().stringValue());
+ //TODO: statement modification date?
+ }
+ } finally {
+ incoming.close();
+ }
+ return hasher.hash().toString();
+ }
+
+ public static String getWeakETag(RepositoryConnection conn, String uri) throws RepositoryException {
+ URI resource = ResourceUtils.getUriResource(conn, uri);
+ return getWeakETag(conn, resource);
+ }
+
+ public static String getWeakETag(RepositoryConnection conn, URI resource) throws RepositoryException {
+ if (resource == null) return "";
+
+ Hasher hasher = buildHasher();
+ hasher.putString(resource.stringValue());
+ //FIXME: The order of the statements is not defined -> might result in different hash!
+ RepositoryResult<Statement> statements = conn.getStatements(resource, null, null, true);
+ try {
+ while (statements.hasNext()) {
+ Statement statement = statements.next();
+ hasher.putString(statement.getPredicate().stringValue());
+ hasher.putString(statement.getObject().stringValue());
+ //TODO: statement modification date?
+ }
+ } finally {
+ statements.close();
+ }
+ return hasher.hash().toString();
+ }
+
+ private static Hasher buildHasher() {
+ HashFunction function = Hashing.goodFastHash(16);
+ Hasher hasher = function.newHasher();
+ return hasher;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-marmotta/blob/5f62ec33/commons/marmotta-commons/src/main/java/org/apache/marmotta/commons/sesame/model/BNodeCommons.java
----------------------------------------------------------------------
diff --git a/commons/marmotta-commons/src/main/java/org/apache/marmotta/commons/sesame/model/BNodeCommons.java b/commons/marmotta-commons/src/main/java/org/apache/marmotta/commons/sesame/model/BNodeCommons.java
new file mode 100644
index 0000000..4550486
--- /dev/null
+++ b/commons/marmotta-commons/src/main/java/org/apache/marmotta/commons/sesame/model/BNodeCommons.java
@@ -0,0 +1,47 @@
+/**
+ * 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 org.apache.marmotta.commons.sesame.model;
+
+import org.openrdf.model.BNode;
+
+/**
+ * Add file description here!
+ * <p/>
+ * Author: Sebastian Schaffert
+ */
+public class BNodeCommons {
+
+ /**
+ * Return the cache key for the BNode passed as argument.
+ *
+ * @param node a Sesame BNode for which to create a cache key
+ * @return a string that can be used as cache key
+ */
+ public static String createCacheKey(BNode node) {
+ return node.getID();
+ }
+
+
+ /**
+ * Return the cache key for the BNode ID passed as argument.
+ *
+ * @param anonId a Sesame BNode ID for which to create a cache key
+ * @return a string that can be used as cache key
+ */
+ public static String createCacheKey(String anonId) {
+ return anonId;
+ }
+}