Author: rwesten
Date: Mon Feb  6 09:20:52 2012
New Revision: 1240945

URL: http://svn.apache.org/viewvc?rev=1240945&view=rev
Log:
### STANBOL-483: forgot to actually commit the implementation and the unit test 
file

Added:
    
incubator/stanbol/trunk/commons/ldpath/clerezza/src/main/java/org/apache/stanbol/commons/ldpath/clerezza/ClerezzaBackend.java
   (with props)
    
incubator/stanbol/trunk/commons/ldpath/clerezza/src/test/java/org/apache/stanbol/commons/ldpath/clerezza/ClerezzaBackendTest.java
   (with props)

Added: 
incubator/stanbol/trunk/commons/ldpath/clerezza/src/main/java/org/apache/stanbol/commons/ldpath/clerezza/ClerezzaBackend.java
URL: 
http://svn.apache.org/viewvc/incubator/stanbol/trunk/commons/ldpath/clerezza/src/main/java/org/apache/stanbol/commons/ldpath/clerezza/ClerezzaBackend.java?rev=1240945&view=auto
==============================================================================
--- 
incubator/stanbol/trunk/commons/ldpath/clerezza/src/main/java/org/apache/stanbol/commons/ldpath/clerezza/ClerezzaBackend.java
 (added)
+++ 
incubator/stanbol/trunk/commons/ldpath/clerezza/src/main/java/org/apache/stanbol/commons/ldpath/clerezza/ClerezzaBackend.java
 Mon Feb  6 09:20:52 2012
@@ -0,0 +1,341 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.stanbol.commons.ldpath.clerezza;
+
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.text.DateFormat;
+import java.text.ParseException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Date;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Locale;
+import java.util.Set;
+
+import org.apache.clerezza.rdf.core.BNode;
+import org.apache.clerezza.rdf.core.Language;
+import org.apache.clerezza.rdf.core.Literal;
+import org.apache.clerezza.rdf.core.LiteralFactory;
+import org.apache.clerezza.rdf.core.MGraph;
+import org.apache.clerezza.rdf.core.NoConvertorException;
+import org.apache.clerezza.rdf.core.NonLiteral;
+import org.apache.clerezza.rdf.core.PlainLiteral;
+import org.apache.clerezza.rdf.core.Resource;
+import org.apache.clerezza.rdf.core.Triple;
+import org.apache.clerezza.rdf.core.TripleCollection;
+import org.apache.clerezza.rdf.core.TypedLiteral;
+import org.apache.clerezza.rdf.core.UriRef;
+import org.apache.clerezza.rdf.core.impl.PlainLiteralImpl;
+import org.apache.clerezza.rdf.core.impl.TypedLiteralImpl;
+import org.apache.clerezza.rdf.core.impl.util.W3CDateFormat;
+import org.apache.commons.collections.BidiMap;
+import org.apache.commons.collections.bidimap.DualHashBidiMap;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import at.newmedialab.ldpath.api.backend.RDFBackend;
+
+/**
+ * Clerezza based implementation of {@link RDFBackend} interface. This 
implementation uses the
+ * {@link Resource} objects of Clerezza as processing unit RDFBackend.
+ * 
+ * @author anil.sinaci
+ * 
+ */
+public class ClerezzaBackend implements RDFBackend<Resource> {
+
+    private static final Logger logger = 
LoggerFactory.getLogger(ClerezzaBackend.class);
+
+    /**
+     * Enumeration containing supported XSD dataTypes including <ul>
+     * <li> local name
+     * <li> uri string
+     * <li> {@link URI}
+     * <li> {@link UriRef}
+     * </ul>
+     * {@link #toString()} returns the uri.
+     */
+    public static enum XSD {
+        INTEGER,INT,SHORT,BYTE,LONG,DOUBLE,FLOAT,
+        ANY_URI("anyURI"),DATE_TIME("dateTime"),BOOLEAN,STRING;
+        static final String namespace = "http://www.w3.org/2001/XMLSchema#";;
+        String localName;
+        String uriString;
+        URI uri;
+        UriRef uriRef;
+        /**
+         * uses <code>{@link #name()}{@link String#toLowerCase() 
.toLoverCase()}
+         * </code> to generate the {@link #getLocalName()}
+         */
+        private XSD() {
+            this(null);
+        }
+        /**
+         * Constructor that allows to parse the local name. if 
<code>null</code>
+         * it uses <code>{@link #name()}{@link String#toLowerCase() 
.toLoverCase()}
+         * </code> to generate the {@link #getLocalName() localName}
+         * @param localName the local name or <code>null</code> to use 
+         * <code>{@link #name()}{@link String#toLowerCase() .toLoverCase()}
+         * </code>
+         */
+        private XSD(String localName){
+            this.localName = localName != null ? localName : 
name().toLowerCase();
+            this.uriString = namespace+this.localName;
+            this.uri = URI.create(uriString);
+            this.uriRef = new UriRef(uriString);
+        }
+        public String getLocalName(){
+            return localName;
+        }
+        public String getUri(){
+            return uriString; 
+        }
+        public URI getURI(){
+            return uri;
+        }
+        public UriRef getUriRef(){
+            return uriRef;
+        }
+        @Override
+        public String toString() {
+            return uriString;
+        }
+        private static BidiMap xsdURI2UriRef = new DualHashBidiMap();
+        
+        static {
+            for(XSD type : XSD.values()){
+                xsdURI2UriRef.put(type.getURI(), type.getUriRef());
+            }
+        }
+        public static URI getXsdURI(UriRef uri){
+            return (URI)xsdURI2UriRef.getKey(uri);
+        }
+        public static UriRef getXsdUriRef(URI uri){
+            return (UriRef)xsdURI2UriRef.get(uri);
+        }
+    }
+    
+    private TripleCollection graph;
+    
+    private static LiteralFactory lf = LiteralFactory.getInstance();
+
+    public ClerezzaBackend(TripleCollection graph) {
+        this.graph = graph;
+    }
+
+    @Override
+    public Resource createLiteral(String content) {
+        return createLiteral(content,null,null);
+    }
+
+    @Override
+    public Resource createLiteral(String content, Locale language, URI type) {
+        logger.debug("creating literal with content \"{}\", language {}, 
datatype {}",
+            new Object[] {content, language, type});
+        if (type == null) {
+            if(language == null){
+                return new PlainLiteralImpl(content);
+            } else {
+                return new PlainLiteralImpl(content, new 
Language(language.getLanguage()));
+            }
+        } else {
+            return new TypedLiteralImpl(content, XSD.getXsdUriRef(type));
+        }
+    }
+
+    @Override
+    public Resource createURI(String uriref) {
+        return new UriRef(uriref);
+    }
+
+    @Override
+    public Double doubleValue(Resource resource) {
+        if (resource instanceof TypedLiteral) {
+            return LiteralFactory.getInstance().createObject(Double.class, 
(TypedLiteral) resource);
+        } else {
+            throw new IllegalArgumentException("Resource " + 
resource.toString() + " is not a TypedLiteral");
+        }
+    }
+
+    @Override
+    public Locale getLiteralLanguage(Resource resource) {
+        if (resource instanceof PlainLiteral) {
+            Language lang = ((PlainLiteral) resource).getLanguage();
+            return lang != null ? new Locale(lang.toString()) : null;
+        } else {
+            throw new IllegalArgumentException("Resource " + 
resource.toString() + " is not a PlainLiteral");
+        }
+    }
+
+    @Override
+    public URI getLiteralType(Resource resource) {
+        if (resource instanceof TypedLiteral) {
+            UriRef type = ((TypedLiteral) resource).getDataType();
+            return type != null ? XSD.getXsdURI(type) : null;
+        } else {
+            throw new IllegalArgumentException("Value " + resource.toString() 
+ " is not a literal");
+        }
+    }
+
+    @Override
+    public boolean isBlank(Resource resource) {
+        return resource instanceof BNode;
+    }
+
+    @Override
+    public boolean isLiteral(Resource resource) {
+        return resource instanceof Literal;
+    }
+
+    @Override
+    public boolean isURI(Resource resource) {
+        return resource instanceof UriRef;
+    }
+
+    @Override
+    public Collection<Resource> listObjects(Resource subject, Resource 
property) {
+        if (!(property instanceof UriRef) || 
+                !(subject instanceof NonLiteral)) {
+            throw new IllegalArgumentException("Subject needs to be a URI or 
blank node, property a URI node");
+        }
+
+        Collection<Resource> result = new ArrayList<Resource>();
+        Iterator<Triple> triples = graph.filter((NonLiteral) subject, (UriRef) 
property, null);
+        while (triples.hasNext()) {
+            result.add(triples.next().getObject());
+        }
+
+        return result;
+    }
+
+    @Override
+    public Collection<Resource> listSubjects(Resource property, Resource 
object) {
+        if (!(property instanceof UriRef)) {
+            throw new IllegalArgumentException("Property needs to be a URI 
node");
+        }
+
+        Collection<Resource> result = new ArrayList<Resource>();
+        Iterator<Triple> triples = graph.filter(null, (UriRef) property, 
object);
+        while (triples.hasNext()) {
+            result.add(triples.next().getSubject());
+        }
+
+        return result;
+    }
+
+    @Override
+    public Long longValue(Resource resource) {
+        if (resource instanceof TypedLiteral) {
+            return lf.createObject(Long.class, (TypedLiteral) resource);
+        } else {
+            throw new IllegalArgumentException("Resource " + 
resource.toString() + " is not a TypedLiteral");
+        }
+    }
+
+    @Override
+    public String stringValue(Resource resource) {
+        if (resource instanceof UriRef) {
+            return ((UriRef) resource).getUnicodeString();
+        } else if (resource instanceof Literal) {
+            return ((Literal) resource).getLexicalForm();
+        } else { //BNode
+            return resource.toString();
+        }
+    }
+
+    @Override
+    public Boolean booleanValue(Resource resource) {
+        if (resource instanceof TypedLiteral) {
+            return lf.createObject(Boolean.class, (TypedLiteral) resource);
+        } else {
+            throw new IllegalArgumentException("Resource " + 
resource.toString() + " is not a TypedLiteral");
+        }
+    }
+
+    @Override
+    public Date dateTimeValue(Resource resource) {
+        if (resource instanceof TypedLiteral) {
+            return lf.createObject(Date.class, (TypedLiteral) resource);
+        } else {
+            throw new IllegalArgumentException("Resource " + 
resource.toString() + " is not a TypedLiteral");
+        }
+    }
+
+    @Override
+    public Date dateValue(Resource resource) {
+        if (resource instanceof TypedLiteral) {
+            return lf.createObject(Date.class, (TypedLiteral) resource);
+        } else {
+            throw new IllegalArgumentException("Resource " + 
resource.toString() + " is not a TypedLiteral");
+        }
+    }
+
+    @Override
+    public Date timeValue(Resource resource) {
+        if (resource instanceof TypedLiteral) {
+            return lf.createObject(Date.class, (TypedLiteral) resource);
+        } else {
+            throw new IllegalArgumentException("Resource " + 
resource.toString() + " is not a TypedLiteral");
+        }
+    }
+
+    @Override
+    public Float floatValue(Resource resource) {
+        if (resource instanceof TypedLiteral) {
+            return lf.createObject(Float.class, (TypedLiteral) resource);
+        } else {
+            throw new IllegalArgumentException("Resource " + 
resource.toString() + " is not a TypedLiteral");
+        }
+    }
+
+    @Override
+    public Integer intValue(Resource resource) {
+        if (resource instanceof TypedLiteral) {
+            return lf.createObject(Integer.class, (TypedLiteral) resource);
+        } else {
+            throw new IllegalArgumentException("Resource " + 
resource.toString() + " is not a TypedLiteral");
+        }
+    }
+
+    @Override
+    public BigInteger integerValue(Resource resource) {
+        if (resource instanceof TypedLiteral) {
+            return lf.createObject(BigInteger.class, (TypedLiteral) resource);
+        } else {
+            throw new IllegalArgumentException("Resource " + 
resource.toString() + " is not a TypedLiteral");
+        }
+    }
+
+    @Override
+    public BigDecimal decimalValue(Resource resource) {
+        if (resource instanceof TypedLiteral) {
+            try {
+                return lf.createObject(BigDecimal.class, (TypedLiteral) 
resource);
+            } catch (NoConvertorException e) {
+                //currently there is no converter for BigDecimal in clerezza
+                //so as a workaround use the lexical form
+                return new 
BigDecimal(((TypedLiteral)resource).getLexicalForm());
+            }
+        } else {
+            throw new IllegalArgumentException("Resource " + 
resource.toString() + " is not a TypedLiteral");
+        }
+    }
+}
\ No newline at end of file

Propchange: 
incubator/stanbol/trunk/commons/ldpath/clerezza/src/main/java/org/apache/stanbol/commons/ldpath/clerezza/ClerezzaBackend.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Added: 
incubator/stanbol/trunk/commons/ldpath/clerezza/src/test/java/org/apache/stanbol/commons/ldpath/clerezza/ClerezzaBackendTest.java
URL: 
http://svn.apache.org/viewvc/incubator/stanbol/trunk/commons/ldpath/clerezza/src/test/java/org/apache/stanbol/commons/ldpath/clerezza/ClerezzaBackendTest.java?rev=1240945&view=auto
==============================================================================
--- 
incubator/stanbol/trunk/commons/ldpath/clerezza/src/test/java/org/apache/stanbol/commons/ldpath/clerezza/ClerezzaBackendTest.java
 (added)
+++ 
incubator/stanbol/trunk/commons/ldpath/clerezza/src/test/java/org/apache/stanbol/commons/ldpath/clerezza/ClerezzaBackendTest.java
 Mon Feb  6 09:20:52 2012
@@ -0,0 +1,193 @@
+package org.apache.stanbol.commons.ldpath.clerezza;
+
+import static junit.framework.Assert.*;
+
+import java.io.BufferedInputStream;
+import java.io.ByteArrayInputStream;
+import java.io.FilterInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.Reader;
+import java.io.UnsupportedEncodingException;
+import java.math.BigDecimal;
+import java.net.URI;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+
+import org.apache.clerezza.rdf.core.MGraph;
+import org.apache.clerezza.rdf.core.Resource;
+import org.apache.clerezza.rdf.core.Triple;
+import org.apache.clerezza.rdf.core.UriRef;
+import org.apache.clerezza.rdf.core.serializedform.ParsingProvider;
+import org.apache.clerezza.rdf.core.serializedform.SupportedFormat;
+import org.apache.clerezza.rdf.jena.parser.JenaParserProvider;
+import org.apache.clerezza.rdf.ontologies.RDF;
+import org.apache.stanbol.commons.indexedgraph.IndexedMGraph;
+import org.apache.stanbol.commons.ldpath.clerezza.ClerezzaBackend;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import at.newmedialab.ldpath.LDPath;
+import at.newmedialab.ldpath.exception.LDPathParseException;
+import at.newmedialab.ldpath.parser.Configuration;
+
+public class ClerezzaBackendTest {
+    /**
+     * Avoids that the parser closes the {@link ZipInputStream} after the
+     * first entry
+     */
+    private static class UncloseableStream extends FilterInputStream {
+
+        public UncloseableStream(InputStream in) {
+            super(in);
+        }
+        @Override
+        public void close() throws IOException {
+        }
+    }
+    
+    private Logger log = LoggerFactory.getLogger(ClerezzaBackendTest.class);
+
+    private static final String NS_SKOS = 
"http://www.w3.org/2004/02/skos/core#";;
+    private static final String NS_DBP = "http://dbpedia.org/property/";;
+    private static final String NS_DBO = "http://dbpedia.org/ontology/";;
+    private static final UriRef SKOS_CONCEPT = new UriRef(NS_SKOS+"Concept");
+    
+    private static MGraph graph;
+    
+    private ClerezzaBackend backend;
+    private LDPath<Resource> ldpath;
+    @BeforeClass
+    public static void readTestData() throws IOException {
+        ParsingProvider parser = new JenaParserProvider();
+        //NOTE(rw): the new third parameter is the base URI used to resolve 
relative paths
+        graph = new IndexedMGraph();
+        InputStream in = 
ClerezzaBackendTest.class.getClassLoader().getResourceAsStream("testdata.rdf.zip");
+        assertNotNull(in);
+        ZipInputStream zipIn = new ZipInputStream(new BufferedInputStream(in));
+        InputStream uncloseable = new UncloseableStream(zipIn);
+        ZipEntry entry;
+        while((entry = zipIn.getNextEntry()) != null){
+            if(entry.getName().endsWith(".rdf")){
+                parser.parse(graph,uncloseable, SupportedFormat.RDF_XML,null);
+            }
+        }
+        assertTrue(graph.size() > 0);
+        zipIn.close();
+        
+    }
+    
+    @Before
+    public void initBackend(){
+        if(backend == null){
+            backend = new ClerezzaBackend(graph);
+        }
+        if(ldpath == null){
+            Configuration<Resource> config = new Configuration<Resource>();
+            config.addNamespace("dbp-prop", NS_DBP);
+            config.addNamespace("dbp-ont", NS_DBO);
+            ldpath = new LDPath<Resource>(backend);
+        }
+    }
+    
+    @Test
+    public void testUriAndListImplemetnation() throws LDPathParseException {
+        UriRef nationalChampionship = new 
UriRef("http://cv.iptc.org/newscodes/subjectcode/15073031";);
+        //this program tests:
+        // * UriRef transformers
+        // * #listSubjects(..) implementation
+        // * #listObjects(..)  implementation
+        Map<String,Collection<?>> results = 
ldpath.programQuery(nationalChampionship, 
+            getReader("skos:broaderTransitive = (skos:broaderTransitive | 
^skos:narrowerTransitive)+;"));
+        Set<Resource> expected = new HashSet<Resource>(Arrays.asList(
+            new UriRef("http://cv.iptc.org/newscodes/subjectcode/15000000";),
+            new UriRef("http://cv.iptc.org/newscodes/subjectcode/15073000";)));
+        Collection<?> broaderTransitive = 
results.get(NS_SKOS+"broaderTransitive");
+        for(Object concept : broaderTransitive){
+            assertNotNull(concept);
+            assertTrue(concept instanceof UriRef);
+            assertTrue(expected.remove(concept));
+        }
+        assertTrue(expected.isEmpty());
+    }
+    @Test
+    public void testStringTransformer() throws LDPathParseException {
+        UriRef nationalChampionship = new 
UriRef("http://cv.iptc.org/newscodes/subjectcode/15073031";);
+        Map<String,Collection<?>> results = 
ldpath.programQuery(nationalChampionship, 
+            getReader("label = skos:prefLabel[@en-GB] :: xsd:string;"));
+        Set<String> expected = new HashSet<String>(Arrays.asList(
+            "national championship 1st level"));
+        Collection<?> broaderTransitive = results.get("label");
+        for(Object concept : broaderTransitive){
+            assertNotNull(concept);
+            assertTrue(concept instanceof String);
+            assertTrue(expected.remove(concept));
+        }
+        assertTrue(expected.isEmpty());
+        
+    }
+    @Test
+    public void testDataTypes() throws LDPathParseException {
+        UriRef hallein = new UriRef("http://dbpedia.org/resource/Hallein";);    
    
+
+        StringBuilder program = new StringBuilder();
+        program.append("@prefix dbp-prop : <").append(NS_DBP).append(">;");
+        program.append("@prefix dbp-ont : <").append(NS_DBO).append(">;");
+        program.append("doubleTest = dbp-ont:areaTotal :: xsd:double;"); 
//Double
+        program.append("decimalTest = dbp-ont:areaTotal :: xsd:decimal;"); 
//BigDecimal
+        program.append("intTest = dbp-prop:areaCode :: xsd:int;"); //Integer
+        program.append("longTest = dbp-prop:population :: xsd:long;"); //Long
+        program.append("uriTest = foaf:homepage :: xsd:anyURI;"); //xsd:anyUri
+        
+        Map<String,Object> expected = new HashMap<String,Object>();
+        expected.put("doubleTest", new Double(2.698E7));
+        expected.put("decimalTest", new BigDecimal("2.698E7"));
+        expected.put("intTest", new Integer(6245));
+        expected.put("longTest", new Long(19473L));
+        expected.put("uriTest", "http://www.hallein.gv.at";);
+        
+        Map<String,Collection<?>> results = ldpath.programQuery(hallein, 
+            getReader(program.toString()));
+        assertNotNull(results);
+        for(Entry<String,Collection<?>> resultEntry : results.entrySet()){
+            assertNotNull(resultEntry);
+            Object expectedResult = expected.get(resultEntry.getKey());
+            assertNotNull(resultEntry.getKey()+" is not an expected 
key",expectedResult);
+            assertTrue(resultEntry.getValue().size() == 1);
+            Object resultValue = resultEntry.getValue().iterator().next();
+            assertNotNull(resultValue);
+            
assertTrue(expectedResult.getClass().isAssignableFrom(resultValue.getClass()));
+            assertEquals(resultValue, expectedResult);
+        }
+    }
+//    @Test
+//    public void testTest(){
+//        for(Iterator<Triple> it = graph.filter(null, RDF.type, 
SKOS_CONCEPT);it.hasNext();){
+//            log.info("Concept: {}",it.next().getSubject());
+//        }
+//    }
+    public static final Reader getReader(String string) {
+        if(string == null){
+            throw new IllegalArgumentException("The parsed string MUST NOT be 
NULL!");
+        }
+        try {
+            return new InputStreamReader(new 
ByteArrayInputStream(string.getBytes("utf-8")), "utf-8");
+        } catch (UnsupportedEncodingException e) {
+            throw new IllegalStateException("Encoding 'utf-8' is not supported 
by this system!",e);
+        }
+    }
+
+}

Propchange: 
incubator/stanbol/trunk/commons/ldpath/clerezza/src/test/java/org/apache/stanbol/commons/ldpath/clerezza/ClerezzaBackendTest.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain


Reply via email to