pax_global_header 0000666 0000000 0000000 00000000064 13761231531 0014514 g ustar 00root root 0000000 0000000 52 comment=e748db82e3394a7147a911639071525c277cfea9
java-rdfa-java-rdfa-parent-1.0.0-BETA1/ 0000775 0000000 0000000 00000000000 13761231531 0017257 5 ustar 00root root 0000000 0000000 java-rdfa-java-rdfa-parent-1.0.0-BETA1/.gitignore 0000664 0000000 0000000 00000004326 13761231531 0021254 0 ustar 00root root 0000000 0000000 ### Maven template
target/
pom.xml.tag
pom.xml.releaseBackup
pom.xml.versionsBackup
pom.xml.next
release.properties
dependency-reduced-pom.xml
buildNumber.properties
.mvn/timing.properties
### JDeveloper template
# default application storage directory used by the IDE Performance Cache feature
.data/
# used for ADF styles caching
temp/
# default output directories
classes/
deploy/
javadoc/
# lock file, a part of Oracle Credential Store Framework
cwallet.sso.lck### Java template
*.class
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.jar
*.war
*.ear
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
### JetBrains template
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff:
.idea
*.iml
## File-based project format:
*.iws
## Plugin-specific files:
# IntelliJ
/out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
### Gradle template
.gradle
build/
# Ignore Gradle GUI config
gradle-app.setting
# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored)
!gradle-wrapper.jar
# Cache of project
.gradletasknamecache
# # Work around https://youtrack.jetbrains.com/issue/IDEA-116898
# gradle/wrapper/gradle-wrapper.properties
### Eclipse template
.metadata
bin/
tmp/
*.tmp
*.bak
*.swp
*~.nib
local.properties
.settings/
.loadpath
.recommenders
# Eclipse Core
.project
# External tool builders
.externalToolBuilders/
# Locally stored "Eclipse launch configurations"
*.launch
# PyDev specific (Python IDE for Eclipse)
*.pydevproject
# CDT-specific (C/C++ Development Tooling)
.cproject
# JDT-specific (Eclipse Java Development Tools)
.classpath
# Java annotation processor (APT)
.factorypath
# PDT-specific (PHP Development Tools)
.buildpath
# sbteclipse plugin
.target
# Tern plugin
.tern-project
# TeXlipse plugin
.texlipse
# STS (Spring Tool Suite)
.springBeans
# Code Recommenders
.recommenders/
java-rdfa-java-rdfa-parent-1.0.0-BETA1/COPYING 0000664 0000000 0000000 00000003163 13761231531 0020315 0 ustar 00root root 0000000 0000000 This work was developed as part of the STARS project [1] at the ILRT.
The project was funded by JISC.
[1]
/*
* (c) Copyright 2009 University of Bristol
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/ java-rdfa-java-rdfa-parent-1.0.0-BETA1/README.md 0000664 0000000 0000000 00000013200 13761231531 0020532 0 ustar 00root root 0000000 0000000 Welcome to java-rdfa
====================
The _cruftiest_ RDFa parser in the world, I'll bet. Apologies that there isn't much documentation. Things may explode: you have been warned.
Currently passing all [conformance](http://github.com/msporny/rdfa-test-suite) tests for XHTML, and the HTML 4 and 5 tests with [one exception](http://github.com/shellac/java-rdfa/issues#issue/15).
This was written by [Damian Steer](mailto:pldms@mac.com). It is an offshoot of the [Stars Project](http://stars.ilrt.bris.ac.uk/blog/) which was funded by [JISC](http://www.jisc.ac.uk/)
Useful Links
------------
* [Maven repository](http://www.rootdev.net/maven/repo/) ([snapshots](http://www.rootdev.net/maven/snapshot-repo/))
* [Java api documentation](http://www.rootdev.net/maven/projects/java-rdfa/apidocs/index.html)
* [Online parser](http://rdf-in-html.appspot.com/)
Basic Use
---------
$ ls
htmlparser-1.4.16.jar java-rdfa-1.0.0-BETA1.jar
$ java -jar java-rdfa-1.0.0-BETA1.jar http://examples.tobyinkster.co.uk/hcard
.
...
or (equivalent):
$ java -cp '*' rdfa.simpleparse http://examples.tobyinkster.co.uk/hcard
.
...
For HTML sources add the format argument, and you will need the [validator.nu](http://about.validator.nu/htmlparser/) parser:
$ java -cp '*' rdfa.simpleparse --format HTML http://www.slideshare.net/intdiabetesfed/world-diabetes-day-2009
.
...
The output of simpleparse is n-triples, and hard to read. If you have [jena](http://openjena.org/) try adding it to you classpath and using rdfa.parse instead:
$ java -cp '*:/path/to/jena/lib/*' rdfa.parse --format HTML http://www.slideshare.net/intdiabetesfed/world-diabetes-day-2009
@prefix dc: .
@prefix hx: .
... nice turtle output ...
Java Use
--------
To use the parser directly, without the assistance of an RDF toolkit (a bold choice) implement a [StatementSink](http://rootdev.net/maven/projects/java-rdfa/apidocs/net/rootdev/javardfa/StatementSink.html) to collect the triples, then use a parser from the [Factory](http://rootdev.net/maven/projects/java-rdfa/apidocs/net/rootdev/javardfa/ParserFactory.html) to make a reader:
XMLReader reader = ParserFactory.createReaderForFormat(sink, Format.XHTML); // or HTML, still an XMLReader
reader.parse(source); // Your sink will be sent triples
java-rdfa can be used from jena. Simply invoke:
Class.forName("net.rootdev.javardfa.RDFaReader");
Which will hook the two readers in to jena, then you will be able to:
model.read(url, "XHTML"); // xml parsing
model.read(other, "HTML"); // html parsing
java-rdfa is available in the maven central repositories. Note that it does not depend on jena.
A sesame reader provided by Henry Story is also available.
Open Graph Protocol
-------------------
A very simple OGP reader is provided. This follows what (I think) Toby Inkster did:
Map prop =
OGPReader.getOGP("http://uk.rottentomatoes.com/m/1217700-kick_ass",
Format.HTML);
Result:
title => 'Kick-Ass'
http://www.facebook.com/2008/fbml#app_id => '326803741017'
http://www.w3.org/1999/xhtml/vocab#icon => 'http://images.rottentomatoes.com/images/icons/favicon.ico'
http://www.w3.org/1999/xhtml/vocab#stylesheet => 'http://images.rottentomatoes.com/files/inc_beta/generated/css/mob.css'
image => 'http://images.rottentomatoes.com/images/movie/custom/00/1217700.jpg'
site_name => 'Rotten Tomatoes'
type => 'movie'
url => 'http://www.rottentomatoes.com/m/1217700-kick_ass/'
http://www.facebook.com/2008/fbml#admins => '1106591'
Form Mode
---------
There is a secret form mode (that prompted the development of this parser). In this mode you can generate basic graph patterns by including ?variables where curies are allowed, and INPUT tags generate @name variables.
[Simple example](http://github.com/shellac/java-rdfa/tree/master/src/test/resources/query-tests/1.html)
(from the tests) and the [query](http://github.com/shellac/java-rdfa/tree/master/src/test/resources/query-tests/1.rq) that results.
Changes
-------
### 1.0.0 ###
* Port to jena-3, finally using jena-3.16.0 (courtesy of user yevster)
* Make test cases operational again.
* Introduce modern maven standards.
* Compile for java 8 onwards to encompass the move of jena-3 to java 8.
* Restructure the project to make it working with maven-release-plugin.
* Hopefully preserving all the valuable work of shellac for the next decade!
### 0.4 ###
* (Finally) support overlapping literals. No one noticed this didn't work!
* Added turtle-ish output. Slightly less nasty than N-Triples.
* Bug fixes...
* Turned OFF html 5 streaming. Such a bad idea on my part.
* Started RDFa 1.1 support.
* Added simple OGP reader.
### 0.3 ###
* Updated to current conformance tests
* Switched validator.nu to streaming mode (may live to regret this).
* Created very simple n-triple and rdf/xml streaming serialisers.
* Usual bug fixes etc.
* Jena is now a provided maven dependency. Using java-rdfa won't pull in jena.
* Sesame reader create by Henry Story added. Can't be added to central maven repository since Sesame isn't available, so spun out in small module.
* Tests for query, and some utilities.
java-rdfa-java-rdfa-parent-1.0.0-BETA1/htmlparser-module/ 0000775 0000000 0000000 00000000000 13761231531 0022723 5 ustar 00root root 0000000 0000000 java-rdfa-java-rdfa-parent-1.0.0-BETA1/htmlparser-module/pom.xml 0000664 0000000 0000000 00000005173 13761231531 0024246 0 ustar 00root root 0000000 0000000
4.0.0net.rootdevjava-rdfa-htmlparserbundle1.0.0-BETA1java-rdfa-htmlparser
A rewrapping of the validator.nu html parser for use in OSGi containers.
net.rootdevjava-rdfa-parent1.0.0-BETA1..2010http://about.validator.nu/htmlparser/GitHubhttp://github.com/iteggmbh/java-rdfa/issuesDamian Steerpldms@mac.comUniversity of Bristolhttp://www.bristol.ac.uk/Henri Sivonenhsivonen@iki.fihttp://hsivonen.iki.fi/MPLhttp://about.validator.nu/htmlparser/org.apache.felixmaven-bundle-plugintruehtmlparsernu.validator.htmlparser.*!nu.xom.*,!org.mozilla.*,!com.ibm.*,*nu.validatorhtmlparser1.4.16compileUTF-8
java-rdfa-java-rdfa-parent-1.0.0-BETA1/pom.xml 0000664 0000000 0000000 00000021050 13761231531 0020572 0 ustar 00root root 0000000 0000000
4.0.0net.rootdevjava-rdfa-parentpom1.0.0-BETA1java-rdfa-parent
A SAX-based java RDFa parser.
./htmlparser-module./sesame-module./rdfa-module2009http://rootdev.net/maven/projects/java-rdfa/GitHubhttps://github.com/iteggmbh/java-rdfa/issuesDamian Steerpldms@mac.comUniversity of Bristolhttp://www.bristol.ac.uk/Wolfgang Glaswolfgang.glas@iteg.atITEG IT-Engineers GmbHhttps://www.iteg.at/BSDhttps://github.com/iteggmbh/java-rdfa/blob/master/COPYINGreposcm:git:git://github.com/iteggmbh/java-rdfa.gitscm:git:git@github.com:iteggmbh/java-rdfa.githttps://github.com/iteggmbh/java-rdfajava-rdfa-parent-1.0.0-BETA1ossrhhttps://oss.sonatype.org/content/repositories/snapshotsossrhhttps://oss.sonatype.org/service/local/staging/deploy/maven2/org.apache.maven.pluginsmaven-compiler-plugin1.81.8${project.build.sourceEncoding}org.apache.maven.pluginsmaven-resources-plugin${project.build.sourceEncoding}org.apache.maven.pluginsmaven-jar-plugintruerdfa.simpleparseorg.apache.maven.pluginsmaven-surefire-plugin**/*.java**/Scratch.java**/*$*.javaonceorg.apache.maven.pluginsmaven-source-pluginattach-sourcesjarorg.apache.maven.pluginsmaven-javadoc-plugintrue
http://docs.oracle.com/javase/6/docs/api/
http://jena.apache.org/documentation/javadoc/jena/
http://jena.apache.org/documentation/javadoc/arq/
http://www.openrdf.org/doc/sesame2/api/
1.8attach-javadocsjarorg.apache.maven.pluginsmaven-site-pluginorg.sonatype.pluginsnexus-staging-maven-plugin1.6.7trueossrhhttps://oss.sonatype.org/trueorg.apache.maven.pluginsmaven-release-plugin2.5.3truefalsereleasedeployreleaseorg.apache.maven.pluginsmaven-gpg-plugin1.6sign-artifactsverifysignorg.apache.maven.pluginsmaven-javadoc-plugintrue
http://docs.oracle.com/javase/6/docs/api/
http://jena.apache.org/documentation/javadoc/jena/
http://jena.apache.org/documentation/javadoc/arq/
http://www.openrdf.org/doc/sesame2/api/
1.8UTF-81.7.30
java-rdfa-java-rdfa-parent-1.0.0-BETA1/rdfa-module/ 0000775 0000000 0000000 00000000000 13761231531 0021456 5 ustar 00root root 0000000 0000000 java-rdfa-java-rdfa-parent-1.0.0-BETA1/rdfa-module/pom.xml 0000664 0000000 0000000 00000012622 13761231531 0022776 0 ustar 00root root 0000000 0000000
4.0.0net.rootdevjava-rdfabundle1.0.0-BETA13.16.0UTF-8java-rdfa
A SAX-based java RDFa parser.
net.rootdevjava-rdfa-parent1.0.0-BETA1..2009http://rootdev.net/maven/projects/java-rdfa/GitHubhttps://github.com/iteggmbh/java-rdfa/issuesDamian Steerpldms@mac.comUniversity of Bristolhttp://www.bristol.ac.uk/Wolfgang Glaswolfgang.glas@iteg.atITEG IT-Engineers GmbHhttps://www.iteg.at/BSDhttps://github.com/iteggmbh/java-rdfa/blob/master/COPYINGreposcm:git:git://github.com/iteggmbh/java-rdfa.gitscm:git:git@github.com:iteggmbh/java-rdfa.githttps://github.com/iteggmbh/java-rdfajava-rdfa-parent-1.0.0-BETA1src/main/resources/library.propertiessrc/main/resourcestrueorg.apache.maven.pluginsmaven-resources-plugin${project.build.sourceEncoding}org.apache.maven.pluginsmaven-jar-plugintruerdfa.simpleparseorg.apache.maven.pluginsmaven-surefire-plugin**/*.java**/Scratch.java**/*$*.javaonceorg.apache.maven.pluginsmaven-site-pluginorg.apache.felixmaven-bundle-plugin5.1.1truenet.rootdev.javardfa,net.rootdev.javardfa.**junitjunit4.5testorg.apache.jenajena-core${org.apache.jena.version}jarprovidedorg.apache.jenajena-iri${org.apache.jena.version}jarcompileorg.apache.jenajena-arq${org.apache.jena.version}jarprovidedorg.slf4jslf4j-api${slf4j.version}compileorg.slf4jslf4j-log4j12${slf4j.version}providednet.rootdevjava-rdfa-htmlparser1.0.0-BETA1compiletrueorg.apache.maven.pluginsmaven-javadoc-plugintrue
http://docs.oracle.com/javase/6/docs/api/
http://jena.apache.org/documentation/javadoc/jena/
http://jena.apache.org/documentation/javadoc/arq/
http://www.openrdf.org/doc/sesame2/api/
java-rdfa-java-rdfa-parent-1.0.0-BETA1/rdfa-module/src/ 0000775 0000000 0000000 00000000000 13761231531 0022245 5 ustar 00root root 0000000 0000000 java-rdfa-java-rdfa-parent-1.0.0-BETA1/rdfa-module/src/main/ 0000775 0000000 0000000 00000000000 13761231531 0023171 5 ustar 00root root 0000000 0000000 java-rdfa-java-rdfa-parent-1.0.0-BETA1/rdfa-module/src/main/java/ 0000775 0000000 0000000 00000000000 13761231531 0024112 5 ustar 00root root 0000000 0000000 java-rdfa-java-rdfa-parent-1.0.0-BETA1/rdfa-module/src/main/java/net/ 0000775 0000000 0000000 00000000000 13761231531 0024700 5 ustar 00root root 0000000 0000000 java-rdfa-java-rdfa-parent-1.0.0-BETA1/rdfa-module/src/main/java/net/rootdev/ 0000775 0000000 0000000 00000000000 13761231531 0026362 5 ustar 00root root 0000000 0000000 java-rdfa-java-rdfa-parent-1.0.0-BETA1/rdfa-module/src/main/java/net/rootdev/javardfa/ 0000775 0000000 0000000 00000000000 13761231531 0030140 5 ustar 00root root 0000000 0000000 java-rdfa-java-rdfa-parent-1.0.0-BETA1/rdfa-module/src/main/java/net/rootdev/javardfa/Constants.java0000664 0000000 0000000 00000015413 13761231531 0032763 0 ustar 00root root 0000000 0000000 /*
* (c) Copyright 2009 University of Bristol
* All rights reserved.
* [See end of file]
*/
package net.rootdev.javardfa;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.xml.namespace.QName;
/**
*
* @author pldms
*/
public class Constants {
final static List _allowed = Arrays.asList(
"alternate", "appendix", "bookmark", "cite",
"chapter", "contents", "copyright", "first",
"glossary", "help", "icon", "index", "last",
"license", "meta", "next", "p3pv1", "prev",
"collection", "role", "section", "stylesheet",
"subsection", "start", "top", "up");
public final static Set SpecialRels = new HashSet(_allowed);
public final static String xhtmlNS = "http://www.w3.org/1999/xhtml";
// Suggestion: switch this for object produced by factory that matches QNames
// we can then en-slacken if needed by passing in different factory etc
public final static QName about = new QName("about"); // safe
public final static QName resource = new QName("resource"); // safe
public final static QName href = new QName("href"); // URI
public final static QName src = new QName("src"); // URI
public final static QName property = new QName("property"); // CURIE
public final static QName datatype = new QName("datatype"); // CURIE
public final static QName typeof = new QName("typeof"); // CURIE
public final static QName rel = new QName("rel"); // Link types and CURIES
public final static QName rev = new QName("rev"); // Link type and CURIES
public final static QName content = new QName("content");
public final static QName xmllang = new QName("xml:lang");
public final static QName xmlbase = new QName("xml:base");
public final static QName xmlbaseNS = new QName("http://www.w3.org/XML/1998/namespace", "base", "xml");
public final static QName xmllangNS = new QName("http://www.w3.org/XML/1998/namespace", "lang", "xml");
public final static QName lang = new QName("lang");
public final static QName base = new QName("http://www.w3.org/1999/xhtml", "base");
public final static QName head = new QName("http://www.w3.org/1999/xhtml", "head");
public final static QName body = new QName("http://www.w3.org/1999/xhtml", "body");
// Hack bits
public final static QName input = new QName("http://www.w3.org/1999/xhtml", "input");
public final static QName name = new QName("name");
public final static QName form = new QName("http://www.w3.org/1999/xhtml", "form");
public final static Collection rdfType = Collections.singleton("http://www.w3.org/1999/02/22-rdf-syntax-ns#type");
public final static Collection rdfaUses = Collections.singleton("http://www.w3.org/ns/rdfa#usesVocabulary");
// RDFa 1.1
public final static QName vocab = new QName("vocab");
public final static QName profile = new QName("profile");
public final static QName prefix = new QName("prefix");
private static Map newMap(String... keyVals) {
Map map = new HashMap();
for (int i = 0; i < keyVals.length; i += 2) {
map.put(keyVals[i], keyVals[i + 1]);
}
return map;
}
public final static Map CORE_DEFAULT_PREFIXES =
newMap(
"xhv" , "http://www.w3.org/1999/xhtml/vocab#" ,
"xml" , "http://www.w3.org/XML/1998/namespace" ,
"rdf" , "http://www.w3.org/1999/02/22-rdf-syntax-ns#" ,
"cc" , "http://creativecommons.org/ns#" ,
"foaf" , "http://xmlns.com/foaf/0.1/" ,
"rdfs" , "http://www.w3.org/2000/01/rdf-schema#" ,
"gr" , "http://purl.org/goodrelations/v1#" ,
"skosxl" , "http://www.w3.org/2008/05/skos-xl#" ,
"dc" , "http://purl.org/dc/terms/" ,
"vcard" , "http://www.w3.org/2006/vcard/ns#" ,
"rif" , "http://www.w3.org/2007/rif#" ,
"owl" , "http://www.w3.org/2002/07/owl#" ,
"dcterms" , "http://purl.org/dc/terms/" ,
"void" , "http://rdfs.org/ns/void#" ,
"v" , "http://rdf.data-vocabulary.org/#" ,
"xsd" , "http://www.w3.org/2001/XMLSchema#" ,
"wdrs" , "http://www.w3.org/2007/05/powder-s#" ,
"ma" , "http://www.w3.org/ns/ma-ont#" ,
"schema" , "http://schema.org/" ,
"rdfa" , "http://www.w3.org/ns/rdfa#" ,
"wdr" , "http://www.w3.org/2007/05/powder#" ,
"ctag" , "http://commontag.org/ns#" ,
"rev" , "http://purl.org/stuff/rev#" ,
"ical" , "http://www.w3.org/2002/12/cal/icaltzd#" ,
"skos" , "http://www.w3.org/2004/02/skos/core#" ,
"og" , "http://ogp.me/ns#" ,
"sioc" , "http://rdfs.org/sioc/ns#" ,
"grddl" , "http://www.w3.org/2003/g/data-view#" ,
"describedby:" , "http://www.w3.org/2007/05/powder-s#describedby",
"license:", "http://www.w3.org/1999/xhtml/vocab#license",
"role:", "http://www.w3.org/1999/xhtml/vocab#role"
);
}
/*
* (c) Copyright 2009 University of Bristol
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/ EvalContext.java 0000664 0000000 0000000 00000014514 13761231531 0033165 0 ustar 00root root 0000000 0000000 java-rdfa-java-rdfa-parent-1.0.0-BETA1/rdfa-module/src/main/java/net/rootdev/javardfa /*
* (c) Copyright 2009 University of Bristol
* All rights reserved.
* [See end of file]
*/
package net.rootdev.javardfa;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.xml.namespace.NamespaceContext;
public final class EvalContext implements NamespaceContext {
EvalContext parent;
String base;
String parentSubject;
String parentObject;
String language;
String vocab;
List forwardProperties;
List backwardProperties;
Map xmlnsMap = Collections.EMPTY_MAP;
Map prefixMap = Collections.EMPTY_MAP;
Map termMap = Collections.EMPTY_MAP;
Map> listMap = Collections.EMPTY_MAP;
protected EvalContext(String base) {
super();
this.base = base;
this.parentSubject = base;
this.forwardProperties = new LinkedList();
this.backwardProperties = new LinkedList();
}
public EvalContext(EvalContext toCopy) {
super();
this.base = toCopy.base;
this.parentSubject = toCopy.parentSubject;
this.parentObject = toCopy.parentObject;
this.language = toCopy.language;
this.forwardProperties = new LinkedList(toCopy.forwardProperties);
this.backwardProperties = new LinkedList(toCopy.backwardProperties);
this.parent = toCopy;
this.vocab = toCopy.vocab;
}
public void setBase(String abase) {
// This is very dodgy. We want to check if ps and po have been changed
// from their typical values (base).
// Base changing happens very late in the day when we're streaming, and
// it is very fiddly to handle
boolean setPS = parentSubject == base;
boolean setPO = parentObject == base;
if (abase.contains("#")) {
this.base = abase.substring(0, abase.indexOf("#"));
} else {
this.base = abase;
}
if (setPS) this.parentSubject = base;
if (setPO) this.parentObject = base;
if (parent != null) {
parent.setBase(base);
}
}
@Override
public String toString() {
return
String.format("[\n\tBase: %s\n\tPS: %s\n\tPO: %s\n\tlang: %s\n\tIncomplete: -> %s <- %s\n]",
base, parentSubject, parentObject, language,
forwardProperties.size(), backwardProperties.size()
);
}
/**
* RDFa 1.1 prefix support
* @param prefix Prefix
* @param uri URI
*/
public void setPrefix(String prefix, String uri) {
if (uri.length() == 0) {
uri = base;
}
if (prefixMap == Collections.EMPTY_MAP) prefixMap = new HashMap();
prefixMap.put(prefix, uri);
}
/**
* RDFa 1.1 prefix support
* @param prefix Prefix
* @param uri URI
*/
public void setPrefixes(Map prefixes) {
if (prefixMap == Collections.EMPTY_MAP) prefixMap = new HashMap();
prefixMap.putAll(prefixes);
}
/**
* RDFa 1.1 prefix support.
* @param prefix
* @return
*/
public String getURIForPrefix(String prefix) {
if (prefixMap.containsKey(prefix)) {
return prefixMap.get(prefix);
} else if (xmlnsMap.containsKey(prefix)) {
return xmlnsMap.get(prefix);
} else if (parent != null) {
return parent.getURIForPrefix(prefix);
} else {
return null;
}
}
// Namespace methods
public void setNamespaceURI(String prefix, String uri) {
/*if (uri.length() == 0) {
uri = base;
}
if (xmlnsMap == Collections.EMPTY_MAP) xmlnsMap = new HashMap();
xmlnsMap.put(prefix, uri);*/
setPrefix(prefix, uri);
}
public String getNamespaceURI(String prefix) {
/*if (xmlnsMap.containsKey(prefix)) {
return xmlnsMap.get(prefix);
} else if (parent != null) {
return parent.getNamespaceURI(prefix);
} else {
return null;
}*/
return getURIForPrefix(prefix);
}
// I'm not sure about this 1.1 term business. Reuse prefix map
public void setTerm(String term, String uri) {
setPrefix(term + ":", uri);
}
public String getURIForTerm(String term) {
return getURIForPrefix(term + ":");
}
public String getBase() {
return base;
}
public String getVocab() {
return vocab;
}
public String getPrefix(String namespaceURI) {
throw new UnsupportedOperationException("Not supported yet.");
}
public Iterator getPrefixes(String namespaceURI) {
throw new UnsupportedOperationException("Not supported yet.");
}
}
/*
* (c) Copyright 2009 University of Bristol
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/ java-rdfa-java-rdfa-parent-1.0.0-BETA1/rdfa-module/src/main/java/net/rootdev/javardfa/Parser.java 0000664 0000000 0000000 00000064516 13761231531 0032253 0 ustar 00root root 0000000 0000000 /*
* (c) Copyright 2009 University of Bristol
* All rights reserved.
* [See end of file]
*/
package net.rootdev.javardfa;
import net.rootdev.javardfa.uri.URIExtractor10;
import net.rootdev.javardfa.uri.URIExtractor;
import net.rootdev.javardfa.uri.IRIResolver;
import net.rootdev.javardfa.literal.LiteralCollector;
import java.util.Collection;
import java.util.EnumSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLEventFactory;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.ErrorHandler;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
/**
* @author Damian Steer
*/
public class Parser implements ContentHandler, ErrorHandler {
private final XMLEventFactory eventFactory;
private final StatementSink sink;
private final Set settings;
private final LiteralCollector literalCollector;
private final URIExtractor extractor;
public Parser(StatementSink sink) {
this( sink,
XMLOutputFactory.newInstance(),
XMLEventFactory.newInstance(),
new URIExtractor10(new IRIResolver()));
}
public Parser(StatementSink sink,
XMLOutputFactory outputFactory,
XMLEventFactory eventFactory,
URIExtractor extractor) {
this.sink = sink;
this.eventFactory = eventFactory;
this.settings = EnumSet.noneOf(Setting.class);
this.extractor = extractor;
this.literalCollector = new LiteralCollector(this, eventFactory, outputFactory);
extractor.setSettings(settings);
// Important, although I guess the caller doesn't get total control
outputFactory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true);
}
public boolean isEnabled(Setting setting) {
return settings.contains(setting);
}
public void enable(Setting setting) {
settings.add(setting);
}
public void disable(Setting setting) {
settings.remove(setting);
}
public void setBase(String base) {
this.context = new EvalContext(base);
if (isEnabled(Setting.OnePointOne)) context.setPrefixes(Constants.CORE_DEFAULT_PREFIXES);
sink.setBase(context.getBase());
}
EvalContext parse(EvalContext context, StartElement element)
throws XMLStreamException {
String currentLanguage = context.language;
boolean inXHTML = Constants.xhtmlNS.equals(element.getName().getNamespaceURI());
// Respect xml:base outside xhtml
if (element.getAttributeByName(Constants.xmlbaseNS) != null && !inXHTML) {
context.setBase(element.getAttributeByName(Constants.xmlbaseNS).getValue());
sink.setBase(context.getBase());
}
if (Constants.base.equals(element.getName()) &&
element.getAttributeByName(Constants.href) != null) {
context.setBase(element.getAttributeByName(Constants.href).getValue());
sink.setBase(context.getBase());
}
// The xml / html namespace matching is a bit ropey. I wonder if the html 5
// parser has a setting for this?
if (settings.contains(Setting.ManualNamespaces)) {
if (element.getAttributeByName(Constants.xmllang) != null) {
currentLanguage = element.getAttributeByName(Constants.xmllang).getValue();
if (currentLanguage.length() == 0) currentLanguage = null;
} else if (element.getAttributeByName(Constants.lang) != null) {
currentLanguage = element.getAttributeByName(Constants.lang).getValue();
if (currentLanguage.length() == 0) currentLanguage = null;
}
} else if (element.getAttributeByName(Constants.xmllangNS) != null) {
currentLanguage = element.getAttributeByName(Constants.xmllangNS).getValue();
if (currentLanguage.length() == 0) currentLanguage = null;
}
if (settings.contains(Setting.OnePointOne)) {
if (element.getAttributeByName(Constants.vocab) != null) {
String vocab =
element.getAttributeByName(Constants.vocab).getValue().trim();
// empty vocab removes default vocab
if (vocab.length() == 0) {
context.vocab = null;
} else {
context.vocab = vocab;
emitTriples(context.base, Constants.rdfaUses, vocab);
}
}
if (element.getAttributeByName(Constants.prefix) != null) {
parsePrefixes(element.getAttributeByName(Constants.prefix).getValue(), context);
}
}
String about = extractor.getURI(element, Constants.about, context);
String src = extractor.getURI(element, Constants.src, context);
String href = extractor.getURI(element, Constants.href, context);
String resource = extractor.getURI(element, Constants.resource, context);
String datatype = extractor.getURI(element, Constants.datatype, context);
Attribute contentAttr = element.getAttributeByName(Constants.content);
String content = (contentAttr == null) ? null : contentAttr.getValue();
List typeof = extractor.getURIs(element, Constants.typeof, context);
List rel = extractor.getURIs(element, Constants.rel, context);
List rev = extractor.getURIs(element, Constants.rev, context);
List property = extractor.getURIs(element, Constants.property, context);
if (settings.contains(Setting.OnePointOne)) {
return parse11(rev, rel, about, src, resource, href, context, inXHTML,
element, typeof, property, content, datatype, currentLanguage);
} else {
return parse10(rev, rel, about, src, resource, href, context, inXHTML,
element, typeof, property, content, datatype, currentLanguage);
}
}
private EvalContext parse10(List rev, List rel, String about, String src, String resource, String href, EvalContext context, boolean inXHTML, StartElement element, List typeof, List property, String content, String datatype, String currentLanguage) {
boolean skipElement = false;
String newSubject = null;
String currentObject = null;
List forwardProperties = new LinkedList();
List backwardProperties = new LinkedList();
if (rev == null && rel == null) {
newSubject = coalesce(about, src, resource, href);
if (newSubject == null) {
if (context.parent == null && !inXHTML) {
newSubject = context.base;
} else if (Constants.body.equals(element.getName()) ||
Constants.head.equals(element.getName())) {
newSubject = context.base;
} else if (typeof != null) {
newSubject = createBNode();
} else {
if (context.parentObject != null) {
newSubject = context.parentObject;
}
if (property == null) {
skipElement = true;
}
}
}
} else {
newSubject = coalesce(about, src);
if (newSubject == null) {
if (context.parent == null && !inXHTML) {
newSubject = context.base;
} else if (Constants.head.equals(element.getName()) ||
Constants.body.equals(element.getName())) {
newSubject = context.base;
} else if (typeof != null) {
newSubject = createBNode();
} else if (context.parentObject != null) {
newSubject = context.parentObject;
}
}
currentObject = coalesce(resource, href);
}
if (newSubject != null && typeof != null) {
for (String type : typeof) {
emitTriples(newSubject,
Constants.rdfType,
type);
}
}
// Dodgy extension
if (settings.contains(Setting.FormMode)) {
if (Constants.form.equals(element.getName())) {
emitTriples(newSubject, Constants.rdfType, "http://www.w3.org/1999/xhtml/vocab/#form"); // Signal entering form
}
if (Constants.input.equals(element.getName()) &&
element.getAttributeByName(Constants.name) != null) {
currentObject = "?" + element.getAttributeByName(Constants.name).getValue();
}
}
if (property != null) {
if (content != null) { // The easy bit
if (datatype == null || datatype.length() == 0) {
emitTriplesPlainLiteral(newSubject, property, content, currentLanguage);
} else {
emitTriplesDatatypeLiteral(newSubject, property, content, datatype);
}
} else {
literalCollector.collect(newSubject, property, datatype, currentLanguage);
}
}
if (currentObject != null) {
if (element.getAttributeByName(Constants.rel) != null) {
emitTriples(newSubject, rel, currentObject);
}
if (element.getAttributeByName(Constants.rev) != null) {
emitTriples(currentObject, rev, newSubject);
}
} else {
if (element.getAttributeByName(Constants.rel) != null) {
forwardProperties.addAll(rel);
}
if (element.getAttributeByName(Constants.rev) != null) {
backwardProperties.addAll(rev);
}
if (!forwardProperties.isEmpty() || !backwardProperties.isEmpty()) {
// if predicate present
currentObject = createBNode();
}
}
if (!skipElement && newSubject != null) {
emitTriples(context.parentSubject,
context.forwardProperties,
newSubject);
emitTriples(newSubject,
context.backwardProperties,
context.parentSubject);
}
EvalContext ec = new EvalContext(context);
if (skipElement) {
ec.language = currentLanguage;
} else {
if (newSubject != null) {
ec.parentSubject = newSubject;
} else {
ec.parentSubject = context.parentSubject;
}
if (currentObject != null) {
ec.parentObject = currentObject;
} else if (newSubject != null) {
ec.parentObject = newSubject;
} else {
ec.parentObject = context.parentSubject;
}
ec.language = currentLanguage;
ec.forwardProperties = forwardProperties;
ec.backwardProperties = backwardProperties;
}
return ec;
}
private EvalContext parse11(List rev, List rel, String about, String src, String resource, String href, EvalContext context, boolean inXHTML, StartElement element, List typeof, List property, String content, String datatype, String currentLanguage) {
boolean skipElement = false;
String newSubject = null;
String currentObject = null;
String typedResource = null;
List forwardProperties = new LinkedList();
List backwardProperties = new LinkedList();
if (rev == null && rel == null) {
if (property != null && content == null && datatype == null) {
if (about != null && about != URIExtractor.NONE) newSubject = about;
else if (context.parent == null) newSubject = context.base;
else if (context.parentObject != null) newSubject = context.parentObject;
if (typeof != null) {
if (about != null && about != URIExtractor.NONE) typedResource = about;
else if (context.parent == null) typedResource = context.base;
else typedResource = coalesce(resource, href, src);
if (typedResource == null) typedResource = createBNode();
currentObject = typedResource;
}
} else {
newSubject = coalesce(about, resource, href, src);
if (newSubject == null) {
if (context.parent == null) newSubject = context.base;
else if (typeof != null) newSubject = createBNode();
else if (context.parentObject != null) {
newSubject = context.parentObject;
if (property == null) skipElement = true;
}
}
if (typeof != null) typedResource = newSubject;
}
} else { // rev or rel present
if (about != null && about != URIExtractor.NONE) newSubject = about;
if (typeof != null) typedResource = newSubject;
if (newSubject == null) {
if (context.parent == null) newSubject = context.base;
else if (context.parentObject != null) newSubject = context.parentObject;
}
currentObject = coalesce(resource, href, src);
if (currentObject == null && typeof != null && about == null) currentObject = createBNode();
if (typeof != null && about == null) typedResource = currentObject;
}
if (typedResource != null) {
for (String type : typeof) {
emitTriples(typedResource,
Constants.rdfType,
type);
}
}
// STEP 8 skipped... list etc
if (currentObject != null) {
if (rel != null) emitTriples(newSubject, rel, currentObject);
if (rev != null) emitTriples(currentObject, rev, newSubject);
} else {
// Do I really want to add all here, or simply assign???
if (rel != null) forwardProperties.addAll(rel);
if (rev != null) backwardProperties.addAll(rev);
if (rev != null || rel != null) currentObject = createBNode();
}
if (property != null) {
String propertyValue = null;
if (content != null) { // The easy bit
if (datatype == null || datatype.length() == 0) {
emitTriplesPlainLiteral(newSubject, property, content, currentLanguage);
} else {
emitTriplesDatatypeLiteral(newSubject, property, content, datatype);
}
propertyValue = URIExtractor.NONE;
} else if (datatype != null) {
literalCollector.collect(newSubject, property, datatype, currentLanguage);
propertyValue = URIExtractor.NONE;
} else if (rev == null && rev == null && content == null) {
propertyValue = coalesce(resource, href, src);
}
if (propertyValue == null && typeof != null && about == null) {
propertyValue = typedResource;
}
if (propertyValue == null && content == null && datatype == null) {
literalCollector.collect(newSubject, property, datatype, currentLanguage);
}
if (propertyValue != null && propertyValue != URIExtractor.NONE) emitTriples(newSubject, property, propertyValue);
}
if (!skipElement && newSubject != null) {
emitTriples(context.parentSubject,
context.forwardProperties,
newSubject);
emitTriples(newSubject,
context.backwardProperties,
context.parentSubject);
}
EvalContext ec = new EvalContext(context);
if (skipElement) {
ec.language = currentLanguage;
} else {
if (newSubject != null) {
ec.parentSubject = newSubject;
} else {
ec.parentSubject = context.parentSubject;
}
if (currentObject != null) {
ec.parentObject = currentObject;
} else if (newSubject != null) {
ec.parentObject = newSubject;
} else {
ec.parentObject = context.parentSubject;
}
ec.language = currentLanguage;
ec.forwardProperties = forwardProperties;
ec.backwardProperties = backwardProperties;
}
return ec;
}
public void emitTriples(String subj, Collection props, String obj) {
for (String prop : props) {
if (!prop.startsWith("_")) sink.addObject(subj, prop, obj);
}
}
public void emitTriplesPlainLiteral(String subj, Collection props, String lex, String language) {
for (String prop : props) {
if (!prop.startsWith("_")) sink.addLiteral(subj, prop, lex, language, null);
}
}
public void emitTriplesDatatypeLiteral(String subj, Collection props, String lex, String datatype) {
for (String prop : props) {
if (!prop.startsWith("_")) sink.addLiteral(subj, prop, lex, null, datatype);
}
}
int bnodeId = 0;
private String createBNode() // TODO probably broken? Can you write bnodes in rdfa directly?
{
return "_:node" + (bnodeId++);
}
private void getNamespaces(Attributes attrs) {
for (int i = 0; i < attrs.getLength(); i++) {
String qname = attrs.getQName(i);
String prefix = getPrefix(qname);
if ("xmlns".equals(prefix)) {
String pre = getLocal(prefix, qname);
String uri = attrs.getValue(i);
if (!settings.contains(Setting.ManualNamespaces) && pre.contains("_"))
continue; // not permitted
context.setNamespaceURI(pre, uri);
sink.addPrefix(pre, uri);
}
}
}
private String getPrefix(String qname) {
if (!qname.contains(":")) {
return "";
}
return qname.substring(0, qname.indexOf(":"));
}
private String getLocal(String prefix, String qname) {
if (prefix.length() == 0) {
return qname;
}
return qname.substring(prefix.length() + 1);
}
/**
* SAX methods
*/
private Locator locator;
private EvalContext context;
public void setDocumentLocator(Locator arg0) {
this.locator = arg0;
if (locator.getSystemId() != null)
this.setBase(arg0.getSystemId());
}
public void startDocument() throws SAXException {
sink.start();
}
public void endDocument() throws SAXException {
sink.end();
}
public void startPrefixMapping(String arg0, String arg1)
throws SAXException {
context.setNamespaceURI(arg0, arg1);
sink.addPrefix(arg0, arg1);
}
public void endPrefixMapping(String arg0) throws SAXException {
}
public void startElement(String arg0, String localname, String qname, Attributes arg3) throws SAXException {
try {
//System.err.println("Start element: " + arg0 + " " + arg1 + " " + arg2);
// This is set very late in some html5 cases (not even ready by document start)
if (context == null) {
this.setBase(locator.getSystemId());
}
// Dammit, not quite the same as XMLEventFactory
String prefix = /*(localname.equals(qname))*/
(qname.indexOf(':') == -1 ) ? ""
: qname.substring(0, qname.indexOf(':'));
if (settings.contains(Setting.ManualNamespaces)) {
getNamespaces(arg3);
if (prefix.length() != 0) {
arg0 = context.getNamespaceURI(prefix);
localname = localname.substring(prefix.length() + 1);
}
}
StartElement e = eventFactory.createStartElement(
prefix, arg0, localname,
fromAttributes(arg3), null, context);
if (literalCollector.isCollecting()) literalCollector.handleEvent(e);
// If we are gathering XML we stop parsing
if (!literalCollector.isCollectingXML()) context = parse(context, e);
} catch (XMLStreamException ex) {
throw new RuntimeException("Streaming issue", ex);
}
}
public void endElement(String arg0, String localname, String qname) throws SAXException {
//System.err.println("End element: " + arg0 + " " + arg1 + " " + arg2);
if (literalCollector.isCollecting()) {
String prefix = (localname.equals(qname)) ? ""
: qname.substring(0, qname.indexOf(':'));
XMLEvent e = eventFactory.createEndElement(prefix, arg0, localname);
literalCollector.handleEvent(e);
}
// If we aren't collecting an XML literal keep parsing
if (!literalCollector.isCollectingXML()) context = context.parent;
}
public void characters(char[] arg0, int arg1, int arg2) throws SAXException {
if (literalCollector.isCollecting()) {
XMLEvent e = eventFactory.createCharacters(String.valueOf(arg0, arg1, arg2));
literalCollector.handleEvent(e);
}
}
public void ignorableWhitespace(char[] arg0, int arg1, int arg2) throws SAXException {
//System.err.println("Whitespace...");
if (literalCollector.isCollecting()) {
XMLEvent e = eventFactory.createIgnorableSpace(String.valueOf(arg0, arg1, arg2));
literalCollector.handleEvent(e);
}
}
public void processingInstruction(String arg0, String arg1) throws SAXException {
}
public void skippedEntity(String arg0) throws SAXException {
}
private Iterator fromAttributes(Attributes attributes) {
List toReturn = new LinkedList();
for (int i = 0; i < attributes.getLength(); i++) {
String qname = attributes.getQName(i);
String prefix = qname.contains(":") ? qname.substring(0, qname.indexOf(":")) : "";
Attribute attr = eventFactory.createAttribute(
prefix, attributes.getURI(i),
attributes.getLocalName(i), attributes.getValue(i));
if (!qname.equals("xmlns") && !qname.startsWith("xmlns:"))
toReturn.add(attr);
}
return toReturn.iterator();
}
// 1.1 method
private void parsePrefixes(String value, EvalContext context) {
String[] parts = value.split("\\s+");
for (int i = 0; i < parts.length; i += 2) {
String prefix = parts[i];
if (i + 1 < parts.length && prefix.endsWith(":")) {
String prefixFix = prefix.substring(0, prefix.length() - 1);
context.setPrefix(prefixFix, parts[i+1]);
sink.addPrefix(prefixFix, parts[i+1]);
}
}
}
// SAX error handling
public void warning(SAXParseException exception) throws SAXException {
System.err.printf("Warning: %s\n", exception.getLocalizedMessage());
}
public void error(SAXParseException exception) throws SAXException {
System.err.printf("Error: %s\n", exception.getLocalizedMessage());
}
public void fatalError(SAXParseException exception) throws SAXException {
System.err.printf("Fatal error: %s\n", exception.getLocalizedMessage());
}
// Coalesce utility functions. Useful in parsing.
private static T coalesce(T a, T b) {
if (a != null && a != URIExtractor.NONE) return a;
return b;
}
private static T coalesce(T a, T b, T c) {
if (a != null && a != URIExtractor.NONE) return a;
if (b != null && b != URIExtractor.NONE) return b;
return c;
}
private static T coalesce(T a, T b, T c, T d) {
if (a != null && a != URIExtractor.NONE) return a;
if (b != null && b != URIExtractor.NONE) return b;
if (c != null && c != URIExtractor.NONE) return c;
return d;
}
}
/*
* (c) Copyright 2009 University of Bristol
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
ParserFactory.java 0000664 0000000 0000000 00000013411 13761231531 0033510 0 ustar 00root root 0000000 0000000 java-rdfa-java-rdfa-parent-1.0.0-BETA1/rdfa-module/src/main/java/net/rootdev/javardfa /*
* (c) Copyright 2009 University of Bristol
* All rights reserved.
* [See end of file]
*/
package net.rootdev.javardfa;
import net.rootdev.javardfa.uri.URIExtractor10;
import net.rootdev.javardfa.uri.URIExtractor;
import net.rootdev.javardfa.uri.URIExtractor11;
import net.rootdev.javardfa.uri.IRIResolver;
import javax.xml.stream.XMLEventFactory;
import javax.xml.stream.XMLOutputFactory;
import nu.validator.htmlparser.common.XmlViolationPolicy;
import nu.validator.htmlparser.sax.HtmlParser;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;
/**
* I use these in a few places. stuck here for simplicity
*
* @author pldms
*/
public class ParserFactory {
public enum Format {
HTML, XHTML;
public static Format lookup(String format) {
if ("xhtml".equalsIgnoreCase(format)) {
return XHTML;
}
if ("html".equalsIgnoreCase(format)) {
return HTML;
}
return null;
}
}
/**
*
* @return An XMLReader with validation turned off
* @throws SAXException
*/
public static XMLReader createNonvalidatingReader() throws SAXException {
XMLReader reader = XMLReaderFactory.createXMLReader();
reader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
try {
reader.setFeature("http://www.xml.org/sax/features/validation", false);
} catch (Exception e) {} // continue whether this is recognised
return reader;
}
/**
*
* @return An HTML 5 XMLReader set up to by fairly forgiving.
*/
public static XMLReader createHTML5Reader() {
HtmlParser reader = new HtmlParser();
reader.setXmlPolicy(XmlViolationPolicy.ALLOW);
reader.setXmlnsPolicy(XmlViolationPolicy.ALLOW);
reader.setMappingLangToXmlLang(false);
return reader;
}
/**
* Makes an XMLReader appropriate to the format, with an rdfa parser plumbed
* to the StatementSink sink. Uses IRI resolver.
*
* @param sink
* @param format
* @return
* @throws SAXException
*/
public static XMLReader createReaderForFormat(StatementSink sink,
Format format, Setting... settings) throws SAXException {
return createReaderForFormat(sink, format, new IRIResolver(), settings);
}
/**
* Makes an XMLReader appropriate to the format, with an rdfa parser plumbed
* to the StatementSink sink.
*
* @param sink
* @param format
* @param resolver
* @return
* @throws SAXException
*/
public static XMLReader createReaderForFormat(StatementSink sink,
Format format, Resolver resolver, Setting... settings) throws SAXException {
XMLReader reader = getReader(format);
boolean is11 = false;
for (Setting setting: settings) if (setting == Setting.OnePointOne) is11 = true;
URIExtractor extractor = (is11) ?
new URIExtractor11(resolver) : new URIExtractor10(resolver);
Parser parser = getParser(format, sink, extractor);
for (Setting setting: settings) parser.enable(setting);
reader.setContentHandler(parser);
reader.setErrorHandler(parser);
return reader;
}
private static XMLReader getReader(Format format) throws SAXException {
switch (format) {
case XHTML:
return ParserFactory.createNonvalidatingReader();
default:
return ParserFactory.createHTML5Reader();
}
}
private static Parser getParser(Format format, StatementSink sink,
URIExtractor extractor) {
return getParser(format, sink, XMLOutputFactory.newInstance(),
XMLEventFactory.newInstance(), extractor);
}
private static Parser getParser(Format format, StatementSink sink,
XMLOutputFactory outputFactory, XMLEventFactory eventFactory,
URIExtractor extractor) {
switch (format) {
case XHTML:
return new Parser(sink, outputFactory, eventFactory, extractor);
default:
Parser p = new Parser(sink, outputFactory, eventFactory, extractor);
p.enable(Setting.ManualNamespaces);
return p;
}
}
}
/*
* (c) Copyright 2009 University of Bristol
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
java-rdfa-java-rdfa-parent-1.0.0-BETA1/rdfa-module/src/main/java/net/rootdev/javardfa/Resolver.java 0000664 0000000 0000000 00000003525 13761231531 0032611 0 ustar 00root root 0000000 0000000 /*
* (c) Copyright 2009 University of Bristol
* All rights reserved.
* [See end of file]
*/
package net.rootdev.javardfa;
/**
* Resolve URI relative to a given URI
*
* @author pldms
*/
public interface Resolver {
/**
* Resolve second URI relative to first.
* @param first
* @param second
* @return
*/
public String resolve(String first, String second);
}
/*
* (c) Copyright 2009 University of Bristol
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/ java-rdfa-java-rdfa-parent-1.0.0-BETA1/rdfa-module/src/main/java/net/rootdev/javardfa/Setting.java 0000664 0000000 0000000 00000003211 13761231531 0032415 0 ustar 00root root 0000000 0000000 /*
* (c) Copyright 2010 University of Bristol
* All rights reserved.
* [See end of file]
*/
package net.rootdev.javardfa;
public enum Setting {
FormMode, ManualNamespaces, OnePointOne
}
/*
* (c) Copyright 2010 University of Bristol
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/ StatementSink.java 0000664 0000000 0000000 00000005311 13761231531 0033515 0 ustar 00root root 0000000 0000000 java-rdfa-java-rdfa-parent-1.0.0-BETA1/rdfa-module/src/main/java/net/rootdev/javardfa /*
* (c) Copyright 2009 University of Bristol
* All rights reserved.
* [See end of file]
*/
package net.rootdev.javardfa;
/**
* @author Damian Steer
*/
public interface StatementSink
{
/**
*
*/
public void setBase(String base);
/**
* Begin parsing
*/
public void start();
/**
* Complete parsing
*/
public void end();
/**
* Add statement with non-literal object.
* Blank nodes begin with _:, variables with ?, otherwise IRI
* @param subject Subject of triple
* @param predicate Predicate
* @param object Object
*/
public void addObject(String subject, String predicate, String object);
/**
* Add statement with a literal object.
* As above, blank nodes begin with _:, variables with ?, otherwise IRI
* @param subject Subject of triple
* @param predicate Predicate
* @param lex Lexical form
* @param lang Language (may be null)
* @param datatype Datatype IRI (may be null)
*/
public void addLiteral(String subject, String predicate, String lex, String lang, String datatype);
/**
* Add a prefix mapping.
* @param prefix
* @param uri
*/
public void addPrefix(String prefix, String uri);
}
/*
* (c) Copyright 2009 University of Bristol
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/ java-rdfa-java-rdfa-parent-1.0.0-BETA1/rdfa-module/src/main/java/net/rootdev/javardfa/Version.java 0000664 0000000 0000000 00000005314 13761231531 0032433 0 ustar 00root root 0000000 0000000 /*
* (c) Copyright 2009 University of Bristol
* All rights reserved.
* [See end of file]
*/
package net.rootdev.javardfa;
import java.io.IOException;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author pldms
*/
public class Version {
private final static Logger log = LoggerFactory.getLogger(Version.class);
private final static Version i = new Version();
private final String name;
private final String version;
public static Version get() { return i; }
public Version() {
Properties props = new Properties();
String _name, _version;
try {
props.load(Version.class.getResourceAsStream("/library.properties"));
_name = props.getProperty("library.name");
_version = props.getProperty("library.version");
} catch (IOException ex) {
log.error("Error loading version info from library.properties", ex);
_name = "Unknown";
_version = "Unknown";
}
this.name = _name;
this.version = _version;
}
public String getName() { return this.name; }
public String getVersion() { return this.version; }
public String toString() { return getName() + " " + getVersion(); }
}
/*
* (c) Copyright 2009 University of Bristol
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/ java-rdfa-java-rdfa-parent-1.0.0-BETA1/rdfa-module/src/main/java/net/rootdev/javardfa/jena/ 0000775 0000000 0000000 00000000000 13761231531 0031055 5 ustar 00root root 0000000 0000000 JenaStatementSink.java 0000664 0000000 0000000 00000007610 13761231531 0035234 0 ustar 00root root 0000000 0000000 java-rdfa-java-rdfa-parent-1.0.0-BETA1/rdfa-module/src/main/java/net/rootdev/javardfa/jena /*
* (c) Copyright 2009 University of Bristol
* All rights reserved.
* [See end of file]
*/
package net.rootdev.javardfa.jena;
import org.apache.jena.rdf.model.Literal;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.Property;
import org.apache.jena.rdf.model.Resource;
import org.apache.jena.shared.PrefixMapping.IllegalPrefixException;
import java.util.HashMap;
import java.util.Map;
import net.rootdev.javardfa.StatementSink;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Damian Steer
*/
public class JenaStatementSink implements StatementSink {
private static Logger log = LoggerFactory.getLogger(JenaStatementSink.class);
private final Model model;
private Map bnodeLookup;
public JenaStatementSink(Model model) {
this.model = model;
}
//@Override
public void start() {
bnodeLookup = new HashMap();
}
//@Override
public void end() {
bnodeLookup = null;
}
//@Override
public void addObject(String subject, String predicate, String object) {
Resource s = getResource(subject);
Property p = model.createProperty(predicate);
Resource o = getResource(object);
model.add(s, p, o);
}
//@Override
public void addLiteral(String subject, String predicate, String lex, String lang, String datatype) {
Resource s = getResource(subject);
Property p = model.createProperty(predicate);
Literal o;
if (lang == null && datatype == null) {
o = model.createLiteral(lex);
} else if (lang != null) {
o = model.createLiteral(lex, lang);
} else {
o = model.createTypedLiteral(lex, datatype);
}
model.add(s, p, o);
}
private Resource getResource(String res) {
if (res.startsWith("_:")) {
if (bnodeLookup.containsKey(res)) {
return bnodeLookup.get(res);
}
Resource bnode = model.createResource();
bnodeLookup.put(res, bnode);
return bnode;
} else {
return model.createResource(res);
}
}
public void addPrefix(String prefix, String uri) {
try {
model.setNsPrefix(prefix, uri);
} catch (IllegalPrefixException e) {
log.warn("Bad prefix, continuing.", e);
}
}
public void setBase(String base) {}
}
/*
* (c) Copyright 2009 University of Bristol
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
RDFaReader.java 0000664 0000000 0000000 00000010632 13761231531 0033542 0 ustar 00root root 0000000 0000000 java-rdfa-java-rdfa-parent-1.0.0-BETA1/rdfa-module/src/main/java/net/rootdev/javardfa/jena /*
* (c) Copyright 2009 University of Bristol
* All rights reserved.
* [See end of file]
*/
package net.rootdev.javardfa.jena;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.RDFErrorHandler;
import org.apache.jena.rdf.model.RDFReader;
import org.apache.jena.rdf.model.impl.RDFReaderFImpl;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import net.rootdev.javardfa.Parser;
import net.rootdev.javardfa.ParserFactory;
import net.rootdev.javardfa.Setting;
import net.rootdev.javardfa.StatementSink;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
/**
* @author Damian Steer
*/
public class RDFaReader implements RDFReader {
static {
RDFReaderFImpl.setBaseReaderClassName("HTML", HTMLRDFaReader.class.getName());
RDFReaderFImpl.setBaseReaderClassName("XHTML", XHTMLRDFaReader.class.getName());
}
public static class HTMLRDFaReader extends RDFaReader {
@Override public XMLReader getReader() {
return ParserFactory.createHTML5Reader();
}
@Override public void initParser(Parser parser) {
parser.enable(Setting.ManualNamespaces);
}
}
public static class XHTMLRDFaReader extends RDFaReader {
@Override public XMLReader getReader() throws SAXException {
return ParserFactory.createNonvalidatingReader();
}
}
private XMLReader xmlReader;
public void read(Model arg0, Reader arg1, String arg2) {
this.runParser(arg0, arg2, new InputSource(arg1));
}
public void read(Model arg0, InputStream arg1, String arg2) {
this.runParser(arg0, arg2, new InputSource(arg1));
}
public void read(Model arg0, String arg1) {
this.runParser(arg0, arg1, new InputSource(arg1));
}
public Object setProperty(String arg0, Object arg1) {
throw new UnsupportedOperationException("Not supported yet.");
}
public RDFErrorHandler setErrorHandler(RDFErrorHandler arg0) {
throw new UnsupportedOperationException("Not supported yet.");
}
public void setReader(XMLReader reader) { this.xmlReader = reader; }
public XMLReader getReader() throws SAXException { return xmlReader; }
public void initParser(Parser parser) { }
private StatementSink getSink(Model arg0) {
return new JenaStatementSink(arg0);
}
private void runParser(Model arg0, String arg2, InputSource source) {
StatementSink sink = getSink(arg0);
Parser parser = new Parser(sink);
parser.setBase(arg2);
initParser(parser);
try {
XMLReader xreader = getReader();
xreader.setContentHandler(parser);
xreader.parse(source);
} catch (IOException ex) {
throw new RuntimeException("IO Error when parsing", ex);
} catch (SAXException ex) {
throw new RuntimeException("SAX Error when parsing", ex);
}
}
}
/*
* (c) Copyright 2009 University of Bristol
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
java-rdfa-java-rdfa-parent-1.0.0-BETA1/rdfa-module/src/main/java/net/rootdev/javardfa/literal/ 0000775 0000000 0000000 00000000000 13761231531 0031574 5 ustar 00root root 0000000 0000000 CanonicalXMLEventWriter.java 0000664 0000000 0000000 00000015473 13761231531 0037041 0 ustar 00root root 0000000 0000000 java-rdfa-java-rdfa-parent-1.0.0-BETA1/rdfa-module/src/main/java/net/rootdev/javardfa/literal /*
* (c) Copyright 2009 University of Bristol
* All rights reserved.
* [See end of file]
*/
package net.rootdev.javardfa.literal;
import java.util.Iterator;
import java.util.SortedMap;
import java.util.TreeMap;
import javax.xml.XMLConstants;
import javax.xml.namespace.NamespaceContext;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.ProcessingInstruction;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;
/**
* All this class does currently is ensure the order of attributes, but
* (By using a stream writer) it is more controllable than the event writer.
*
* @author pldms
*/
public class CanonicalXMLEventWriter
implements XMLEventWriter {
private final XMLStreamWriter swriter;
private final Attribute contextLang;
private int level;
public CanonicalXMLEventWriter(XMLStreamWriter swriter, Attribute contextLang) {
this.swriter = swriter;
this.contextLang = contextLang;
this.level = 0;
}
public void flush() throws XMLStreamException {
swriter.flush();
}
public void close() throws XMLStreamException {
swriter.close();
}
public void add(XMLEvent event) throws XMLStreamException {
if (event.isEndElement()) {
level--;
swriter.writeEndElement();
} else if (event.isCharacters()) {
swriter.writeCharacters(event.asCharacters().getData());
} else if (event.isProcessingInstruction()) {
swriter.writeProcessingInstruction(((ProcessingInstruction) event).getData(),
((ProcessingInstruction) event).getTarget());
} else if (event.isStartElement()) {
level++;
StartElement se = event.asStartElement();
if (se.getName().getNamespaceURI() == null ||
se.getName().getNamespaceURI().length() == 0)
swriter.writeStartElement(se.getName().getLocalPart());
else if (se.getName().getPrefix().length() == 0) {
swriter.setDefaultNamespace(se.getName().getNamespaceURI());
swriter.writeStartElement(
se.getName().getNamespaceURI(),
se.getName().getLocalPart());
}
else {
//swriter.setPrefix(se.getName().getPrefix(), se.getName().getNamespaceURI());
swriter.writeStartElement(se.getName().getPrefix(),
se.getName().getLocalPart(),
se.getName().getNamespaceURI());
}
writeAttributes(se);
swriter.writeCharacters(""); // Force close of start element
} else {
System.err.printf("Gah! Missed one <%s>, '%s'\n", event.getClass(), event);
}
}
public void add(XMLEventReader reader) throws XMLStreamException {
while (reader.hasNext()) {
this.add(reader.nextEvent());
}
}
public String getPrefix(String uri) throws XMLStreamException {
return swriter.getPrefix(uri);
}
public void setPrefix(String prefix, String uri) throws XMLStreamException {
swriter.setPrefix(prefix, uri);
}
public void setDefaultNamespace(String uri) throws XMLStreamException {
swriter.setDefaultNamespace(uri);
}
public void setNamespaceContext(NamespaceContext context) throws XMLStreamException {
swriter.setNamespaceContext(context);
}
public NamespaceContext getNamespaceContext() {
return swriter.getNamespaceContext();
}
private void writeAttributes(StartElement se) throws XMLStreamException {
SortedMap atts = new TreeMap();
if (level == 2 && contextLang != null) atts.put("_xml:lang", contextLang);
for (Iterator i = se.getAttributes(); i.hasNext();) {
Attribute a = (Attribute) i.next();
atts.put(getName(a), a);
}
for (Attribute a : atts.values()) {
if (a.getName().getNamespaceURI() == null ||
a.getName().getNamespaceURI().length() == 0)
swriter.writeAttribute(a.getName().getLocalPart(), a.getValue());
else if (a.getName().getPrefix().length() == 0)
swriter.writeAttribute(a.getName().getNamespaceURI(),
a.getName().getLocalPart(), a.getValue());
else
swriter.writeAttribute(
a.getName().getPrefix(),
a.getName().getNamespaceURI(),
a.getName().getLocalPart(),
a.getValue());
}
}
private String getName(Attribute a) {
QName name = a.getName();
String toReturn = null;
// TODO I think something -- probably my code -- is wrong
// localName is sometimes xml:lang, so I got xml:xml:lang
if (name.getLocalPart().contains(":")) toReturn = name.getLocalPart();
else toReturn = (name.getPrefix() == null) ?
name.getLocalPart() :
name.getPrefix() + ":" + name.getLocalPart();
if (toReturn.startsWith("xml:")) {
return "_" + toReturn;
} else {
return toReturn;
}
}
}
/*
* (c) Copyright 2009 University of Bristol
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
LiteralCollector.java 0000664 0000000 0000000 00000015706 13761231531 0035634 0 ustar 00root root 0000000 0000000 java-rdfa-java-rdfa-parent-1.0.0-BETA1/rdfa-module/src/main/java/net/rootdev/javardfa/literal /*
* (c) Copyright 2010 University of Bristol
* All rights reserved.
* [See end of file]
*/
package net.rootdev.javardfa.literal;
import java.io.StringWriter;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Stack;
import javax.xml.XMLConstants;
import javax.xml.stream.XMLEventFactory;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;
import net.rootdev.javardfa.Parser;
import net.rootdev.javardfa.Setting;
/**
*
* @author pldms
*/
public class LiteralCollector {
final String XMLLiteral = "http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral";
private final Stack collectors;
private List queuedEvents;
private int level;
private final Parser parser;
private final StartElement fakeEnvelope;
private final XMLEventFactory eventFactory;
private final XMLOutputFactory outputFactory;
public LiteralCollector(Parser parser, XMLEventFactory eventFactory, XMLOutputFactory outputFactory) {
this.parser = parser;
this.collectors = new Stack();
this.queuedEvents = null;
this.eventFactory = eventFactory;
this.outputFactory = outputFactory;
this.fakeEnvelope = eventFactory.createStartElement(XMLConstants.DEFAULT_NS_PREFIX, XMLConstants.NULL_NS_URI, "fake");
}
public boolean isCollecting() { return !collectors.isEmpty(); }
public boolean isCollectingXML() {
if (!isCollecting()) return false;
return XMLLiteral.equals(collectors.peek().datatype);
}
public void collect(String subject, Collection props, String datatype, String lang) {
if (!isCollecting()) { // set up collection
queuedEvents = new LinkedList();
level = 0;
}
Collector coll = new Collector(subject, props, datatype, lang, level, queuedEvents.size());
collectors.push(coll);
}
public void handleEvent(XMLEvent event) {
if (!isCollecting()) return; // nothing to do
if (event.isStartElement()) handleStartEvent(event);
else if (event.isEndElement()) handleEndEvent(event);
else queuedEvents.add(event);
}
private void handleStartEvent(XMLEvent event) {
level++;
queuedEvents.add(event);
// In 1.0 if no explicit dt given dt determined by content
// i.e. if it contains tags we have an xml literal
if (!parser.isEnabled(Setting.OnePointOne) &&
collectors.peek().datatype == null) { // undecided so far
collectors.peek().datatype = XMLLiteral;
}
}
private void handleEndEvent(XMLEvent event) {
queuedEvents.add(event);
if (collectors.peek().level == level) {
Collector coll = collectors.pop();
emitTriples(coll, queuedEvents.subList(coll.start, queuedEvents.size()));
}
level--;
}
private void emitTriples(Collector coll, List subList) {
String lex = (XMLLiteral.equals(coll.datatype)) ?
gatherXML(subList, coll.lang) :
gatherText(subList) ;
if ((coll.datatype != null) && !"".equals(coll.datatype)) // not plain
parser.emitTriplesDatatypeLiteral(coll.subject,
coll.props, lex, coll.datatype);
else
parser.emitTriplesPlainLiteral(coll.subject,
coll.props, lex, coll.lang);
}
private String gatherXML(List subList, String lang) {
try {
return gatherXMLEx(subList, lang);
} catch (XMLStreamException ex) {
throw new RuntimeException("Problem gathering XML", ex);
}
}
private String gatherXMLEx(List subList, String lang)
throws XMLStreamException {
Attribute xmlLang = (lang == null) ?
null :
eventFactory.createAttribute("xml:lang", lang);
StringWriter sw = new StringWriter();
XMLStreamWriter out = outputFactory.createXMLStreamWriter(sw);
XMLEventWriter xmlWriter = new CanonicalXMLEventWriter(out, xmlLang);
xmlWriter.add(fakeEnvelope); // Some libraries dislike xml fragements
for (XMLEvent e: subList) {
xmlWriter.add(e);
}
xmlWriter.flush();
String xml = sw.toString();
int start = xml.indexOf('>') + 1;
int end = xml.lastIndexOf('<');
return xml.substring(start, end); // remove
}
private String gatherText(List subList) {
StringBuilder sb = new StringBuilder();
for (XMLEvent e: subList) {
if (e.isCharacters()) sb.append(e.asCharacters().getData());
}
return sb.toString();
}
final static class Collector {
private final String subject;
private final Collection props;
private String datatype;
private final String lang;
private final int level;
private final int start;
private Collector(String subject, Collection props, String datatype,
String lang, int level, int start) {
this.subject = subject;
this.props = props;
this.datatype = datatype;
this.lang = lang;
this.level = level;
this.start = start;
}
}
}
/*
* (c) Copyright 2009 University of Bristol
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/ java-rdfa-java-rdfa-parent-1.0.0-BETA1/rdfa-module/src/main/java/net/rootdev/javardfa/output/ 0000775 0000000 0000000 00000000000 13761231531 0031500 5 ustar 00root root 0000000 0000000 NTripleSink.java 0000664 0000000 0000000 00000011141 13761231531 0034464 0 ustar 00root root 0000000 0000000 java-rdfa-java-rdfa-parent-1.0.0-BETA1/rdfa-module/src/main/java/net/rootdev/javardfa/output /*
* (c) Copyright 2009 University of Bristol
* All rights reserved.
* [See end of file]
*/
package net.rootdev.javardfa.output;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.regex.Pattern;
import net.rootdev.javardfa.StatementSink;
/**
* A pretty ropey NTriple serialiser.
* Advantages: streams, no dependencies.
*
* @author pldms
*/
public class NTripleSink implements StatementSink {
protected final PrintWriter out;
protected final String[] comments;
public NTripleSink(OutputStream os, String... comments) throws UnsupportedEncodingException {
this(new OutputStreamWriter(os, "US-ASCII"), comments); // N-Triples is 7-bit ascii
}
public NTripleSink(Writer writer, String... comments) {
this.out = new PrintWriter(writer);
this.comments = comments;
}
public void start() {
for (String line: comments) {
out.print("# ");
out.println(line);
}
}
public void end() {
out.flush();
}
public void addObject(String subject, String predicate, String object) {
out.print(toNode(subject));
out.print(toNode(predicate));
out.print(toNode(object));
out.println(".");
}
public void addLiteral(String subject, String predicate, String lex, String lang, String datatype) {
out.print(toNode(subject));
out.print(toNode(predicate));
out.print(toLiteral(lex, lang, datatype));
out.println(".");
}
public void addPrefix(String prefix, String uri) {}
protected final String toNode(String node) {
if (node.startsWith("_:") || node.startsWith("?"))
return node + " ";
return "<" + node + "> ";
}
protected final String toLiteral(String lex, String lang, String datatype) {
if (lang != null && lang.length() != 0)
return quote(lex) + "@" + lang + " ";
if (datatype != null)
return quote(lex) + "^^<" + datatype + "> ";
return quote(lex) + " ";
}
private Pattern quotePattern = Pattern.compile("\"");
protected final String quote(String lex) {
return "\"" + encode(lex) + "\"";
}
protected final String encode(String s) {
StringBuilder b = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
int c = s.codePointAt(i);
if (c <= 8) b.append(enc(c));
else if (c == '\t') b.append("\\t");
else if (c == '\n') b.append("\\n");
else if (c == '\r') b.append("\\r");
else if (c == '"') b.append("\\\"");
else if (c == '\\') b.append("\\\\");
else if (c <= 127) b.appendCodePoint(c);
else if (c <= 0xFFFF) b.append(enc(c));
else b.append(longenc(c));
}
return b.toString();
}
protected String enc(int codepoint) {
return String.format("\\u%04x", codepoint);
}
protected String longenc(int codepoint) {
return String.format("\\U%08x", codepoint);
}
public void setBase(String base) {}
}
/*
* (c) Copyright 2009 University of Bristol
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/ OGPReader.java 0000664 0000000 0000000 00000007015 13761231531 0034037 0 ustar 00root root 0000000 0000000 java-rdfa-java-rdfa-parent-1.0.0-BETA1/rdfa-module/src/main/java/net/rootdev/javardfa/output /*
* (c) Copyright 2010 University of Bristol
* All rights reserved.
* [See end of file]
*/
package net.rootdev.javardfa.output;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import net.rootdev.javardfa.ParserFactory;
import net.rootdev.javardfa.ParserFactory.Format;
import net.rootdev.javardfa.StatementSink;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
/**
*
* @author pldms
*/
public class OGPReader implements StatementSink {
static final String NS = "http://opengraphprotocol.org/schema/";
static final int NSlen = NS.length();
private String base;
private final Map content = new HashMap();
public void start() {}
public void end() {}
public void addObject(String subject, String predicate, String object) {
collect(subject, predicate, object);
}
public void addLiteral(String subject, String predicate, String lex, String lang, String datatype) {
collect(subject, predicate, lex);
}
public void addPrefix(String prefix, String uri) {}
public void setBase(String base) {
this.base = base;
}
private void collect(String subject, String predicate, String value) {
if (!subject.equals(base)) return;
if (predicate.startsWith(NS)) content.put(predicate.substring(NSlen), value);
else content.put(predicate, value);
}
public Map getContent() { return content; }
/**
* A rudimentary Open Graph Protocol parser
* @param url Source to parse
* @param format HTML or XHTML
* @return Map from key to value. For OGP properties the key is simple (e.g. email)
* @throws SAXException
* @throws IOException
*/
public static Map getOGP(String url, Format format) throws SAXException, IOException {
OGPReader reader = new OGPReader();
XMLReader parser = ParserFactory.createReaderForFormat(reader, format);
parser.parse(new InputSource(url));
return reader.getContent();
}
}
/*
* (c) Copyright 2010 University of Bristol
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/ RDFXMLSink.java 0000664 0000000 0000000 00000016113 13761231531 0034107 0 ustar 00root root 0000000 0000000 java-rdfa-java-rdfa-parent-1.0.0-BETA1/rdfa-module/src/main/java/net/rootdev/javardfa/output /*
* (c) Copyright 2009 University of Bristol
* All rights reserved.
* [See end of file]
*/
package net.rootdev.javardfa.output;
import java.io.OutputStream;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import net.rootdev.javardfa.StatementSink;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A pretty ropey RDF/XML serialiser.
* Advantages: streams, no dependencies.
*
* @author pldms
*/
public class RDFXMLSink implements StatementSink {
final static Logger log = LoggerFactory.getLogger(RDFXMLSink.class);
final static String RDFNS = "http://www.w3.org/1999/02/22-rdf-syntax-ns#";
private final XMLStreamWriter out;
private final String[] comments;
public RDFXMLSink(OutputStream os, String... comments) {
this.comments = comments;
XMLOutputFactory factory = XMLOutputFactory.newInstance();
factory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true);
try {
out = factory.createXMLStreamWriter(os, "utf-8");
} catch (XMLStreamException ex) {
throw new RuntimeException("Couldn't create writer", ex);
}
}
public void start() {
try {
out.writeStartDocument("utf-8", "1.0");
if (comments.length != 0) {
out.writeCharacters("\n");
StringBuilder sb = new StringBuilder("\n");
for (String line: comments) { sb.append(line); sb.append("\n"); }
out.writeComment(sb.toString());
}
out.writeCharacters("\n");
out.writeStartElement(RDFNS, "RDF");
out.writeNamespace("rdf", RDFNS);
out.writeCharacters("\n");
} catch (XMLStreamException ex) {
throw new RuntimeException("Problem starting document", ex);
}
}
public void end() {
try {
out.writeEndDocument();
out.flush();
out.close();
} catch (XMLStreamException ex) {
throw new RuntimeException("Problem ending document", ex);
}
}
public void addObject(String subject, String predicate, String object) {
try {
out.writeStartElement(RDFNS, "Description");
writeSubject(subject);
out.writeCharacters("\n\t");
writePredicate(predicate, true); // closed
writeObject(object);
out.writeCharacters("\n");
out.writeEndElement();
out.writeCharacters("\n");
} catch (XMLStreamException ex) {
throw new RuntimeException("Problem writing statement", ex);
}
}
public void addLiteral(String subject, String predicate, String lex, String lang, String datatype) {
try {
out.writeStartElement(RDFNS, "Description");
writeSubject(subject);
out.writeCharacters("\n\t");
writePredicate(predicate, false); // not closed
writeLiteral(lex, lang, datatype);
out.writeEndElement();
out.writeCharacters("\n");
out.writeEndElement();
out.writeCharacters("\n");
} catch (XMLStreamException ex) {
throw new RuntimeException("Problem writing statement", ex);
}
}
public void addPrefix(String prefix, String uri) {
}
private void writeSubject(String subject) throws XMLStreamException {
if (blank(subject))
out.writeAttribute(RDFNS, "nodeID", id(subject));
else
out.writeAttribute(RDFNS, "about", subject);
}
private void writePredicate(String predicate, boolean closed) throws XMLStreamException {
String[] nsln = split(predicate);
if (closed)
out.writeEmptyElement("ns", nsln[1], nsln[0]);
else
out.writeStartElement("ns", nsln[1], nsln[0]);
out.writeNamespace("ns", nsln[0]);
}
private void writeObject(String object) throws XMLStreamException {
if (blank(object))
out.writeAttribute(RDFNS, "nodeID", id(object));
else
out.writeAttribute(RDFNS, "resource", object);
}
private void writeLiteral(String lex, String lang, String datatype) throws XMLStreamException {
if (lang != null)
out.writeAttribute("xml:lang", lang);
else if (datatype != null)
out.writeAttribute(RDFNS, "datatype", datatype);
out.writeCharacters(lex);
}
private boolean blank(String subject) {
return subject.startsWith("_:");
}
private String id(String subject) {
return subject.substring(2);
}
protected String[] split(String predicate) {
String[] toReturn = new String[2];
int i = predicate.length() - 1;
int lastStartChar = -1;
while (i > 0 && isNameChar(predicate.codePointAt(i))) {
if (isNameStartChar(predicate.codePointAt(i)))
lastStartChar = i;
i--;
}
if (lastStartChar == -1)
throw new RuntimeException("Unsplitable predicate " + predicate);
toReturn[0] = predicate.substring(0, lastStartChar);
toReturn[1] = predicate.substring(lastStartChar);
return toReturn;
}
private boolean isNameChar(int cp) {
return isNameStartChar(cp) ||
(cp == '.') ||
(cp == '-') ||
(cp >= '0' && cp <= '9');
}
private boolean isNameStartChar(int cp) {
return (cp >= 'a' && cp <= 'z') ||
(cp >= 'A' && cp <= 'Z') ||
cp == ':' ||
cp == '_';
}
public void setBase(String base) {}
}
/*
* (c) Copyright 2009 University of Bristol
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/ TurtleSink.java 0000664 0000000 0000000 00000007507 13761231531 0034401 0 ustar 00root root 0000000 0000000 java-rdfa-java-rdfa-parent-1.0.0-BETA1/rdfa-module/src/main/java/net/rootdev/javardfa/output /*
* (c) Copyright 2010 University of Bristol
* All rights reserved.
* [See end of file]
*/
package net.rootdev.javardfa.output;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
/**
* A pretty ropey turtle serialiser.
* Advantages: streams, no dependencies.
*
* @author pldms
*/
public class TurtleSink extends NTripleSink {
private String currentSubject = null;
private String currentPredicate = null;
public TurtleSink(OutputStream os, String... comments) throws UnsupportedEncodingException {
super(new OutputStreamWriter(os, "UTF-8"), comments);
}
public TurtleSink(Writer writer, String... comments) {
super(writer, comments);
}
@Override
public void end() {
out.println(".");
super.end();
}
@Override
public void addObject(String subject, String predicate, String object) {
emitTriple(subject, predicate, toNode(object));
}
@Override
public void addLiteral(String subject, String predicate, String lex, String lang, String datatype) {
emitTriple(subject, predicate, toLiteral(lex, lang, datatype));
}
private void emitTriple(String subject, String predicate, String objectEncoded) {
if (subject.equals(currentSubject)) { // We can at least ';'
if (predicate.equals(currentPredicate)) { // We can ','
out.println(",");
out.print("\t\t");
out.print(objectEncoded);
} else {
out.println(";");
out.print("\t");
out.println(toNode(predicate));
out.print("\t\t");
out.print(objectEncoded);
currentPredicate = predicate;
}
} else {
if (currentSubject != null) out.println(".");
out.println(toNode(subject));
out.print("\t");
out.println(toNode(predicate));
out.print("\t\t");
out.print(objectEncoded);
currentPredicate = predicate;
currentSubject = subject;
}
}
@Override
protected final String enc(int codepoint) {
return new String( new int[] {codepoint},0,1);
}
@Override
protected final String longenc(int codepoint) {
return new String( new int[] {codepoint},0,1);
}
}
/*
* (c) Copyright 2009 University of Bristol
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/ java-rdfa-java-rdfa-parent-1.0.0-BETA1/rdfa-module/src/main/java/net/rootdev/javardfa/query/ 0000775 0000000 0000000 00000000000 13761231531 0031305 5 ustar 00root root 0000000 0000000 QueryCollector.java 0000664 0000000 0000000 00000014246 13761231531 0035054 0 ustar 00root root 0000000 0000000 java-rdfa-java-rdfa-parent-1.0.0-BETA1/rdfa-module/src/main/java/net/rootdev/javardfa/query /*
* (c) Copyright 2009 University of Bristol
* All rights reserved.
* [See end of file]
*/
package net.rootdev.javardfa.query;
import org.apache.jena.datatypes.TypeMapper;
import org.apache.jena.graph.BlankNodeId;
import org.apache.jena.graph.Node;
import org.apache.jena.graph.NodeFactory;
import org.apache.jena.graph.Triple;
import org.apache.jena.query.Query;
import org.apache.jena.rdf.model.AnonId;
import org.apache.jena.sparql.core.BasicPattern;
import org.apache.jena.sparql.core.Var;
import org.apache.jena.sparql.syntax.Element;
import org.apache.jena.sparql.syntax.ElementGroup;
import org.apache.jena.sparql.syntax.ElementNamedGraph;
import org.apache.jena.sparql.syntax.Template;
import org.apache.jena.vocabulary.RDF;
import java.util.*;
import java.util.Map.Entry;
import net.rootdev.javardfa.StatementSink;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class QueryCollector implements StatementSink {
final static Logger log = LoggerFactory.getLogger(QueryCollector.class);
private static final Node FormType = NodeFactory.createURI("http://www.w3.org/1999/xhtml/vocab/#form");
private static final TypeMapper TMapper = TypeMapper.getInstance();
private final Map queries;
private List currentQuery;
private String currentQueryName;
private final Map prefixMapping;
public QueryCollector() {
queries = new HashMap();
prefixMapping = new HashMap();
}
public Map getQueries() {
return Collections.unmodifiableMap(queries);
}
public void addLiteral(String arg0, String arg1, String arg2, String arg3,
String arg4) {
//log.info("Add literal");
Node subject = getNode(arg0);
Node predicate = getNode(arg1);
Node object = getLiteralNode(arg2, arg3, arg4);
addTriple(subject, predicate, object);
}
public void addObject(String arg0, String arg1, String arg2) {
//log.info("Add object");
Node subject = getNode(arg0);
Node predicate = getNode(arg1);
Node object = getNode(arg2);
addTriple(subject, predicate, object);
}
private void addTriple(Node subject, Node predicate, Node object) {
//log.info("Adding triple: " + subject + " " + predicate + " " + object);
if (RDF.type.asNode().equals(predicate) &&
FormType.equals(object)) {
if (currentQueryName != null) {
queries.put(currentQueryName, createQuery(currentQuery));
}
currentQueryName = subject.getURI();
currentQuery = new LinkedList();
return;
}
if (currentQueryName == null) {
return; // good idea? not sure...
}
currentQuery.add(Triple.create(subject, predicate, object));
}
private Node getLiteralNode(String arg2, String arg3, String arg4) {
if (arg3 == null && arg4 == null) {
return NodeFactory.createLiteral(arg2);
} else if (arg4 == null) { // has lang
return NodeFactory.createLiteral(arg2, arg3, false);
} else { // has datatype
return NodeFactory.createLiteral(arg2, null, TMapper.getSafeTypeByName(arg4));
}
}
private Node getNode(String arg0) {
if (arg0.startsWith("_:")) // BNode
{
return NodeFactory.createBlankNode(BlankNodeId.create(arg0.substring(2)));
}
if (arg0.startsWith("?")) // Var
{
return Var.alloc(arg0.substring(1));
} else {
return NodeFactory.createURI(arg0);
}
}
public void end() {
if (currentQueryName != null) {
queries.put(currentQueryName, createQuery(currentQuery));
}
}
public void start() {
}
public Query createQuery(List triples) {
log.info("Create query");
Query query = new Query();
ElementGroup body = new ElementGroup();
for (Triple t : triples) {
body.addTriplePattern(t);
}
// TODO make this switchable.
Element pattern = new ElementNamedGraph(Var.alloc("graph"), body);
query.setQueryPattern(pattern);
query.addProjectVars(Collections.singleton("s"));
//query.setQuerySelectType();
Template templ = new Template(BasicPattern.wrap(triples));
query.setQuerySelectType();
query.setQueryResultStar(true);
query.setConstructTemplate(templ);
for (Entry e: prefixMapping.entrySet())
query.setPrefix(e.getKey(), e.getValue());
return query;
}
public void addPrefix(String prefix, String uri) {
prefixMapping.put(prefix, uri);
}
public void setBase(String base) {}
}
/*
* (c) Copyright 2009 University of Bristol
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/ QueryUtilities.java 0000664 0000000 0000000 00000013542 13761231531 0035077 0 ustar 00root root 0000000 0000000 java-rdfa-java-rdfa-parent-1.0.0-BETA1/rdfa-module/src/main/java/net/rootdev/javardfa/query /*
* (c) Copyright 2009 University of Bristol
* All rights reserved.
* [See end of file]
*/
package net.rootdev.javardfa.query;
import org.apache.jena.graph.Node;
import org.apache.jena.graph.Triple;
import org.apache.jena.query.Query;
import org.apache.jena.query.QueryExecution;
import org.apache.jena.query.QueryExecutionFactory;
import org.apache.jena.query.QuerySolution;
import org.apache.jena.query.QuerySolutionMap;
import org.apache.jena.query.ResultSet;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.sparql.syntax.ElementTriplesBlock;
import org.apache.jena.sparql.syntax.ElementVisitorBase;
import org.apache.jena.sparql.syntax.ElementWalker;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import net.rootdev.javardfa.Parser;
import net.rootdev.javardfa.ParserFactory;
import net.rootdev.javardfa.ParserFactory.Format;
import net.rootdev.javardfa.Setting;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
/**
*
* Some useful functions concerning pages with variables
*
* @author pldms
*/
public class QueryUtilities {
final static Logger log = LoggerFactory.getLogger(QueryUtilities.class);
public final static QuerySolution NoResult = new QuerySolutionMap();
/**
* Grab simple (BGP) queries from an html document. Over named graphs currently.
*
* @param format document format
* @param source document id
* @return
*/
public static Map makeQueries(Format format, String source) throws SAXException, IOException {
QueryCollector qc = new QueryCollector();
XMLReader reader = ParserFactory.createReaderForFormat(qc, format);
((Parser) reader.getContentHandler()).enable(Setting.FormMode);
if (source.matches("file:/[^/][^/].*")) source = source.replaceFirst("file:/", "file:///");
reader.parse(source);
return qc.getQueries();
}
// TODO: currently this won't work! Need to add to a named graph
/**
* Simple method to help rebinding data to form. Currently too simple.
* @param model Contains data to rebind
* @param query Extracted from the form above
* @return Name / node bindings
*/
public static QuerySolution extractBinding(Model model, Query query) {
QueryExecution qe = QueryExecutionFactory.create(query, model);
ResultSet res = qe.execSelect();
final QuerySolution toReturn = (res.hasNext()) ?
res.next() : NoResult; // I will never use null again
if (res.hasNext()) log.warn("More than one available binding");
qe.close();
return toReturn;
}
/**
* Given some bindings and a form create a model. Intended use is handling
* the result of form submission.
*
* @param query The form
* @param bindings Submitted bindings
* @return Bindings applied to the query
*/
public static Model bind(Query query, Map bindings) {
List triples = pullTriples(query);
List boundTriples = new LinkedList();
Model model = ModelFactory.createDefaultModel();
for (Triple t: triples) {
Node s = bind(t.getSubject(), bindings);
Node p = bind(t.getPredicate(), bindings);
Node o = bind(t.getObject(), bindings);
Triple nt = Triple.create(s, p, o);
model.add(model.asStatement(nt));
}
return model;
}
/**
* Collect all triples from a query body
* @param query
* @return
*/
private static List pullTriples(Query query) {
List triples = new LinkedList();
ElementWalker.walk(query.getQueryPattern(), new TripleCollector(triples));
return triples;
}
private static Node bind(Node object, Map bindings) {
throw new UnsupportedOperationException("Not yet implemented");
}
private static class TripleCollector extends ElementVisitorBase {
private final List triples;
private TripleCollector(List triples) {
this.triples = triples;
}
@Override
public void visit(ElementTriplesBlock el) {
triples.addAll(el.getPattern().getList());
}
}
}
/*
* (c) Copyright 2009 University of Bristol
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
java-rdfa-java-rdfa-parent-1.0.0-BETA1/rdfa-module/src/main/java/net/rootdev/javardfa/uri/ 0000775 0000000 0000000 00000000000 13761231531 0030737 5 ustar 00root root 0000000 0000000 IRIResolver.java 0000664 0000000 0000000 00000004554 13761231531 0033700 0 ustar 00root root 0000000 0000000 java-rdfa-java-rdfa-parent-1.0.0-BETA1/rdfa-module/src/main/java/net/rootdev/javardfa/uri /*
* (c) Copyright 2009 University of Bristol
* All rights reserved.
* [See end of file]
*/
package net.rootdev.javardfa.uri;
import org.apache.jena.iri.IRI;
import org.apache.jena.iri.IRIFactory;
import net.rootdev.javardfa.Resolver;
/**
* Resolver that uses the IRI library.
* This is the recommended resolver.
*
* @author pldms
*/
public class IRIResolver implements Resolver {
private final IRIFactory iriFactory;
/**
* Create a semantic web version
*/
public IRIResolver() {
this(IRIFactory.semanticWebImplementation());
}
public IRIResolver(IRIFactory iriFactory) {
this.iriFactory = iriFactory;
}
public String resolve(String first, String second) {
if (first == null) throw new RuntimeException("Base is null.");
IRI iri = iriFactory.construct(first);
IRI resolved = iri.resolve(second);
return resolved.toString();
}
}
/*
* (c) Copyright 2009 University of Bristol
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
URIExtractor.java 0000664 0000000 0000000 00000004552 13761231531 0034064 0 ustar 00root root 0000000 0000000 java-rdfa-java-rdfa-parent-1.0.0-BETA1/rdfa-module/src/main/java/net/rootdev/javardfa/uri /*
* (c) Copyright 2010 University of Bristol
* All rights reserved.
* [See end of file]
*/
package net.rootdev.javardfa.uri;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import javax.xml.namespace.QName;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.StartElement;
import net.rootdev.javardfa.EvalContext;
import net.rootdev.javardfa.Setting;
/**
*
* @author pldms
*/
public interface URIExtractor {
// Represents a missing URI.
// We can distinguish between a missing attribute and missing URI
final static String NONE = "__NONE__";
void setSettings(Set settings);
String getURI(StartElement element, QName attrName, EvalContext context);
List getURIs(StartElement element, QName attrName, EvalContext context);
String resolveURI(String uri, EvalContext context);
}
/*
* (c) Copyright 2010 University of Bristol
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/ URIExtractor10.java 0000664 0000000 0000000 00000014037 13761231531 0034224 0 ustar 00root root 0000000 0000000 java-rdfa-java-rdfa-parent-1.0.0-BETA1/rdfa-module/src/main/java/net/rootdev/javardfa/uri /*
* (c) Copyright 2010 University of Bristol
* All rights reserved.
* [See end of file]
*/
package net.rootdev.javardfa.uri;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import javax.xml.namespace.QName;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.StartElement;
import net.rootdev.javardfa.Constants;
import net.rootdev.javardfa.EvalContext;
import net.rootdev.javardfa.Resolver;
import net.rootdev.javardfa.Setting;
/**
* This uses the RDFa 1.0 URI logic
*
* @author pldms
*/
public class URIExtractor10 implements URIExtractor {
private Set settings;
private final Resolver resolver;
public URIExtractor10(Resolver resolver) {
this.resolver = resolver;
}
public void setSettings(Set settings) {
this.settings = settings;
}
public String getURI(StartElement element, QName attrName, EvalContext context) {
Attribute attr = element.getAttributeByName(attrName);
if (attr == null) return null;
if (attrName.equals(Constants.href) || attrName.equals(Constants.src)) // A URI
{
if (attr.getValue().length() == 0) {
return context.getBase();
} else {
return resolver.resolve(context.getBase(), attr.getValue());
}
}
if (attrName.equals(Constants.about) || attrName.equals(Constants.resource)) // Safe CURIE or URI
{
return expandSafeCURIE(element, attr.getValue(), context);
}
if (attrName.equals(Constants.datatype)) // A CURIE
{
String val = attr.getValue();
if (val.length() == 0) {
return "";
}
else {
return expandCURIE(element, attr.getValue(), context);
}
}
throw new RuntimeException("Unexpected attribute: " + attr);
}
public List getURIs(StartElement element, QName attrName, EvalContext context) {
Attribute attr = element.getAttributeByName(attrName);
if (attr == null) return null;
List uris = new LinkedList();
String[] curies = attr.getValue().split("\\s+");
boolean permitReserved = Constants.rel.equals(attr.getName()) ||
Constants.rev.equals(attr.getName());
for (String curie : curies) {
if (Constants.SpecialRels.contains(curie.toLowerCase())) {
if (permitReserved)
uris.add("http://www.w3.org/1999/xhtml/vocab#" + curie.toLowerCase());
} else {
String uri = expandCURIE(element, curie, context);
if (uri != null) {
uris.add(uri);
}
}
}
return uris;
}
public String expandCURIE(StartElement element, String value, EvalContext context) {
if (value.startsWith("_:")) {
if (!settings.contains(Setting.ManualNamespaces)) return value;
if (element.getNamespaceURI("_") == null) return value;
}
if (settings.contains(Setting.FormMode) && // variable
value.startsWith("?")) {
return value;
}
int offset = value.indexOf(":") + 1;
if (offset == 0) {
//throw new RuntimeException("Is this a curie? \"" + value + "\"");
return null;
}
String prefix = value.substring(0, offset - 1);
// Apparently these are not allowed to expand
if ("xml".equals(prefix) || "xmlns".equals(prefix)) return null;
String namespaceURI = prefix.length() == 0 ? "http://www.w3.org/1999/xhtml/vocab#" : element.getNamespaceURI(prefix);
if (namespaceURI == null) {
return null;
//throw new RuntimeException("Unknown prefix: " + prefix);
}
return namespaceURI + value.substring(offset);
}
public String expandSafeCURIE(StartElement element, String value, EvalContext context) {
if (value.startsWith("[") && value.endsWith("]")) {
return expandCURIE(element, value.substring(1, value.length() - 1), context);
} else {
if (value.length() == 0) {
return context.getBase();
}
if (settings.contains(Setting.FormMode) &&
value.startsWith("?")) {
return value;
}
return resolver.resolve(context.getBase(), value);
}
}
public String resolveURI(String uri, EvalContext context) {
return resolver.resolve(context.getBase(), uri);
}
}
/*
* (c) Copyright 2010 University of Bristol
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
URIExtractor11.java 0000664 0000000 0000000 00000013761 13761231531 0034230 0 ustar 00root root 0000000 0000000 java-rdfa-java-rdfa-parent-1.0.0-BETA1/rdfa-module/src/main/java/net/rootdev/javardfa/uri /*
* (c) Copyright 2010 University of Bristol
* All rights reserved.
* [See end of file]
*/
package net.rootdev.javardfa.uri;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import javax.xml.namespace.QName;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.StartElement;
import net.rootdev.javardfa.Constants;
import net.rootdev.javardfa.EvalContext;
import net.rootdev.javardfa.Resolver;
import net.rootdev.javardfa.Setting;
/**
* This uses the RDFa 1.1 URI logic
*
* @author pldms
*/
public class URIExtractor11 implements URIExtractor {
private Set settings;
private final Resolver resolver;
public URIExtractor11(Resolver resolver) {
this.resolver = resolver;
}
public void setSettings(Set settings) {
this.settings = settings;
}
public String getURI(StartElement element, QName attrName, EvalContext context) {
Attribute attr = element.getAttributeByName(attrName);
if (attr == null) return null;
if (attrName.equals(Constants.href) || attrName.equals(Constants.src)) // A URI
{
if (attr.getValue().length() == 0) return context.getBase();
else return resolver.resolve(context.getBase(), attr.getValue());
}
if (attrName.equals(Constants.about) || attrName.equals(Constants.resource)) // Safe CURIE or URI
{
return expandSafeCURIE(element, attr.getValue(), context);
}
if (attrName.equals(Constants.datatype)) // A CURIE
{
String val = attr.getValue();
if (val.length() == 0) {
return "";
}
else {
return expandCURIE(element, attr.getValue(), context);
}
}
throw new RuntimeException("Unexpected attribute: " + attr);
}
public List getURIs(StartElement element, QName attrName, EvalContext context) {
Attribute attr = element.getAttributeByName(attrName);
if (attr == null) return null;
List uris = new LinkedList();
String[] curies = attr.getValue().split("\\s+");
for (String curie : curies) {
String uri = expandCURIE(element, curie, context);
if (uri != null && uri != URIExtractor.NONE) {
uris.add(uri);
}
}
return uris;
}
public String expandCURIE(StartElement element, String value, EvalContext context) {
if (value.startsWith("_:")) {
if (!settings.contains(Setting.ManualNamespaces)) return value;
if (context.getPrefix("_") == null) return value;
}
if (settings.contains(Setting.FormMode) && // variable
value.startsWith("?")) {
return value;
}
int offset = value.indexOf(":") + 1;
if (offset == 0) {
if (context.getURIForTerm(value) != null) return context.getURIForTerm(value);
String vocab = context.getVocab();
if (vocab != null) {
return vocab + value;
} else {
return URIExtractor.NONE;
}
}
String prefix = value.substring(0, offset - 1);
String namespaceURI = prefix.length() == 0 ? "http://www.w3.org/1999/xhtml/vocab#" : context.getURIForPrefix(prefix);
if (namespaceURI == null) {
// Assume this is some kind of URI
return value;
}
return namespaceURI + value.substring(offset);
}
public String expandSafeCURIE(StartElement element, String value, EvalContext context) {
if (value.startsWith("[") && value.endsWith("]")) {
return expandCURIE(element, value.substring(1, value.length() - 1), context);
} else {
String epd = expandCURIE(element, value, context);
if (epd != null && epd != URIExtractor.NONE && !value.equals(epd)) {
return epd;
}
//System.err.printf("Expandable? %s [%s,%s]\n", value.equals(epd), epd, value);
if (value.length() == 0) {
return context.getBase();
}
if (settings.contains(Setting.FormMode) &&
value.startsWith("?")) {
return value;
}
return resolver.resolve(context.getBase(), value);
}
}
public String resolveURI(String uri, EvalContext context) {
return resolver.resolve(context.getBase(), uri);
}
}
/*
* (c) Copyright 2010 University of Bristol
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
URIResolver.java 0000664 0000000 0000000 00000004370 13761231531 0033710 0 ustar 00root root 0000000 0000000 java-rdfa-java-rdfa-parent-1.0.0-BETA1/rdfa-module/src/main/java/net/rootdev/javardfa/uri /*
* (c) Copyright 2009 University of Bristol
* All rights reserved.
* [See end of file]
*/
package net.rootdev.javardfa.uri;
import java.net.URI;
import java.net.URISyntaxException;
import net.rootdev.javardfa.Resolver;
/**
* Resolver that uses java's URI library.
* The IRI resolver is strongly recommended over this.
*
* @author pldms
*/
public class URIResolver implements Resolver {
public URIResolver() { }
public String resolve(String first, String second) {
try {
URI uri = new URI(first);
return uri.resolve(second).toString();
} catch (URISyntaxException ex) {
// TODO Is this a good idea???
return null;
} catch (IllegalArgumentException ex) {
// See above
return null;
}
}
}
/*
* (c) Copyright 2009 University of Bristol
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
java-rdfa-java-rdfa-parent-1.0.0-BETA1/rdfa-module/src/main/java/rdfa/ 0000775 0000000 0000000 00000000000 13761231531 0025026 5 ustar 00root root 0000000 0000000 java-rdfa-java-rdfa-parent-1.0.0-BETA1/rdfa-module/src/main/java/rdfa/parse.java 0000664 0000000 0000000 00000006236 13761231531 0027012 0 ustar 00root root 0000000 0000000 /*
* (c) Copyright 2009 University of Bristol
* All rights reserved.
* [See end of file]
*/
package rdfa;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.util.FileManager;
import java.io.InputStream;
import java.util.LinkedList;
import java.util.List;
import net.rootdev.javardfa.Version;
/**
* Simple command line tool. Uses Jena, and doesn't stream, so output
* is much nicer than simpleparse.
*
* @author pldms
*/
public class parse {
public static void main(String... args) throws ClassNotFoundException {
if (args.length == 0) usage();
if ("--version".equals(args[0]) || "-v".equals(args[0])) version();
// Ensure hooks run
Class.forName("net.rootdev.javardfa.RDFaReader");
String format = "XHTML";
boolean getFormat = false;
List uris = new LinkedList();
for (String arg: args) {
if (getFormat) { format = arg; getFormat = false; }
else if ("--help".equalsIgnoreCase(arg)) usage();
else if ("--format".equalsIgnoreCase(arg)) getFormat = true;
else uris.add(arg);
}
if (getFormat) usage();
Model m = ModelFactory.createDefaultModel();
FileManager fm = FileManager.get();
for (String uri: uris) {
InputStream in = fm.open(uri);
m.read(in, uri, format);
}
m.write(System.out, "TTL");
}
private static void usage() {
System.err.println("rdfa.parse [--version] [--format XHTML|HTML] [...]");
System.exit(0);
}
private static void version() {
System.err.println(Version.get());
System.exit(0);
}
}
/*
* (c) Copyright 2009 University of Bristol
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
java-rdfa-java-rdfa-parent-1.0.0-BETA1/rdfa-module/src/main/java/rdfa/simpleparse.java 0000664 0000000 0000000 00000006637 13761231531 0030231 0 ustar 00root root 0000000 0000000 /*
* (c) Copyright 2009 University of Bristol
* All rights reserved.
* [See end of file]
*/
package rdfa;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.LinkedList;
import java.util.List;
import net.rootdev.javardfa.ParserFactory;
import net.rootdev.javardfa.ParserFactory.Format;
import net.rootdev.javardfa.StatementSink;
import net.rootdev.javardfa.output.TurtleSink;
import net.rootdev.javardfa.uri.URIResolver;
import net.rootdev.javardfa.Version;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
/**
* Simple command line tool
*
* @author pldms
*/
public class simpleparse {
public static void main(String... args) throws ClassNotFoundException, MalformedURLException, IOException, SAXException {
if (args.length == 0) usage();
if ("--version".equals(args[0]) || "-v".equals(args[0])) version();
Format format = Format.XHTML;
boolean getFormat = false;
List uris = new LinkedList();
for (String arg: args) {
if (getFormat) { format = Format.lookup(arg); getFormat = false; }
else if ("--help".equalsIgnoreCase(arg)) usage();
else if ("--format".equalsIgnoreCase(arg)) getFormat = true;
else uris.add(arg);
}
if (format == null) unknownFormat();
if (getFormat) usage();
for (String uri: uris) {
StatementSink sink = new TurtleSink(System.out);
XMLReader reader = ParserFactory.createReaderForFormat(sink, format, new URIResolver());
reader.parse(uri);
}
}
private static void usage() {
System.err.println("rdfa.simpleparse [--version] [--format XHTML|HTML] [...]");
System.exit(0);
}
private static void version() {
System.err.println(Version.get());
System.exit(0);
}
private static void unknownFormat() {
System.err.println("Unknown format");
usage();
}
}
/*
* (c) Copyright 2009 University of Bristol
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
java-rdfa-java-rdfa-parent-1.0.0-BETA1/rdfa-module/src/main/resources/ 0000775 0000000 0000000 00000000000 13761231531 0025203 5 ustar 00root root 0000000 0000000 java-rdfa-java-rdfa-parent-1.0.0-BETA1/rdfa-module/src/main/resources/library.properties 0000664 0000000 0000000 00000000176 13761231531 0030771 0 ustar 00root root 0000000 0000000 # This is used to get the version at build time
# Used by Version.java
library.name=${pom.name}
library.version=${pom.version} java-rdfa-java-rdfa-parent-1.0.0-BETA1/rdfa-module/src/main/resources/location-mapping.n3 0000664 0000000 0000000 00000001154 13761231531 0030707 0 ustar 00root root 0000000 0000000 @prefix lm: .
[] lm:mapping
[ lm:prefix
"http://rdfa.digitalbazaar.com/test-suite/test-cases/xhtml1/" ;
lm:altPrefix
"file:conformance/xhtml/"
] ,
[ lm:prefix
"http://rdfa.digitalbazaar.com/test-suite/test-cases/html5/" ;
lm:altPrefix
"file:conformance/html5/"
] ,
[ lm:prefix
"http://rdfa.digitalbazaar.com/test-suite/test-cases/html4/" ;
lm:altPrefix
"file:conformance/html4/"
] ,
[
lm:name "http://philip.html5.org/demos/rdfa/tests.json" ;
lm:altName "file:tests.json"
]
. java-rdfa-java-rdfa-parent-1.0.0-BETA1/rdfa-module/src/test/ 0000775 0000000 0000000 00000000000 13761231531 0023224 5 ustar 00root root 0000000 0000000 java-rdfa-java-rdfa-parent-1.0.0-BETA1/rdfa-module/src/test/java/ 0000775 0000000 0000000 00000000000 13761231531 0024145 5 ustar 00root root 0000000 0000000 java-rdfa-java-rdfa-parent-1.0.0-BETA1/rdfa-module/src/test/java/net/ 0000775 0000000 0000000 00000000000 13761231531 0024733 5 ustar 00root root 0000000 0000000 java-rdfa-java-rdfa-parent-1.0.0-BETA1/rdfa-module/src/test/java/net/rootdev/ 0000775 0000000 0000000 00000000000 13761231531 0026415 5 ustar 00root root 0000000 0000000 java-rdfa-java-rdfa-parent-1.0.0-BETA1/rdfa-module/src/test/java/net/rootdev/javardfa/ 0000775 0000000 0000000 00000000000 13761231531 0030173 5 ustar 00root root 0000000 0000000 FileBasedTests.java 0000664 0000000 0000000 00000013427 13761231531 0033627 0 ustar 00root root 0000000 0000000 java-rdfa-java-rdfa-parent-1.0.0-BETA1/rdfa-module/src/test/java/net/rootdev/javardfa /*
* (c) Copyright 2009 University of Bristol
* All rights reserved.
* [See end of file]
*/
package net.rootdev.javardfa;
import org.apache.jena.query.Query;
import org.apache.jena.query.QueryFactory;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.sparql.algebra.Algebra;
import org.apache.jena.util.FileManager;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import net.rootdev.javardfa.ParserFactory.Format;
import net.rootdev.javardfa.jena.JenaStatementSink;
import net.rootdev.javardfa.query.QueryUtilities;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
/**
* @author Damian Steer
*/
@RunWith(Parameterized.class)
public class FileBasedTests {
static final String BASE = "/query-tests/";
@Parameters
public static Collection testFiles()
throws URISyntaxException, IOException {
InputStream stream = FileBasedTests.class.getClassLoader().getResourceAsStream("test-manifest");
if (stream == null) {
throw new Error("Couldn't find test-manifest");
}
BufferedReader reader =
new BufferedReader(new InputStreamReader(stream, "UTF-8"));
Collection filePairs = new ArrayList();
String nextLine;
while ((nextLine = reader.readLine()) != null) {
if (nextLine.startsWith("#")) continue;
filePairs.add(nextLine.split("\\s+"));
}
return filePairs;
}
private final String htmlFile;
private final String compareFile;
private final XMLInputFactory xmlFactory;
public FileBasedTests(String htmlFile, String compareFile) {
this.htmlFile = BASE + htmlFile;
this.compareFile = BASE + compareFile;
xmlFactory = XMLInputFactory.newInstance();
}
@Test
public void compare() throws XMLStreamException, IOException, ParserConfigurationException, SAXException {
URL htmlURL = this.getClass().getResource(htmlFile);
URL compareURL = this.getClass().getResource(compareFile);
if (compareFile.endsWith(".rq")) compareQuery(htmlURL, compareURL);
else compareRDF(htmlURL, compareURL);
}
private void compareRDF(URL htmlURL, URL compareURL) throws SAXException, IOException {
String cf = compareURL.toExternalForm();
if (cf.matches("file:/[^/][^/].*")) cf = cf.replaceFirst("file:/", "file:///");
String hf = htmlURL.toExternalForm();
if (hf.matches("file:/[^/][^/].*")) hf = hf.replaceFirst("file:/", "file:///");
Model c = FileManager.get().loadModel(compareURL.toExternalForm());
Model m = ModelFactory.createDefaultModel();
StatementSink sink = new JenaStatementSink(m);
XMLReader parser = ParserFactory.createReaderForFormat(sink, Format.XHTML, Setting.OnePointOne);
parser.parse(hf);
boolean result = c.isIsomorphicWith(m);
if (!result) {
System.err.println("===== "+htmlURL+" =====");
m.write(System.err, "TTL");
System.err.println("===== "+compareURL+" =====");
c.write(System.err, "TTL");
}
assertTrue("Files match (" + htmlURL + ")", result);
}
private void compareQuery(URL htmlURL, URL compareURL) throws SAXException, IOException {
Query query = QueryFactory.read(compareURL.toExternalForm());
Map qs = QueryUtilities.makeQueries(ParserFactory.Format.XHTML,
htmlURL.toExternalForm());
assertTrue("We have a query", qs.size() != 0);
Query qFromHTML = qs.get(qs.keySet().toArray()[0]);
assertEquals("Query matches (" + htmlURL + ")",
Algebra.compile(query),
Algebra.compile(qFromHTML));
}
}
/*
* (c) Copyright 2009 University of Bristol
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
java-rdfa-java-rdfa-parent-1.0.0-BETA1/rdfa-module/src/test/java/net/rootdev/javardfa/MiscTests.java0000664 0000000 0000000 00000004366 13761231531 0032765 0 ustar 00root root 0000000 0000000 /*
* (c) Copyright 2010 University of Bristol
* All rights reserved.
* [See end of file]
*/
package net.rootdev.javardfa;
import net.rootdev.javardfa.uri.URIResolver;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author pldms
*/
public class MiscTests {
@Test
public void CheckURIResolver() {
Resolver resolver = new URIResolver();
String url = "javascript:working_ajax('div_trailers_row_ID_0', '/trailers_pictures/photo_strip_ajax.php?media_type=trailers&skin=mob&type=2&id=1144763');";
try {
String resolved = resolver.resolve("http://example.com/", url);
assertNull(resolved);
} catch (Exception e) {
e.printStackTrace();
fail("resolver threw exception: " + e.getMessage());
}
}
}
/*
* (c) Copyright 2010 University of Bristol
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/ ParserTest.java 0000664 0000000 0000000 00000005062 13761231531 0033056 0 ustar 00root root 0000000 0000000 java-rdfa-java-rdfa-parent-1.0.0-BETA1/rdfa-module/src/test/java/net/rootdev/javardfa /*
* (c) Copyright 2010 University of Bristol
* All rights reserved.
* [See end of file]
*/
package net.rootdev.javardfa;
import net.rootdev.javardfa.jena.JenaStatementSink;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.Resource;
import net.rootdev.javardfa.ParserFactory.Format;
import org.junit.Test;
import static org.junit.Assert.*;
import org.xml.sax.XMLReader;
/**
* Note: most testing happens in conformance
* @author pldms
*/
public class ParserTest {
public ParserTest() {
}
/**
* This bit me. html5 parser sets systemId rather late.
*/
@Test
public void testBaseLocator() throws Exception {
Model m = ModelFactory.createDefaultModel();
StatementSink sink = new JenaStatementSink(m);
XMLReader parser = ParserFactory.createReaderForFormat(sink, Format.HTML);
parser.parse(this.getClass().getResource("/simple.html").toExternalForm());
Resource r = m.listSubjects().nextResource();
assertTrue("HTML 5 base correct", r.getURI().endsWith("simple.html"));
}
}
/*
* (c) Copyright 2010 University of Bristol
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/ QueryUtilitiesTest.java 0000664 0000000 0000000 00000006213 13761231531 0034622 0 ustar 00root root 0000000 0000000 java-rdfa-java-rdfa-parent-1.0.0-BETA1/rdfa-module/src/test/java/net/rootdev/javardfa /*
* (c) Copyright 2010 University of Bristol
* All rights reserved.
* [See end of file]
*/
package net.rootdev.javardfa;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.net.URL;
import java.util.Map;
import org.apache.jena.query.Query;
import org.apache.jena.query.QueryFactory;
import org.apache.jena.sparql.algebra.Algebra;
import org.apache.jena.sparql.sse.SSE;
import org.junit.Test;
import net.rootdev.javardfa.ParserFactory.Format;
import net.rootdev.javardfa.query.QueryUtilities;
/**
*
* @author pldms
*/
public class QueryUtilitiesTest {
public QueryUtilitiesTest() {
}
/**
* Test of makeQueries method, of class QueryUtilities.
*/
@Test
public void testMakeQueries() throws Exception {
Map q =
QueryUtilities.makeQueries(Format.XHTML,
this.getClass().getResource("/query-tests/1.html").toExternalForm());
assertEquals("Just the one query", 1, q.entrySet().size());
String qId = q.entrySet().iterator().next().getKey();
assertTrue("Got the right id for the query", qId.endsWith("/query-tests/1.html#1"));
//System.out.println("Query:");
SSE.write(Algebra.compile(q.get(qId)));
URL u = this.getClass().getResource("/query-tests/1.rq");
Query exp = QueryFactory.read(u.toExternalForm());
//System.out.println("QueryE:");
SSE.write(Algebra.compile(exp));
assertEquals("Got the right query", Algebra.compile(exp), Algebra.compile(q.get(qId)));
}
/**
* Test of extractBinding method, of class QueryUtilities.
*/
@Test
public void testExtractBinding() {
}
}
/*
* (c) Copyright 2010 University of Bristol
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/ java-rdfa-java-rdfa-parent-1.0.0-BETA1/rdfa-module/src/test/java/net/rootdev/javardfa/Scratch.java 0000664 0000000 0000000 00000005756 13761231531 0032442 0 ustar 00root root 0000000 0000000 /*
* (c) 2009
* Damian Steer
*/
package net.rootdev.javardfa;
import net.rootdev.javardfa.jena.JenaStatementSink;
import net.rootdev.javardfa.*;
import org.apache.jena.query.Query;
import org.apache.jena.query.QueryExecution;
import org.apache.jena.query.QueryExecutionFactory;
import org.apache.jena.query.QueryFactory;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.util.FileManager;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Map.Entry;
import javax.xml.stream.XMLInputFactory;
import net.rootdev.javardfa.ParserFactory.Format;
import net.rootdev.javardfa.output.OGPReader;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;
/**
*
* @author pldms
*/
public class Scratch {
private static XMLInputFactory xmlFactory = XMLInputFactory.newInstance();
public static void main(String[] args) throws SAXException, IOException, ClassNotFoundException {
Map prop = OGPReader.getOGP("http://uk.rottentomatoes.com/m/1217700-kick_ass", Format.HTML);
for (Entry ent: prop.entrySet()) {
System.err.printf("[%s] => '%s'\n", ent.getKey(), ent.getValue());
}
if (true) return;
String base = "http://rdfa.digitalbazaar.com/test-suite/test-cases/xhtml1/";
String testHTML = base + "0121.xhtml";
String testSPARQL = base + "0121.sparql";
check(testHTML, testSPARQL, Format.XHTML);
//XMLReader parser = ParserFactory.createReaderForFormat(new NTripleSink(System.out), Format.HTML);
//parser.parse(Scratch.class.getResource("/simple.html").toExternalForm());
/*Class.forName(RDFaReader.class.getName());
Model model = ModelFactory.createDefaultModel();
//model.read("http://www.ivan-herman.net/foaf.html", "HTML");
model.read("http://www.myspace.com/parishilton", "HTML");
System.err.println("== Read ==");
model.write(System.err, "TTL");*/
}
private static void check(String testHTML, String testSPARQL, Format format)
throws SAXException, IOException {
Model model = ModelFactory.createDefaultModel();
StatementSink sink = new JenaStatementSink(model);
InputStream in = FileManager.get().open(testHTML);
XMLReader reader = ParserFactory.createReaderForFormat(sink, format);
InputSource ins = new InputSource(in);
ins.setEncoding("utf-8");
ins.setSystemId(testHTML);
reader.parse(ins);
Query theQuery = QueryFactory.read(testSPARQL);
QueryExecution qe = QueryExecutionFactory.create(theQuery, model);
if (qe.execAsk()) {
System.err.println("It worked! " + testHTML);
return;
}
System.err.println("Failed: ");
model.write(System.err, "TTL");
System.err.println(theQuery);
}
}
VersionTest.java 0000664 0000000 0000000 00000004523 13761231531 0033250 0 ustar 00root root 0000000 0000000 java-rdfa-java-rdfa-parent-1.0.0-BETA1/rdfa-module/src/test/java/net/rootdev/javardfa /*
* (c) Copyright 2010 University of Bristol
* All rights reserved.
* [See end of file]
*/
package net.rootdev.javardfa;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author pldms
*/
public class VersionTest {
/**
* Test of get method, of class Version.
*/
@Test
public void testGet() {
assertNotNull(Version.get());
}
/**
* Test of getName method, of class Version.
*/
@Test
public void testGetName() {
assertEquals("java-rdfa", Version.get().getName());
}
/**
* Test of getVersion method, of class Version.
*/
@Test
public void testGetVersion() {
// Gah, can't usefully test this
}
/**
* Test of toString method, of class Version.
*/
@Test
public void testToString() {
assertTrue(Version.get().toString().matches("java-rdfa \\S+"));
}
}
/*
* (c) Copyright 2010 University of Bristol
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/ java-rdfa-java-rdfa-parent-1.0.0-BETA1/rdfa-module/src/test/java/net/rootdev/javardfa/conformance/ 0000775 0000000 0000000 00000000000 13761231531 0032465 5 ustar 00root root 0000000 0000000 HTML4.java 0000664 0000000 0000000 00000002774 13761231531 0034113 0 ustar 00root root 0000000 0000000 java-rdfa-java-rdfa-parent-1.0.0-BETA1/rdfa-module/src/test/java/net/rootdev/javardfa/conformance /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package net.rootdev.javardfa.conformance;
import org.apache.jena.rdf.model.Model;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Collection;
import java.util.Collections;
import net.rootdev.javardfa.jena.JenaStatementSink;
import net.rootdev.javardfa.ParserFactory;
import net.rootdev.javardfa.ParserFactory.Format;
import org.junit.runners.Parameterized.Parameters;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
/**
*
* @author pldms
*/
public class HTML4 extends RDFaConformance
{
@Parameters
public static Collection testFiles()
throws URISyntaxException, IOException {
if (false)
return Collections.EMPTY_LIST;
else
return RDFaConformance.
testFiles("http://rdfa.digitalbazaar.com/test-suite/test-cases/html4/html4-manifest.rdf",
"http://rdfa.digitalbazaar.com/test-suite/test-cases/html4/0121",
"http://rdfa.digitalbazaar.com/test-suite/test-cases/html4/0113"
);
}
public HTML4(String test, String title,
String purpose, String input, String query, String expected) {
super(test, title, purpose, input, query, expected);
}
@Override
public XMLReader getParser(Model model) throws SAXException {
return ParserFactory.createReaderForFormat(new JenaStatementSink(model), Format.HTML);
}
}
HTML5.java 0000664 0000000 0000000 00000002774 13761231531 0034114 0 ustar 00root root 0000000 0000000 java-rdfa-java-rdfa-parent-1.0.0-BETA1/rdfa-module/src/test/java/net/rootdev/javardfa/conformance /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package net.rootdev.javardfa.conformance;
import org.apache.jena.rdf.model.Model;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Collection;
import java.util.Collections;
import net.rootdev.javardfa.jena.JenaStatementSink;
import net.rootdev.javardfa.ParserFactory;
import net.rootdev.javardfa.ParserFactory.Format;
import org.junit.runners.Parameterized.Parameters;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
/**
*
* @author pldms
*/
public class HTML5 extends RDFaConformance
{
@Parameters
public static Collection testFiles()
throws URISyntaxException, IOException {
if (false)
return Collections.EMPTY_LIST;
else
return RDFaConformance.
testFiles("http://rdfa.digitalbazaar.com/test-suite/test-cases/html5/html5-manifest.rdf",
"http://rdfa.digitalbazaar.com/test-suite/test-cases/html5/0121",
"http://rdfa.digitalbazaar.com/test-suite/test-cases/html5/0113"
);
}
public HTML5(String test, String title,
String purpose, String input, String query, String expected) {
super(test, title, purpose, input, query, expected);
}
@Override
public XMLReader getParser(Model model) throws SAXException {
return ParserFactory.createReaderForFormat(new JenaStatementSink(model), Format.HTML);
}
}
RDFaConformance.java 0000664 0000000 0000000 00000014116 13761231531 0036203 0 ustar 00root root 0000000 0000000 java-rdfa-java-rdfa-parent-1.0.0-BETA1/rdfa-module/src/test/java/net/rootdev/javardfa/conformance /*
* (c) Copyright 2009 University of Bristol
* All rights reserved.
* [See end of file]
*/
package net.rootdev.javardfa.conformance;
import org.apache.jena.query.Query;
import org.apache.jena.query.QueryExecution;
import org.apache.jena.query.QueryExecutionFactory;
import org.apache.jena.query.QueryFactory;
import org.apache.jena.query.QuerySolution;
import org.apache.jena.query.ResultSet;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.util.FileManager;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import org.junit.Test;
import static org.junit.Assert.*;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
/**
* @author Damian Steer
*/
@RunWith(Parameterized.class)
public abstract class RDFaConformance {
final static Logger log = LoggerFactory.getLogger(RDFaConformance.class);
public static Collection testFiles(String manifestURI, String... excludes)
throws URISyntaxException, IOException {
Set toExclude = new HashSet(Arrays.asList(excludes));
FileManager fm = FileManager.get();
Model manifest = fm.loadModel(manifestURI);
Query manifestExtract = QueryFactory.read("manifest-extract.rq");
Collection tests = new ArrayList();
QueryExecution qe = QueryExecutionFactory.create(manifestExtract, manifest);
ResultSet results = qe.execSelect();
if (!results.hasNext()) {
throw new RuntimeException("No results");
}
while (results.hasNext()) {
QuerySolution soln = results.next();
String[] params = new String[6];
params[0] = soln.getResource("test").getURI();
params[1] = soln.getLiteral("title").getString();
params[2] = soln.getLiteral("purpose").getString();
params[3] = soln.getResource("input").getURI();
params[4] = soln.getResource("query").getURI();
// getBoolean not working??
//boolean expected = (soln.contains("expect")) ?
// soln.getLiteral("expect").getBoolean() : true;
params[5] = soln.contains("expect") ? soln.getLiteral("expect").getLexicalForm() : "true";
if (toExclude.contains(params[0]) ||
toExclude.contains(params[3]) ||
toExclude.contains(params[4]) ) {
log.warn("Skipping test <" + params[0] + ">");
continue;
}
tests.add(params);
}
return tests;
}
private final String test;
private final String title;
private final String purpose;
private final String input;
private final String query;
private final boolean expected;
public RDFaConformance(String test, String title,
String purpose, String input, String query, String expected) {
this.test = test;
this.title = title;
this.purpose = purpose;
this.input = input;
this.query = query;
this.expected = Boolean.valueOf(expected);
}
public abstract XMLReader getParser(Model model) throws SAXException;
@Test
public void compare() throws SAXException, IOException {
Model model = ModelFactory.createDefaultModel();
InputStream in = FileManager.get().open(input);
XMLReader reader = getParser(model);
try {
InputSource ins = new InputSource(in);
ins.setEncoding("utf-8");
ins.setSystemId(input);
reader.parse(ins);
} catch (NullPointerException e) {
fail("NPE <" + test + ">");
}
Query theQuery = QueryFactory.read(query);
QueryExecution qe = QueryExecutionFactory.create(theQuery, model);
boolean result = qe.execAsk();
if (result != expected) {
System.err.println("------ " + test + " ------");
model.write(System.err, "TTL");
System.err.println("------ Query ------");
System.err.println(theQuery);
System.err.println("-----------------------");
}
if (expected) {
assertTrue(title + " <" + test + ">", result);
} else {
assertFalse(title + " <" + test + ">", result);
}
}
}
/*
* (c) Copyright 2009 University of Bristol
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
XHTML.java 0000664 0000000 0000000 00000002340 13761231531 0034144 0 ustar 00root root 0000000 0000000 java-rdfa-java-rdfa-parent-1.0.0-BETA1/rdfa-module/src/test/java/net/rootdev/javardfa/conformance /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package net.rootdev.javardfa.conformance;
import org.apache.jena.rdf.model.Model;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Collection;
import net.rootdev.javardfa.jena.JenaStatementSink;
import net.rootdev.javardfa.ParserFactory;
import net.rootdev.javardfa.ParserFactory.Format;
import org.junit.runners.Parameterized.Parameters;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
/**
*
* @author pldms
*/
public class XHTML extends RDFaConformance
{
@Parameters
public static Collection testFiles()
throws URISyntaxException, IOException {
return RDFaConformance.
testFiles("http://rdfa.digitalbazaar.com/test-suite/test-cases/xhtml1/xhtml-manifest.rdf");
}
public XHTML(String test, String title,
String purpose, String input, String query, String expected) {
super(test, title, purpose, input, query, expected);
}
@Override
public XMLReader getParser(Model model) throws SAXException {
return ParserFactory.createReaderForFormat(new JenaStatementSink(model), Format.XHTML);
}
}
java-rdfa-java-rdfa-parent-1.0.0-BETA1/rdfa-module/src/test/java/net/rootdev/javardfa/conformance2/ 0000775 0000000 0000000 00000000000 13761231531 0032547 5 ustar 00root root 0000000 0000000 Cacher.java 0000664 0000000 0000000 00000011165 13761231531 0034524 0 ustar 00root root 0000000 0000000 java-rdfa-java-rdfa-parent-1.0.0-BETA1/rdfa-module/src/test/java/net/rootdev/javardfa/conformance2 package net.rootdev.javardfa.conformance2;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.NodeIterator;
import org.apache.jena.rdf.model.RDFNode;
import org.apache.jena.riot.RIOT;
import org.apache.jena.util.FileManager;
import org.apache.jena.util.LocationMapper;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* A utility to retrieve and store the conformance tests locally.
* Uses jena's location mapping
*
* @author Damian Steer
*/
public class Cacher {
final static Logger log = LoggerFactory.getLogger(Cacher.class);
final static String CACHED = "//////CACHED/////";
public static void main(String... args) {
RIOT.init();
Cacher c = new Cacher("src/test/resources/", false);
c.cacheManifest("http://rdfa.info/test-suite/rdfa1.0/svg/manifest");
c.cacheManifest("http://rdfa.info/test-suite/rdfa1.0/xhtml/manifest");
c.cacheManifest("http://rdfa.info/test-suite/rdfa1.0/xml/manifest");
c.cacheManifest("http://rdfa.info/test-suite/rdfa1.1/xml/manifest");
}
private final LocationMapper lm;
private final String base;
private final boolean forceDownload;
public Cacher(String base, boolean forceDownload) {
this.lm = LocationMapper.get();
this.base = base;
this.forceDownload = forceDownload;
}
public void cacheManifest(String uri) {
String location = cache(uri);
if (location == null) {
log.error("Failed to get manifest <{}>", uri);
return;
}
try {
Model manifest = FileManager.get().loadModel(uri, "TTL");
NodeIterator ni = manifest.listObjects();
// Download every object (bit broad?!)
while (ni.hasNext()) {
RDFNode n = ni.next();
if (n.isURIResource()) {
String res = cache(n.asResource().getURI());
if (res == null) System.out.print("!");
else if (res == CACHED) System.out.print("-");
else System.out.print("+");
}
}
System.out.println();
} catch (Exception e) {
log.error("Issue caching manifest <{}>: {}", uri, e);
}
}
public String cache(String uri) {
try {
return cacheInternal(uri);
} catch (Exception ex) {
log.error("Error getting <{}>: {}", uri, ex);
}
return null;
}
private String cacheInternal(String uri) throws MalformedURLException, IOException {
String location = lm.altMapping(uri);
if (location == null || uri.equals(location)) {
log.error("No mapping for <{}>", uri);
return null;
}
location = location.replace("file:", "");
log.info("Location is: {}\n", location);
File target = new File(base, location);
if (!forceDownload && target.isFile()) {
log.info("<{}> already stored.", uri);
return CACHED;
}
if (target.getParentFile().exists() && !target.getParentFile().isDirectory()) {
log.error("<{}> is not a directory", target.getParentFile());
return null;
}
if (!target.getParentFile().exists() && !target.getParentFile().mkdirs()) {
log.error("Couldn't create <{}>", target.getParentFile());
return null;
}
HttpURLConnection conn = null;
BufferedInputStream in = null;
FileOutputStream out = null;
try {
URL url = new URL(uri);
conn = (HttpURLConnection) url.openConnection();
in = new BufferedInputStream(conn.getInputStream());
if (conn.getResponseCode() / 100 != 2) {
log.error("<{}> returned code {}", uri, conn.getResponseCode());
return null;
}
out = new FileOutputStream(target);
byte[] buffer = new byte[2048];
int got;
while ((got = in.read(buffer)) != -1) {
out.write(buffer, 0, got);
}
return location;
} finally {
if (out != null) out.close();
if (in != null) in.close();
if (conn.getErrorStream() != null) conn.getErrorStream().close();
}
}
}
RDFaConformance.java 0000664 0000000 0000000 00000016037 13761231531 0036271 0 ustar 00root root 0000000 0000000 java-rdfa-java-rdfa-parent-1.0.0-BETA1/rdfa-module/src/test/java/net/rootdev/javardfa/conformance2 /*
* (c) Copyright 2009 University of Bristol
* All rights reserved.
* [See end of file]
*/
package net.rootdev.javardfa.conformance2;
import org.apache.jena.query.Query;
import org.apache.jena.query.QueryExecution;
import org.apache.jena.query.QueryExecutionFactory;
import org.apache.jena.query.QueryFactory;
import org.apache.jena.query.QueryParseException;
import org.apache.jena.query.QuerySolution;
import org.apache.jena.query.ResultSet;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.riot.RIOT;
import org.apache.jena.util.FileManager;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.junit.Test;
import static org.junit.Assert.*;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
/**
* @author Damian Steer
*/
@RunWith(Parameterized.class)
public abstract class RDFaConformance {
final static Logger log = LoggerFactory.getLogger(RDFaConformance.class);
static {
RIOT.init();
}
/** Utility to limit test indices **/
public static List filterTests(List allTests, Integer... testNums) {
List tests = new ArrayList();
for (Integer num: testNums) tests.add(allTests.get(num));
return tests;
}
public static List testFiles(String manifestURI, String extractQuery, String... excludes)
throws URISyntaxException, IOException {
Set toExclude = new HashSet(Arrays.asList(excludes));
FileManager fm = FileManager.get();
Model manifest = fm.loadModel(manifestURI, "TTL");
Query manifestExtract = QueryFactory.read(extractQuery);
List tests = new ArrayList();
QueryExecution qe = QueryExecutionFactory.create(manifestExtract, manifest);
ResultSet results = qe.execSelect();
if (!results.hasNext()) {
throw new RuntimeException("No results");
}
while (results.hasNext()) {
QuerySolution soln = results.next();
String[] params = new String[6];
params[0] = soln.getResource("test").getURI();
params[1] = soln.getLiteral("title").getString();
params[2] = soln.getLiteral("purpose").getString();
params[3] = soln.getResource("input").getURI();
params[4] = soln.getResource("query").getURI();
// getBoolean not working??
//boolean expected = (soln.contains("expect")) ?
// soln.getLiteral("expect").getBoolean() : true;
params[5] = soln.contains("expect") ? soln.getLiteral("expect").getLexicalForm() : "true";
if (toExclude.contains(params[0])
|| toExclude.contains(params[3])
|| toExclude.contains(params[4])) {
log.warn("Skipping test <" + params[0] + ">");
continue;
}
tests.add(params);
}
return tests;
}
private final String test;
private final String title;
private final String purpose;
private final String input;
private final String query;
private final boolean expected;
public RDFaConformance(String test, String title,
String purpose, String input, String query, String expected) {
this.test = test;
this.title = title;
this.purpose = purpose;
this.input = input;
this.query = query;
this.expected = Boolean.valueOf(expected);
}
public abstract XMLReader getParser(Model model) throws SAXException;
@Test
public void compare() throws Throwable {
try {
Model model = ModelFactory.createDefaultModel();
InputStream in = FileManager.get().open(input);
XMLReader reader = getParser(model);
InputSource ins = new InputSource(in);
ins.setEncoding("utf-8");
ins.setSystemId(input);
reader.parse(ins);
Query theQuery = QueryFactory.read(query);
QueryExecution qe = QueryExecutionFactory.create(theQuery, model);
boolean result = qe.execAsk();
if (result != expected) {
System.err.println("------ " + test + " ------");
model.write(System.err, "TTL");
System.err.println("------ Query ------");
System.err.println(theQuery);
System.err.println("-----------------------");
}
if (expected) {
assertTrue(title + " <" + test + ">", result);
} else {
assertFalse(title + " <" + test + ">", result);
}
} catch (Throwable e) {
// Make error reporting more informative by noting test that failed
// These are fine, of course
if (e instanceof AssertionError) throw e;
// Note source of issue and throw
String message = String.format("<%s>: %s %s", test, e.getClass().getName(), e.getLocalizedMessage());
Exception newEx = new Exception(message, e);
newEx.setStackTrace(e.getStackTrace()); // very dodgy!
throw newEx;
}
}
}
/*
* (c) Copyright 2009 University of Bristol
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
SVG10.java 0000664 0000000 0000000 00000002430 13761231531 0034132 0 ustar 00root root 0000000 0000000 java-rdfa-java-rdfa-parent-1.0.0-BETA1/rdfa-module/src/test/java/net/rootdev/javardfa/conformance2 package net.rootdev.javardfa.conformance2;
import org.apache.jena.rdf.model.Model;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Collection;
import net.rootdev.javardfa.ParserFactory;
import net.rootdev.javardfa.ParserFactory.Format;
import net.rootdev.javardfa.jena.JenaStatementSink;
import org.junit.runners.Parameterized.Parameters;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
/**
*
* @author pldms
*/
public class SVG10 extends RDFaConformance
{
@Parameters
public static Collection testFiles()
throws URISyntaxException, IOException {
return RDFaConformance.
testFiles("http://rdfa.info/test-suite/rdfa1.0/svg/manifest",
"conformance2/manifest-extract.rq",
// Not an RDFa test!
"http://rdfa.info/test-suite/test-cases/rdfa1.0/svg/0304.svg"
);
}
public SVG10(String test, String title,
String purpose, String input, String query, String expected) {
super(test, title, purpose, input, query, expected);
}
@Override
public XMLReader getParser(Model model) throws SAXException {
return ParserFactory.createReaderForFormat(new JenaStatementSink(model), Format.XHTML);
}
}
XML10.java 0000664 0000000 0000000 00000003051 13761231531 0034133 0 ustar 00root root 0000000 0000000 java-rdfa-java-rdfa-parent-1.0.0-BETA1/rdfa-module/src/test/java/net/rootdev/javardfa/conformance2 package net.rootdev.javardfa.conformance2;
import org.apache.jena.rdf.model.Model;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Collection;
import net.rootdev.javardfa.ParserFactory;
import net.rootdev.javardfa.ParserFactory.Format;
import net.rootdev.javardfa.jena.JenaStatementSink;
import org.junit.runners.Parameterized.Parameters;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
/**
*
* @author pldms
*/
public class XML10 extends RDFaConformance
{
@Parameters
public static Collection testFiles()
throws URISyntaxException, IOException {
return RDFaConformance.
testFiles("http://rdfa.info/test-suite/rdfa1.0/xml/manifest",
"conformance2/manifest-extract.rq",
// Exclude: test uses html base outside html. Badly migrated, I guess.
"http://rdfa.info/test-suite/test-cases/rdfa1.0/xml/0210.xml",
// Exclude: test namespaces are wrong. xhtml isn't mentioned, dc inclusion is dubious.
"http://rdfa.info/test-suite/test-cases/rdfa1.0/xml/0212.xml"
);
}
public XML10(String test, String title,
String purpose, String input, String query, String expected) {
super(test, title, purpose, input, query, expected);
}
@Override
public XMLReader getParser(Model model) throws SAXException {
return ParserFactory.createReaderForFormat(new JenaStatementSink(model), Format.XHTML);
}
}
XML11.java 0000664 0000000 0000000 00000002556 13761231531 0034145 0 ustar 00root root 0000000 0000000 java-rdfa-java-rdfa-parent-1.0.0-BETA1/rdfa-module/src/test/java/net/rootdev/javardfa/conformance2 package net.rootdev.javardfa.conformance2;
import org.apache.jena.rdf.model.Model;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Collection;
import net.rootdev.javardfa.ParserFactory;
import net.rootdev.javardfa.ParserFactory.Format;
import net.rootdev.javardfa.Setting;
import net.rootdev.javardfa.jena.JenaStatementSink;
import org.junit.runners.Parameterized.Parameters;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
/**
*
* @author pldms
*/
public class XML11 extends RDFaConformance
{
@Parameters
public static Collection testFiles()
throws URISyntaxException, IOException {
return RDFaConformance.
testFiles("http://rdfa.info/test-suite/rdfa1.1/xml/manifest",
"conformance2/manifest-extract-1.1.rq",
// Exclude: test stopped working with jena-3
"http://rdfa.info/test-suite/test-cases/rdfa1.1/xml/0319.xml"
);
}
public XML11(String test, String title,
String purpose, String input, String query, String expected) {
super(test, title, purpose, input, query, expected);
}
@Override
public XMLReader getParser(Model model) throws SAXException {
return ParserFactory.createReaderForFormat(new JenaStatementSink(model), Format.XHTML, Setting.OnePointOne);
}
}
java-rdfa-java-rdfa-parent-1.0.0-BETA1/rdfa-module/src/test/java/net/rootdev/javardfa/output/ 0000775 0000000 0000000 00000000000 13761231531 0031533 5 ustar 00root root 0000000 0000000 NTripleSinkTest.java 0000664 0000000 0000000 00000007211 13761231531 0035362 0 ustar 00root root 0000000 0000000 java-rdfa-java-rdfa-parent-1.0.0-BETA1/rdfa-module/src/test/java/net/rootdev/javardfa/output /*
* (c) Copyright 2010 University of Bristol
* All rights reserved.
* [See end of file]
*/
package net.rootdev.javardfa.output;
import java.io.StringWriter;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author pldms
*/
public class NTripleSinkTest {
private StringWriter out;
private NTripleSink sink;
public NTripleSinkTest() {
}
@Before
public void setUp() {
this.out = new StringWriter();
this.sink = new NTripleSink(out);
}
/**
* Test of end method, of class NTripleSink.
*/
@Test
public void testEnd() {}
/**
* Test of addObject method, of class NTripleSink.
*/
@Test
public void testAddObject() {}
/**
* Test of addLiteral method, of class NTripleSink.
*/
@Test
public void testAddLiteral() {}
/**
* Test of addPrefix method, of class NTripleSink.
*/
@Test
public void testAddPrefix() {}
/**
* Test of toNode method, of class NTripleSink.
*/
@Test
public void testToNode() {
assertEquals("Convert bnode", "_:a ", sink.toNode("_:a"));
assertEquals("Convert var", "?a ", sink.toNode("?a"));
assertEquals("Convert uri", " ", sink.toNode("http://www.example.com/"));
}
/**
* Test of toLiteral method, of class NTripleSink.
*/
@Test
public void testToLiteral() {
assertEquals("Convert plain", "\"a\" ", sink.toLiteral("a", null, null));
assertEquals("Convert lang", "\"a\"@en ", sink.toLiteral("a", "en", null));
assertEquals("Convert no lang", "\"a\" ", sink.toLiteral("a", "", null));
assertEquals("Convert dt", "\"a\"^^ ", sink.toLiteral("a", null, "http://www.example.com/"));
}
/**
* Test of quote method, of class NTripleSink.
*/
@Test
public void testQuote() {
assertEquals("Quote me", "\"a\\\"b\"", sink.quote("a\"b"));
assertEquals("Quote tab", "\"a\\tb\"", sink.quote("a\tb"));
assertEquals("Quote newline", "\"a\\nb\"", sink.quote("a\nb"));
assertEquals("Quote non-ascii", "\"a\\ufeffb\"", sink.quote("a\ufeffb"));
}
}
/*
* (c) Copyright 2010 University of Bristol
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/ OGPReaderTest.java 0000664 0000000 0000000 00000005306 13761231531 0034733 0 ustar 00root root 0000000 0000000 java-rdfa-java-rdfa-parent-1.0.0-BETA1/rdfa-module/src/test/java/net/rootdev/javardfa/output /*
* (c) Copyright 2010 University of Bristol
* All rights reserved.
* [See end of file]
*/
package net.rootdev.javardfa.output;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import net.rootdev.javardfa.ParserFactory.Format;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author pldms
*/
public class OGPReaderTest {
/**
* Test of getOGP method, of class OGPReader.
*/
@Test
public void testGetOGP() throws Exception {
URL toLoad = OGPReaderTest.class.getResource("/ogp.html");
System.out.println("getOGP");
String url = "";
Format format = null;
Map expResult = new HashMap();
expResult.put("latitude", "37.416343");
expResult.put("longitude", "-122.153013");
expResult.put("street-address", "1601 S California Ave");
expResult.put("locality", "Palo Alto");
expResult.put("region", "CA");
expResult.put("postal-code", "94304");
expResult.put("country-name", "USA");
expResult.put("http://example.com/ex#foo", "not-ogp");
Map result = OGPReader.getOGP(toLoad.toExternalForm(), Format.HTML);
assertEquals(expResult, result);
}
}
/*
* (c) Copyright 2009 University of Bristol
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/ java-rdfa-java-rdfa-parent-1.0.0-BETA1/rdfa-module/src/test/resources/ 0000775 0000000 0000000 00000000000 13761231531 0025236 5 ustar 00root root 0000000 0000000 java-rdfa-java-rdfa-parent-1.0.0-BETA1/rdfa-module/src/test/resources/1.tmpl 0000664 0000000 0000000 00000002454 13761231531 0026301 0 ustar 00root root 0000000 0000000