incubator-odf-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From svanteschub...@apache.org
Subject svn commit: r1418326 [7/8] - in /incubator/odf/trunk: ./ odfdom/ odfdom/src/main/java/org/odftoolkit/odfdom/dom/ odfdom/src/main/java/org/odftoolkit/odfdom/dom/element/table/ odfdom/src/main/java/org/odftoolkit/odfdom/dom/element/text/ odfdom/src/main/...
Date Fri, 07 Dec 2012 14:28:13 GMT
Modified: incubator/odf/trunk/odfdom/src/main/java/org/odftoolkit/odfdom/pkg/OdfPackageDocument.java
URL: http://svn.apache.org/viewvc/incubator/odf/trunk/odfdom/src/main/java/org/odftoolkit/odfdom/pkg/OdfPackageDocument.java?rev=1418326&r1=1418325&r2=1418326&view=diff
==============================================================================
--- incubator/odf/trunk/odfdom/src/main/java/org/odftoolkit/odfdom/pkg/OdfPackageDocument.java (original)
+++ incubator/odf/trunk/odfdom/src/main/java/org/odftoolkit/odfdom/pkg/OdfPackageDocument.java Fri Dec  7 14:28:07 2012
@@ -1,4 +1,5 @@
-/************************************************************************
+/**
+ * **********************************************************************
  *
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
  *
@@ -7,8 +8,8 @@
  * Use is subject to license terms.
  *
  * Licensed under the Apache License, Version 2.0 (the "License"); you may not
- * use this file except in compliance with the License. You may obtain a copy
- * of the License at http://www.apache.org/licenses/LICENSE-2.0. You can also
+ * use this file except in compliance with the License. You may obtain a copy of
+ * the License at http://www.apache.org/licenses/LICENSE-2.0. You can also
  * obtain a copy of the License at http://odftoolkit.org/docs/license.txt
  *
  * Unless required by applicable law or agreed to in writing, software
@@ -18,21 +19,37 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  *
- ************************************************************************/
+ ***********************************************************************
+ */
 package org.odftoolkit.odfdom.pkg;
 
+import com.hp.hpl.jena.rdf.model.Model;
+import com.hp.hpl.jena.rdf.model.ModelFactory;
+import com.hp.hpl.jena.util.ResourceUtils;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
 import java.io.Closeable;
 import java.io.File;
 import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.net.URI;
 import java.util.logging.Level;
 import java.util.logging.Logger;
+import javax.xml.transform.Templates;
+import javax.xml.transform.TransformerFactory;
 import javax.xml.transform.URIResolver;
+import javax.xml.transform.sax.SAXSource;
+import javax.xml.transform.stream.StreamResult;
+import org.odftoolkit.odfdom.dom.OdfSchemaDocument;
+import org.odftoolkit.odfdom.pkg.rdfa.Util;
 import org.xml.sax.EntityResolver;
+import org.xml.sax.InputSource;
 
 /**
  *
- * The package layer described by the ODF 1.2 Package specification is independent
- * of the above ODF XML layer described by the ODF 1.2 XML Schema specification.
+ * The package layer described by the ODF 1.2 Package specification is
+ * independent of the above ODF XML layer described by the ODF 1.2 XML Schema
+ * specification.
  *
  * Still the abstract concept of documents exist in the ODF Package layer.
  */
@@ -42,24 +59,35 @@ public class OdfPackageDocument implemen
 	private static final String SLASH = "/";
 	private static final String COLON = ":";
 	private static final String EMPTY_STRING = "";
-	/** The path of the root document */
+	/**
+	 * The path of the root document
+	 */
 	protected static final String ROOT_DOCUMENT_PATH = EMPTY_STRING;
 	private Resolver mResolver;
-	/** The ODF package containing the document */
+	/**
+	 * The ODF package containing the document
+	 */
 	protected OdfPackage mPackage;
-	/** The internal path to the document relative to the ODF package */
+	/**
+	 * The internal path to the document relative to the ODF package
+	 */
 	protected String mDocumentPathInPackage;
-	/** The mediatype of the ODF package document. Note: Not necessarily an ODF XML mediatype as specified in ODF 1.2 part1 */
+	/**
+	 * The mediatype of the ODF package document. Note: Not necessarily an ODF
+	 * XML mediatype as specified in ODF 1.2 part1
+	 */
 	protected String mDocumentMediaType;
-
+	private static Templates mRdfFileExtractionTemplate;
 
 	/**
 	 * Creates a new OdfPackageDocument.
 	 *
-	 * @param pkg - the ODF Package that contains the document. A baseURL is being generated based on its location.
-	 * @param internalPath - the directory path within the package from where the document should be loaded.
-	 * @param mediaTypeString
-	 *      - media type of stream. If unknown null can be used.
+	 * @param pkg - the ODF Package that contains the document. A baseURL is
+	 * being generated based on its location.
+	 * @param internalPath - the directory path within the package from where
+	 * the document should be loaded.
+	 * @param mediaTypeString - media type of stream. If unknown null can be
+	 * used.
 	 */
 	protected OdfPackageDocument(OdfPackage pkg, String internalPath, String mediaTypeString) {
 		super();
@@ -76,12 +104,12 @@ public class OdfPackageDocument implemen
 	/**
 	 * Loads an OdfPackageDocument from the provided path.
 	 *
-	 * <p>OdfPackageDocument relies on the file being available for read access over
-	 * the whole lifecycle of OdfDocument.</p>
+	 * <p>OdfPackageDocument relies on the file being available for read access
+	 * over the whole lifecycle of OdfDocument.</p>
 	 *
 	 * @param documentPath - the path from where the document can be loaded
-	 * @return the OpenDocument from the given path
-	 *		  or NULL if the media type is not supported by ODFDOM.
+	 * @return the OpenDocument from the given path or NULL if the media type is
+	 * not supported by ODFDOM.
 	 * @throws java.lang.Exception - if the document could not be created.
 	 */
 	public static OdfPackageDocument loadDocument(String documentPath) throws Exception {
@@ -92,7 +120,8 @@ public class OdfPackageDocument implemen
 	/**
 	 * Returns an embedded OdfPackageDocument from the given package path.
 	 *
-	 * @param documentPath to the document within the package. The path is relative the current document path.
+	 * @param documentPath to the document within the package. The path is
+	 * relative the current document path.
 	 * @return an embedded OdfPackageDocument
 	 */
 	public OdfPackageDocument loadSubDocument(String documentPath) {
@@ -138,7 +167,9 @@ public class OdfPackageDocument implemen
 
 	/**
 	 * Set the relative path for an embedded ODF document.
-	 * @param path to directory of the embedded ODF document (relative to ODF package root).
+	 *
+	 * @param path to directory of the embedded ODF document (relative to ODF
+	 * package root).
 	 */
 	String setDocumentPath(String path) {
 		mDocumentPathInPackage = normalizeDocumentPath(path);
@@ -147,23 +178,28 @@ public class OdfPackageDocument implemen
 
 	/**
 	 * Get the relative path for an embedded ODF document.
-	 * @return path to the directory of the embedded ODF document (relative to ODF package root).
+	 *
+	 * @return path to the directory of the embedded ODF document (relative to
+	 * ODF package root).
 	 */
 	public String getDocumentPath() {
 		return mDocumentPathInPackage;
 	}
 
 	/**
-	 * Removes an embedded ODF document from the ODF Package.
-	 * All files within the embedded document directory will be removed.
+	 * Removes an embedded ODF document from the ODF Package. All files within
+	 * the embedded document directory will be removed.
 	 *
-	 * @param internDocumentPath path to the directory of the embedded ODF document (always relative to the package path of the current document).
+	 * @param internDocumentPath path to the directory of the embedded ODF
+	 * document (always relative to the package path of the current document).
 	 */
 	public void removeDocument(String internDocumentPath) {
 		mPackage.removeDocument(mDocumentPathInPackage + internDocumentPath);
 	}
 
-	/** @return true if the document is at the root level of the package */
+	/**
+	 * @return true if the document is at the root level of the package
+	 */
 	public boolean isRootDocument() {
 		if (getDocumentPath().equals(ROOT_DOCUMENT_PATH)) {
 			return true;
@@ -176,8 +212,8 @@ public class OdfPackageDocument implemen
 	 * Checks if the given reference is a reference, which points outside the
 	 * ODF package Only relative path are allowed with the exception of a single
 	 * slash '/' representing the root document.
-	 * 
-	 * @param ref   the file reference to be checked
+	 *
+	 * @param ref the file reference to be checked
 	 * @return true if the reference is an package external reference
 	 */
 	protected static boolean isExternalReference(String ref) {
@@ -196,10 +232,10 @@ public class OdfPackageDocument implemen
 	/**
 	 * Ensure the document path for is valid and gurantee unique encoding by
 	 * normalizing the path.
-	 * 
+	 *
 	 * @see OdfPackage#normalizeDirectoryPath(java.lang.String)
-	 * @param documentPath  the destination directory of the document. The path should end
-	 *            with a '/'.
+	 * @param documentPath the destination directory of the document. The path
+	 * should end with a '/'.
 	 * @return the documentPath after normalization.
 	 */
 	protected static String normalizeDocumentPath(String documentPath) {
@@ -214,14 +250,15 @@ public class OdfPackageDocument implemen
 	/**
 	 * Save the document to given path.
 	 *
-	 * <p>When save the embedded document to a stand alone document,
-	 * all the file entries of the embedded document will be copied to a new document package.
-	 * If the embedded document is outside of the current document directory,
-	 * you have to embed it to the sub directory and refresh the link of the embedded document.
-	 * You should reload it from the given path to get the saved embedded document.
+	 * <p>When save the embedded document to a stand alone document, all the
+	 * file entries of the embedded document will be copied to a new document
+	 * package. If the embedded document is outside of the current document
+	 * directory, you have to embed it to the sub directory and refresh the link
+	 * of the embedded document. You should reload it from the given path to get
+	 * the saved embedded document.
 	 *
 	 * @param documentPath - the path to the package document
-	 * @throws java.lang.Exception  if the document could not be saved
+	 * @throws java.lang.Exception if the document could not be saved
 	 */
 	public void save(String documentPath) throws Exception {
 		File f = new File(documentPath);
@@ -231,46 +268,53 @@ public class OdfPackageDocument implemen
 	/**
 	 * Save the document to a given file.
 	 *
-	 * <p>If the input file has been cached (this is the case when loading from an
-	 * InputStream), the input file can be overwritten.</p>
+	 * <p>If the input file has been cached (this is the case when loading from
+	 * an InputStream), the input file can be overwritten.</p>
 	 *
-	 * <p>Otherwise it's allowed to overwrite the input file as long as
-	 * the same path name is used that was used for loading (no symbolic link
-	 * foo2.odt pointing to the loaded file foo1.odt, no network path X:\foo.odt
-	 * pointing to the loaded file D:\foo.odt).</p>
-	 *
-	 * <p>When saving the embedded document to a stand alone document,
-	 * all files of the embedded document will be copied to a new document package.
-	 * If the embedded document is outside of the current document directory,
-	 * you have to embed it to the sub directory and refresh the link of the embedded document.
-	 * You should reload it from the given file to get the saved embedded document.
+	 * <p>Otherwise it's allowed to overwrite the input file as long as the same
+	 * path name is used that was used for loading (no symbolic link foo2.odt
+	 * pointing to the loaded file foo1.odt, no network path X:\foo.odt pointing
+	 * to the loaded file D:\foo.odt).</p>
+	 *
+	 * <p>When saving the embedded document to a stand alone document, all files
+	 * of the embedded document will be copied to a new document package. If the
+	 * embedded document is outside of the current document directory, you have
+	 * to embed it to the sub directory and refresh the link of the embedded
+	 * document. You should reload it from the given file to get the saved
+	 * embedded document.
 	 *
 	 * @param file - the file to save the document
-	 * @throws java.lang.Exception  if the document could not be saved
+	 * @throws java.lang.Exception if the document could not be saved
 	 */
 	public void save(File file) throws Exception {
 		mPackage.save(file);
 	}
 
-	/** Flush the existing DOM to the document to get in advantage of the recent changes from the DOM */
+	/**
+	 * Flush the existing DOM to the document to get in advantage of the recent
+	 * changes from the DOM
+	 */
 	protected void flushDoms() {
 		mPackage.flushDoms(this);
 	}
 
 	/**
-	 * Embed an OdfPackageDocument to the current OdfPackageDocument.
-	 * All the file entries of child document will be embedded as well to the current document package.
+	 * Embed an OdfPackageDocument to the current OdfPackageDocument. All the
+	 * file entries of child document will be embedded as well to the current
+	 * document package.
+	 *
 	 * @param newDocument the OdfPackageDocument to be embedded.
-	 * @param documentPath to the directory the ODF document should be inserted (relative to the root of this document).	 
+	 * @param documentPath to the directory the ODF document should be inserted
+	 * (relative to the root of this document).
 	 */
 	public void insertDocument(OdfPackageDocument newDocument, String documentPath) {
 		newDocument.flushDoms();
 		mPackage.insertDocument(newDocument, mDocumentPathInPackage + documentPath);
 	}
 
-	/** 
+	/**
 	 * @param internalPath path to the XML file relative to package root
-	 * @return the typed DOM of the given file 
+	 * @return the typed DOM of the given file
 	 */
 	public OdfFileDom getFileDom(String internalPath) throws Exception {
 		String normalizeDocumentPath = getDocumentPath();
@@ -281,8 +325,8 @@ public class OdfPackageDocument implemen
 	}
 
 	/**
-	 * Get EntityResolver to be used in XML Parsers
-	 * which can resolve content inside the OdfPackage
+	 * Get EntityResolver to be used in XML Parsers which can resolve content
+	 * inside the OdfPackage
 	 */
 	EntityResolver getEntityResolver() {
 		if (mResolver == null) {
@@ -292,8 +336,8 @@ public class OdfPackageDocument implemen
 	}
 
 	/**
-	 * Get URIResolver to be used in XSL Transformations
-	 * which can resolve content inside the OdfPackage
+	 * Get URIResolver to be used in XSL Transformations which can resolve
+	 * content inside the OdfPackage
 	 */
 	URIResolver getURIResolver() {
 		if (mResolver == null) {
@@ -303,10 +347,10 @@ public class OdfPackageDocument implemen
 	}
 
 	/**
-	 * Close the OdfPackageDocument, its OdfPackage and release all temporary created data.
-	 * Acter execution of this method, this class is no longer usable.
-	 * Do this as the last action to free resources.
-	 * Closing an already closed document has no effect.
+	 * Close the OdfPackageDocument, its OdfPackage and release all temporary
+	 * created data. Acter execution of this method, this class is no longer
+	 * usable. Do this as the last action to free resources. Closing an already
+	 * closed document has no effect.
 	 */
 	public void close() {
 		mPackage.close();
@@ -314,7 +358,10 @@ public class OdfPackageDocument implemen
 		mPackage = null;
 	}
 
-	/** Helper class to receive an ODF document template for new documents from the environment (ie. from the JAR via classloader)*/
+	/**
+	 * Helper class to receive an ODF document template for new documents from
+	 * the environment (ie. from the JAR via classloader)
+	 */
 	protected static class Resource {
 
 		private String name;
@@ -331,4 +378,34 @@ public class OdfPackageDocument implemen
 			return in;
 		}
 	}
+
+	/**
+	 * Extracts RDF Metadata triple from XML files
+	 * 
+	 * @param internalPath path to the XML file relative to package root
+	 * @return RDF Metadata through GRDDL XSLT of given XML file
+	 */
+	public Model getXMLFileMetadata(String internalPath) {
+		Model rdfModel = null;
+		try {
+			ByteArrayOutputStream out = new ByteArrayOutputStream();
+			OdfXMLHelper helper = new OdfXMLHelper();
+			if (mRdfFileExtractionTemplate == null) {
+				String filePath = "file:" + OdfPackageDocument.class.getClassLoader().getResource("grddl/odf2rdf.xsl").getPath();
+				URI uri = new URI(filePath);
+				InputSource inputSource = new InputSource(uri.toString());
+				mRdfFileExtractionTemplate = TransformerFactory.newInstance().newTemplates(new SAXSource(inputSource));
+			}
+			helper.transform(this.getPackage(), internalPath, mRdfFileExtractionTemplate, new StreamResult(out));
+			String RDFBaseUri = Util.getRDFBaseUri(this.getPackage().getBaseURI(), internalPath);
+			rdfModel = ModelFactory.createDefaultModel();
+			rdfModel.read(new InputStreamReader(new ByteArrayInputStream(out.toByteArray()), "utf-8"), RDFBaseUri);
+			// remove the last SLASH at the end of the RDFBaseUri:
+			// test_rdfmeta.odt/ --> test_rdfmeta.odt
+			ResourceUtils.renameResource(rdfModel.getResource(RDFBaseUri), RDFBaseUri.substring(0, RDFBaseUri.length() - 1));
+		} catch (Exception ex) {
+			Logger.getLogger(OdfPackageDocument.class.getName()).log(Level.SEVERE, null, ex);
+		}
+		return rdfModel;
+	}
 }

Added: incubator/odf/trunk/odfdom/src/main/java/org/odftoolkit/odfdom/pkg/OdfXMLHelper.java
URL: http://svn.apache.org/viewvc/incubator/odf/trunk/odfdom/src/main/java/org/odftoolkit/odfdom/pkg/OdfXMLHelper.java?rev=1418326&view=auto
==============================================================================
--- incubator/odf/trunk/odfdom/src/main/java/org/odftoolkit/odfdom/pkg/OdfXMLHelper.java (added)
+++ incubator/odf/trunk/odfdom/src/main/java/org/odftoolkit/odfdom/pkg/OdfXMLHelper.java Fri Dec  7 14:28:07 2012
@@ -0,0 +1,377 @@
+/************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
+ * 
+ * Copyright 2008, 2010 Oracle and/or its affiliates. All rights reserved.
+ * 
+ * Use is subject to license terms.
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License. You may obtain a copy
+ * of the License at http://www.apache.org/licenses/LICENSE-2.0. You can also
+ * obtain a copy of the License at http://odftoolkit.org/docs/license.txt
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * 
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ************************************************************************/
+package org.odftoolkit.odfdom.pkg;
+
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.transform.Result;
+import javax.xml.transform.Source;
+import javax.xml.transform.Templates;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerConfigurationException;
+import javax.xml.transform.TransformerException;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
+import javax.xml.transform.stream.StreamSource;
+
+import org.odftoolkit.odfdom.pkg.rdfa.Util;
+import org.w3c.dom.Document;
+import org.w3c.dom.DocumentType;
+import org.xml.sax.ContentHandler;
+import org.xml.sax.ErrorHandler;
+import org.xml.sax.InputSource;
+import org.xml.sax.SAXException;
+import org.xml.sax.XMLReader;
+
+class OdfXMLHelper {
+
+	/**
+	 * create an XMLReader
+	 * with a Resolver set to parse content in a ODF Package
+	 *
+	 * @param pkg the ODF Package
+	 * @return a SAX XMLReader
+	 * @throws SAXException
+	 * @throws ParserConfigurationException
+	 */
+	public XMLReader newXMLReader(OdfPackage pkg)
+			throws SAXException, ParserConfigurationException {
+		XMLReader xmlReader = pkg.getXMLReader();
+		xmlReader.setEntityResolver(pkg.getEntityResolver());
+		return xmlReader;
+	}
+
+	/**
+	 * use SAX parser to parse content of package
+	 * @param pkg a OdfPackage
+	 * @param path a path inside the OdfPackage, eg. to a contained content.xml stream
+	 * @param contentHandler a SAX Content handler to receive SAX Events
+	 * @param errorHandler a SAX Error handler to be called on errors during parsing
+	 * @throws SAXException
+	 * @throws ParserConfigurationException
+	 * @throws IOException
+	 * @throws IllegalArgumentException
+	 * @throws TransformerConfigurationException
+	 * @throws TransformerException
+	 */
+	public void parse(OdfPackage pkg, String path, ContentHandler contentHandler, ErrorHandler errorHandler)
+			throws SAXException, ParserConfigurationException, IOException, IllegalArgumentException, TransformerConfigurationException, TransformerException {
+
+		InputStream is = null;
+		try {
+			is = pkg.getInputStream(path);
+			XMLReader reader = newXMLReader(pkg);
+
+			String uri = pkg.getBaseURI() + path;
+
+			if (contentHandler != null) {
+				reader.setContentHandler(contentHandler);
+			}
+			if (errorHandler != null) {
+				reader.setErrorHandler(errorHandler);
+			}
+
+			InputSource ins = new InputSource(is);
+			ins.setSystemId(uri);
+
+			reader.parse(ins);
+		} catch (Exception ex) {
+			Logger.getLogger(OdfXMLHelper.class.getName()).log(Level.SEVERE, null, ex);
+		} finally {
+			try {
+				is.close();
+			} catch (IOException ex) {
+				Logger.getLogger(OdfXMLHelper.class.getName()).log(Level.SEVERE, null, ex);
+			}
+		}
+	}
+
+	/**
+	 * Do XSL-Transformation on content contained in package
+	 * @param pkg a OdfPackage
+	 * @param path a path inside the OdfPackage, eg. to a contained content.xml stream
+	 * @param templatePath a path to a file in the filesystem containing an XSL Template
+	 * @param outPath a path in the filesystem for the output of the XSL Transformation
+	 * @throws TransformerConfigurationException
+	 * @throws TransformerException
+	 * @throws IOException
+	 * @throws IllegalArgumentException
+	 * @throws SAXException
+	 * @throws ParserConfigurationException
+	 */
+	public void transform(OdfPackage pkg, String path, String templatePath, String outPath)
+			throws TransformerConfigurationException, TransformerException,
+			IOException, IllegalArgumentException, SAXException, ParserConfigurationException {
+
+		transform(pkg, path, new File(templatePath), new File(outPath));
+	}
+
+	/**
+	 * Do XSL-Transformation on content contained in package
+	 * @param pkg a OdfPackage
+	 * @param path a path inside the OdfPackage, eg. to a contained content.xml stream
+	 * @param templateSource TraX Source of an XSL Transformation Template
+	 * @param outPath path to an output file for the XSL Transformation
+	 * @throws TransformerConfigurationException
+	 * @throws TransformerException
+	 * @throws IOException
+	 * @throws IllegalArgumentException
+	 * @throws SAXException
+	 * @throws ParserConfigurationException
+	 */
+	public void transform(OdfPackage pkg, String path, Source templateSource, String outPath)
+			throws TransformerConfigurationException, TransformerException,
+			IOException, IllegalArgumentException, SAXException, ParserConfigurationException {
+
+		transform(pkg, path, templateSource, new File(outPath));
+	}
+
+	/**
+	 * Do XSL-Transformation on content contained in package
+	 * @param pkg a OdfPackage
+	 * @param path a path inside the OdfPackage, eg. to a contained content.xml stream
+	 * @param templateSource TraX Source of an XSL Transformation
+	 * @param out an output File
+	 * @throws TransformerConfigurationException
+	 * @throws TransformerException
+	 * @throws IOException
+	 * @throws IllegalArgumentException
+	 * @throws SAXException
+	 * @throws ParserConfigurationException
+	 */
+	public void transform(OdfPackage pkg, String path, Source templateSource, File out)
+			throws TransformerConfigurationException, TransformerException,
+			IOException, IllegalArgumentException, SAXException, ParserConfigurationException {
+
+		transform(pkg, path, templateSource, new StreamResult(out));
+	}
+
+	/**
+	 * Do XSL-Transformation on content contained in package
+	 * insert result back to package
+	 * @param pkg a OdfPackage
+	 * @param path a path inside the OdfPackage, eg. to a contained content.xml stream
+	 * @param templatePath path inside the filesystem to an XSL template file
+	 * @throws TransformerConfigurationException
+	 * @throws TransformerException
+	 * @throws IOException
+	 * @throws IllegalArgumentException
+	 * @throws SAXException
+	 * @throws ParserConfigurationException
+	 */
+	public void transform(OdfPackage pkg, String path, String templatePath)
+			throws TransformerConfigurationException, TransformerException,
+			IOException, IllegalArgumentException, SAXException, ParserConfigurationException {
+		transform(pkg, path, new File(templatePath));
+	}
+
+	/**
+	 * Do XSL-Transformation on content contained in package
+	 * @param pkg a OdfPackage
+	 * @param path a path inside the OdfPackage, eg. to a contained content.xml stream
+	 * @param template File containing an XSLT Template
+	 * @param out File for the XSLT ouput
+	 * @throws TransformerConfigurationException
+	 * @throws TransformerException
+	 * @throws IOException
+	 * @throws IllegalArgumentException
+	 * @throws SAXException
+	 * @throws ParserConfigurationException
+	 */
+	public void transform(OdfPackage pkg, String path, File template, File out)
+			throws TransformerConfigurationException, TransformerException,
+			IOException, IllegalArgumentException, SAXException, ParserConfigurationException {
+
+		TransformerFactory transformerfactory = TransformerFactory.newInstance();
+
+		Templates templates = transformerfactory.newTemplates(new StreamSource(template));
+		transform(pkg, path, templates, new StreamResult(out));
+	}
+
+	/**
+	 * Do XSL-Transformation on content contained in package
+	 * insert result back to package
+	 * @param pkg a OdfPackage
+	 * @param path a path inside the OdfPackage, eg. to a contained content.xml stream
+	 * @param template a File containing an XSLT Template
+	 * @throws TransformerConfigurationException
+	 * @throws TransformerException
+	 * @throws IOException
+	 * @throws IllegalArgumentException
+	 * @throws SAXException
+	 * @throws ParserConfigurationException
+	 */
+	public void transform(OdfPackage pkg, String path, File template)
+			throws TransformerConfigurationException, TransformerException,
+			IOException, IllegalArgumentException, SAXException, ParserConfigurationException {
+
+		TransformerFactory transformerfactory = TransformerFactory.newInstance();
+
+		Templates templates = transformerfactory.newTemplates(new StreamSource(template));
+		transform(pkg, path, templates);
+	}
+
+	/**
+	 * Do XSL-Transformation on content contained in package
+	 * @param pkg a OdfPackage
+	 * @param path a path inside the OdfPackage, eg. to a contained content.xml stream
+	 * @param templateSource TraX Source of an XSLT Template
+	 * @param result TraX Result of XSL-Tranformation
+	 * @throws TransformerConfigurationException
+	 * @throws TransformerException
+	 * @throws IOException
+	 * @throws IllegalArgumentException
+	 * @throws SAXException
+	 * @throws ParserConfigurationException
+	 */
+	public void transform(OdfPackage pkg, String path, Source templateSource, Result result)
+			throws TransformerConfigurationException, TransformerException,
+			IOException, IllegalArgumentException, SAXException,
+			ParserConfigurationException {
+		TransformerFactory transformerfactory = TransformerFactory.newInstance();
+		transformerfactory.setURIResolver(pkg.getURIResolver());
+
+		Templates templates = transformerfactory.newTemplates(templateSource);
+		transform(pkg, path, templates, result);
+	}
+
+	/**
+	 * Does an XSL-Transformation on content contained in package.<br/><br/>
+	 *
+	 * There are three default parameters provided to the transformation:
+	 * There are three default parameters provided to the transformation:
+	 * <ol>
+	 * <li><b>sourceURL:</b> the URL of the source directory </li>
+	 * <li><b>sourceBaseURL:</b> baseURL of the source file (the package).
+	 * This URL necessary to access any content within the package from the XSLT scripts.
+	 * The relative package path will concatenated after the 'sourceBaseURL'.</li>
+	 * <li><b>targetURL:</b> the URL of the target directory</li>
+	 * <li><b>targetBaseURL:</b>the baseURL of the target file</li>
+	 * </ol>
+	 *
+	 * @param pkg a OdfPackage
+	 * @param path a path inside the OdfPackage, eg. to a contained content.xml stream
+	 * @param templates TraX XSLT Template
+	 * @param result TraX XSLT Result
+	 * @throws TransformerConfigurationException
+	 * @throws TransformerException
+	 * @throws IOException
+	 * @throws IllegalArgumentException
+	 * @throws SAXException
+	 * @throws ParserConfigurationException
+	 */
+	public void transform(OdfPackage pkg, String path, Templates templates, Result result)
+			throws TransformerConfigurationException, TransformerException,
+			IOException, IllegalArgumentException, SAXException,
+			ParserConfigurationException {
+		try {
+
+			Source source = null;
+			String uri = pkg.getBaseURI() + path;
+			Document doc = pkg.getDom(path);
+			source = new DOMSource(doc);
+			Transformer transformer = templates.newTransformer();
+			transformer.setURIResolver(pkg.getURIResolver());
+
+			transformer.setParameter("sourceURL", uri);
+			// switch to this, for odf2rdf.xsl grddl transformation
+			transformer.setParameter("sourceBaseURL", Util.getRDFBaseUri(pkg.getBaseURI(), path));
+
+			uri = result.getSystemId();
+			if (uri != null) {
+				transformer.setParameter("targetURL", uri);
+				int i = uri.lastIndexOf('/');
+				if (i > 0) {
+					uri = uri.substring(0, i + 1);
+					transformer.setParameter("targetBaseURL", uri);
+				}
+			}
+			DocumentType doctype = doc.getDoctype();
+			if (doctype != null) {
+				if (doctype.getPublicId() != null) {
+					transformer.setParameter("publicType", doctype.getPublicId());
+				}
+				if (doctype.getSystemId() != null) {
+					transformer.setParameter("systemType", doctype.getSystemId());
+				}
+			}
+
+			transformer.transform(source, result);
+		} catch (Exception ex) {
+			Logger.getLogger(OdfXMLHelper.class.getName()).log(Level.SEVERE, ex.getMessage(), ex);
+		}
+	}
+
+	/**
+	 * Do XSL-Transformation on content contained in package
+	 * and insert result back to package
+	 * @param pkg a OdfPackage
+	 * @param path a path inside the OdfPackage, eg. to a contained content.xml stream
+	 * @param templates Trax XSLT Template
+	 * @throws TransformerConfigurationException
+	 * @throws TransformerException
+	 * @throws IOException
+	 * @throws IllegalArgumentException
+	 * @throws SAXException
+	 * @throws ParserConfigurationException
+	 */
+	public void transform(OdfPackage pkg, String path, Templates templates)
+			throws TransformerConfigurationException, TransformerException,
+			IOException, IllegalArgumentException, SAXException, ParserConfigurationException {
+
+		Result result = null;
+		ByteArrayOutputStream baos = null;
+
+//		if (pkg.isDomCached(path)) {
+//			result = new DOMResult();
+//		} else {
+			baos = new ByteArrayOutputStream();
+			result = new StreamResult(baos);
+//		}
+
+		transform(pkg, path, templates, result);
+
+//		if (pkg.isDomCached(path)) {
+//			try {
+//				pkg.insert((Document) ((DOMResult) result).getNode(), path, null);
+//			} catch (Exception ex) {
+//				Logger.getLogger(OdfXMLHelper.class.getName()).log(Level.SEVERE, null, ex);
+//			}
+//		} else {
+			try {
+				byte[] data = baos.toByteArray();
+				pkg.insert(data, path, "text/xml");
+			} catch (Exception ex) {
+				Logger.getLogger(OdfXMLHelper.class.getName()).log(Level.SEVERE, null, ex);
+			}
+//		}
+
+	}
+}
+

Added: incubator/odf/trunk/odfdom/src/main/java/org/odftoolkit/odfdom/pkg/manifest/OdfManifestDom.java
URL: http://svn.apache.org/viewvc/incubator/odf/trunk/odfdom/src/main/java/org/odftoolkit/odfdom/pkg/manifest/OdfManifestDom.java?rev=1418326&view=auto
==============================================================================
--- incubator/odf/trunk/odfdom/src/main/java/org/odftoolkit/odfdom/pkg/manifest/OdfManifestDom.java (added)
+++ incubator/odf/trunk/odfdom/src/main/java/org/odftoolkit/odfdom/pkg/manifest/OdfManifestDom.java Fri Dec  7 14:28:07 2012
@@ -0,0 +1,104 @@
+/************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
+ *
+ * Use is subject to license terms.
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ************************************************************************/
+package org.odftoolkit.odfdom.pkg.manifest;
+
+import javax.xml.xpath.XPath;
+import javax.xml.xpath.XPathFactory;
+
+import org.odftoolkit.odfdom.dom.OdfSchemaDocument;
+import org.odftoolkit.odfdom.pkg.OdfFileDom;
+import org.odftoolkit.odfdom.pkg.OdfPackage;
+
+/**
+ * The DOM representation of the ODF manifest.xml file of an ODF document.
+ * 
+ * @since 0.8.9
+ */
+public class OdfManifestDom extends OdfFileDom {
+	
+	private static final long serialVersionUID = 8149848234988627233L;
+	
+	/**
+	 * Creates the DOM representation of an XML file of an Odf document.
+	 * 
+	 * @param odfDocument
+	 *            the document the XML files belongs to
+	 * @param packagePath
+	 *            the internal package path to the XML file
+	 */
+	public OdfManifestDom(OdfSchemaDocument odfDocument, String packagePath) {
+		super(odfDocument, packagePath);
+	}
+	
+	/**
+	 * Creates the DOM representation of an XML file of an Odf document.
+	 * 
+	 * @param pkg
+	 *            the package the XML files belongs to
+	 * @param packagePath
+	 *            the internal package path to the XML file
+	 */
+	public OdfManifestDom(OdfPackage pkg, String packagePath) {
+		super(pkg, packagePath);
+	}
+	
+	/**
+	 * Might be used to initialize specific XML Namespace prefixes/URIs for this
+	 * XML file
+	 */
+	@Override
+	protected void initialize() {
+		mUriByPrefix.put("manifest", "urn:oasis:names:tc:opendocument:xmlns:manifest:1.0");
+		mPrefixByUri.put("urn:oasis:names:tc:opendocument:xmlns:manifest:1.0", "manifest");
+		super.initialize();
+	}
+	
+	/**
+	 * @return The root element <manifest:manifest > of the manifest.xml file as
+	 *         <code>ManifestElement</code>.
+	 */
+	@Override
+	public ManifestElement getRootElement() {
+		return (ManifestElement) getDocumentElement();
+	}
+	
+	/**
+	 * Creates an JDK <code>XPath</code> instance. Initialized with ODF
+	 * namespaces from <code>OdfDocumentNamespace</code>. Updated with all
+	 * namespace of the XML file.
+	 * 
+	 * @return an XPath instance with namespace context set to include the
+	 *         standard ODFDOM prefixes.
+	 */
+	@Override
+	public XPath getXPath() {
+		if (mXPath == null) {
+			mXPath = XPathFactory.newInstance().newXPath();
+			mXPath.setNamespaceContext(this);
+			mUriByPrefix.put("manifest", "urn:oasis:names:tc:opendocument:xmlns:manifest:1.0");
+			mPrefixByUri.put("urn:oasis:names:tc:opendocument:xmlns:manifest:1.0", "manifest");
+		}
+		return mXPath;
+	}
+}
\ No newline at end of file

Added: incubator/odf/trunk/odfdom/src/main/java/org/odftoolkit/odfdom/pkg/rdfa/DOMAttributes.java
URL: http://svn.apache.org/viewvc/incubator/odf/trunk/odfdom/src/main/java/org/odftoolkit/odfdom/pkg/rdfa/DOMAttributes.java?rev=1418326&view=auto
==============================================================================
--- incubator/odf/trunk/odfdom/src/main/java/org/odftoolkit/odfdom/pkg/rdfa/DOMAttributes.java (added)
+++ incubator/odf/trunk/odfdom/src/main/java/org/odftoolkit/odfdom/pkg/rdfa/DOMAttributes.java Fri Dec  7 14:28:07 2012
@@ -0,0 +1,92 @@
+/************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
+ * 
+ * Copyright 2008, 2010 Oracle and/or its affiliates. All rights reserved.
+ * 
+ * Use is subject to license terms.
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License. You may obtain a copy
+ * of the License at http://www.apache.org/licenses/LICENSE-2.0. You can also
+ * obtain a copy of the License at http://odftoolkit.org/docs/license.txt
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * 
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ************************************************************************/
+package org.odftoolkit.odfdom.pkg.rdfa;
+
+import org.w3c.dom.NamedNodeMap;
+import org.xml.sax.Attributes;
+
+/**
+ * Simple wrapper class for NamedNodeMap as Attributes
+ */
+public class DOMAttributes implements Attributes{
+	
+	private NamedNodeMap attributes;
+
+	/**
+	 * Class constructor
+	 * 
+	 * @param attributes
+	 */
+	public DOMAttributes(NamedNodeMap attributes) {
+		this.attributes = attributes;
+	}
+	
+
+	public int getLength() {
+		return attributes.getLength();
+	}
+
+	public String getURI(int index) {
+		return attributes.item(index).getNamespaceURI();
+	}
+
+	public String getLocalName(int index) {
+		return attributes.item(index).getLocalName();
+	}
+
+	public String getQName(int index) {
+		return attributes.item(index).getNodeName();
+	}
+
+	public String getType(int index) {
+		throw new RuntimeException("DOMAttributes.getType() is not supported");
+	}
+
+	public String getValue(int index) {
+		return attributes.item(index).getNodeValue();
+	}
+
+	public int getIndex(String uri, String localName) {
+		throw new RuntimeException("DOMAttributes.getIndex(String uri, String localName) is not supported");
+	}
+
+	public int getIndex(String qName) {
+		throw new RuntimeException("DOMAttributes.getIndex(String qName) is not supported");
+	}
+
+	public String getType(String uri, String localName) {
+		throw new RuntimeException("DOMAttributes.getType(String uri, String localName) is not supported");
+	}
+
+	public String getType(String qName) {
+		throw new RuntimeException("DOMAttributes.getType(String qName) is not supported");
+	}
+
+	public String getValue(String uri, String localName) {
+		throw new RuntimeException("DOMAttributes.getValue(String uri, String localName) is not supported");
+	}
+
+	public String getValue(String qName) {
+		throw new RuntimeException("DOMAttributes.getValue(String qName) is not supported");
+	}
+
+}

Added: incubator/odf/trunk/odfdom/src/main/java/org/odftoolkit/odfdom/pkg/rdfa/DOMRDFaParser.java
URL: http://svn.apache.org/viewvc/incubator/odf/trunk/odfdom/src/main/java/org/odftoolkit/odfdom/pkg/rdfa/DOMRDFaParser.java?rev=1418326&view=auto
==============================================================================
--- incubator/odf/trunk/odfdom/src/main/java/org/odftoolkit/odfdom/pkg/rdfa/DOMRDFaParser.java (added)
+++ incubator/odf/trunk/odfdom/src/main/java/org/odftoolkit/odfdom/pkg/rdfa/DOMRDFaParser.java Fri Dec  7 14:28:07 2012
@@ -0,0 +1,92 @@
+/************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
+ * 
+ * Copyright 2008, 2010 Oracle and/or its affiliates. All rights reserved.
+ * 
+ * Use is subject to license terms.
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License. You may obtain a copy
+ * of the License at http://www.apache.org/licenses/LICENSE-2.0. You can also
+ * obtain a copy of the License at http://odftoolkit.org/docs/license.txt
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * 
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ************************************************************************/
+package org.odftoolkit.odfdom.pkg.rdfa;
+
+import javax.xml.stream.XMLEventFactory;
+import javax.xml.stream.XMLOutputFactory;
+
+import org.odftoolkit.odfdom.dom.element.text.TextBookmarkStartElement;
+import org.w3c.dom.Node;
+
+/**
+ * A RDFa parser for DOM
+ * 
+ */
+public class DOMRDFaParser extends RDFaParser {
+
+	public static DOMRDFaParser createInstance(JenaSink sink) {
+		sink.getExtractor().setForSAX(false);
+		return new DOMRDFaParser(sink, XMLOutputFactory.newInstance(),
+				XMLEventFactory.newInstance(), sink.getExtractor());
+	}
+
+	public DOMRDFaParser(JenaSink sink, XMLOutputFactory outputFactory,
+			XMLEventFactory eventFactory, URIExtractor extractor) {
+		super(sink, outputFactory, eventFactory, extractor);
+
+	}
+
+	/**
+	 * Parse the RDFa in-content metadata of the node.
+	 * 
+	 * @param node
+	 */
+	public void parse(Node node) {
+		process(node);
+	}
+
+	private void process(Node node) {
+
+		switch (node.getNodeType()) {
+		case Node.ELEMENT_NODE:
+			if (!(node instanceof TextBookmarkStartElement)) {
+				sink.setContextNode(node);
+			}
+			// Start element
+			beginRDFaElement(node.getNamespaceURI(), node.getLocalName(),
+					node.getNodeName(), new DOMAttributes(node.getAttributes()));
+			// Recurse to child
+//			if (node.hasChildNodes() == true) {
+//				process(node.getFirstChild());
+//			}
+			if (node.hasChildNodes() == true) {
+				Node n = node.getFirstChild();
+				process(n);
+				while (n.getNextSibling()!=null){
+					process(n.getNextSibling());
+					n= n.getNextSibling();
+				}
+			}
+
+			// End element
+			endRDFaElement(node.getNamespaceURI(), node.getLocalName(),
+					node.getNodeName());
+			break;
+		case Node.CDATA_SECTION_NODE:
+		case Node.TEXT_NODE:
+			// Text or CDATA
+			writeCharacters(node.getNodeValue());
+			break;
+		}
+
+	}
+}

Added: incubator/odf/trunk/odfdom/src/main/java/org/odftoolkit/odfdom/pkg/rdfa/EvalContext.java
URL: http://svn.apache.org/viewvc/incubator/odf/trunk/odfdom/src/main/java/org/odftoolkit/odfdom/pkg/rdfa/EvalContext.java?rev=1418326&view=auto
==============================================================================
--- incubator/odf/trunk/odfdom/src/main/java/org/odftoolkit/odfdom/pkg/rdfa/EvalContext.java (added)
+++ incubator/odf/trunk/odfdom/src/main/java/org/odftoolkit/odfdom/pkg/rdfa/EvalContext.java Fri Dec  7 14:28:07 2012
@@ -0,0 +1,198 @@
+/************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
+ * 
+ * Copyright 2008, 2010 Oracle and/or its affiliates. All rights reserved.
+ * 
+ * Use is subject to license terms.
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License. You may obtain a copy
+ * of the License at http://www.apache.org/licenses/LICENSE-2.0. You can also
+ * obtain a copy of the License at http://odftoolkit.org/docs/license.txt
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * 
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ************************************************************************/
+package org.odftoolkit.odfdom.pkg.rdfa;
+
+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;
+
+/**
+ * EvalContext modified from net.rootdev.javardfa.EvalContext
+ */
+final class EvalContext implements NamespaceContext {
+
+    EvalContext parent;
+    String base;
+    String parentSubject;
+    String parentObject;
+    String language;
+    String vocab;
+    List<String> forwardProperties;
+    List<String> backwardProperties;
+    Map<String, String> xmlnsMap = Collections.EMPTY_MAP;
+    Map<String, String> prefixMap = Collections.EMPTY_MAP;
+
+    protected EvalContext(String base) {
+        super();
+        this.base = base;
+        this.parentSubject = base;
+        this.forwardProperties = new LinkedList<String>();
+        this.backwardProperties = new LinkedList<String>();
+    }
+
+    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<String>(toCopy.forwardProperties);
+        this.backwardProperties = new LinkedList<String>(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<String, String>();
+        prefixMap.put(prefix, uri);
+    }
+
+    /**
+     * 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<String, String>();
+        xmlnsMap.put(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;
+        }
+    }
+
+    public String getPrefix(String uri) {
+        throw new UnsupportedOperationException("Not supported yet.");
+    }
+
+    public Iterator getPrefixes(String uri) {
+        throw new UnsupportedOperationException("Not supported yet.");
+    }
+    
+    // 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;
+    }
+}
+
+/*
+ * (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.
+ */
+

Added: incubator/odf/trunk/odfdom/src/main/java/org/odftoolkit/odfdom/pkg/rdfa/JenaSink.java
URL: http://svn.apache.org/viewvc/incubator/odf/trunk/odfdom/src/main/java/org/odftoolkit/odfdom/pkg/rdfa/JenaSink.java?rev=1418326&view=auto
==============================================================================
--- incubator/odf/trunk/odfdom/src/main/java/org/odftoolkit/odfdom/pkg/rdfa/JenaSink.java (added)
+++ incubator/odf/trunk/odfdom/src/main/java/org/odftoolkit/odfdom/pkg/rdfa/JenaSink.java Fri Dec  7 14:28:07 2012
@@ -0,0 +1,165 @@
+/************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
+ * 
+ * Copyright 2008, 2010 Oracle and/or its affiliates. All rights reserved.
+ * 
+ * Use is subject to license terms.
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License. You may obtain a copy
+ * of the License at http://www.apache.org/licenses/LICENSE-2.0. You can also
+ * obtain a copy of the License at http://odftoolkit.org/docs/license.txt
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * 
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ************************************************************************/
+package org.odftoolkit.odfdom.pkg.rdfa;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+
+import net.rootdev.javardfa.StatementSink;
+
+import org.odftoolkit.odfdom.pkg.OdfFileDom;
+import org.odftoolkit.odfdom.pkg.OdfFileSaxHandler;
+import org.w3c.dom.Node;
+
+import com.hp.hpl.jena.rdf.model.Literal;
+import com.hp.hpl.jena.rdf.model.Model;
+import com.hp.hpl.jena.rdf.model.ModelFactory;
+import com.hp.hpl.jena.rdf.model.Property;
+import com.hp.hpl.jena.rdf.model.Resource;
+import com.hp.hpl.jena.shared.PrefixMapping.IllegalPrefixException;
+
+/**
+ * To cache the Jena RDF triples parsed from RDFaParser
+ *
+ */
+public class JenaSink implements StatementSink {
+
+//	private OdfFileSaxHandler odf;
+	private Node contextNode;
+	private OdfFileDom mFileDom;
+    private Map<String, Resource> bnodeLookup;
+    private URIExtractor extractor;
+    private EvalContext context;
+
+    public JenaSink(OdfFileDom mFileDom) {
+		this.mFileDom = mFileDom;
+		this.bnodeLookup = new HashMap<String, Resource>();
+    }
+
+    //@Override
+    public void start() {
+        bnodeLookup = new HashMap<String, Resource>();
+    }
+
+    //@Override
+    public void end() {
+        bnodeLookup = null;
+    }
+
+    //@Override
+    public void addObject(String subject, String predicate, String object) {
+    	Model model =getContextModel();
+        Resource s = getResource(model, subject.trim());
+        Property p = model.createProperty(predicate.trim());
+        Resource o = getResource(model, object.trim());
+        model.add(s, p, o);
+    }
+
+    //@Override
+    public void addLiteral(String subject, String predicate, String lex, String lang, String datatype) {
+    	if (lex.isEmpty()){
+    		return;
+    	}
+    	Model model =getContextModel();
+    	Resource s = getResource(model, subject.trim());
+        Property p = model.createProperty(predicate.trim());
+        Literal o;
+        if (lang == null && datatype == null) {
+            o = model.createLiteral(lex.trim());
+        } else if (lang != null) {
+            o = model.createLiteral(lex.trim(), lang.trim());
+        } else {
+            o = model.createTypedLiteral(lex.trim(), datatype.trim());
+        }
+        model.add(s, p, o);
+    }
+
+    private Resource getResource(Model model, 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) {
+//    	Model model =getContextModel();
+//        try {
+//            model.setNsPrefix(prefix.trim(), uri.trim());
+//        } catch (IllegalPrefixException e) {
+//        }
+    }
+
+    public void setBase(String base) {}
+    
+	private Model getContextModel() {
+		Map<Node, Model> cache = this.mFileDom.getInContentMetadataCache();
+		Model model = cache.get(contextNode);
+		if (model == null) {
+			model = ModelFactory.createDefaultModel();
+			this.mFileDom.getInContentMetadataCache().put(
+					contextNode, model);
+		}
+		return model;
+	}
+
+	public Node getContextNode() {
+		return contextNode;
+	}
+
+	public void setContextNode(Node contextNode) {
+		this.contextNode = contextNode;
+	}
+
+	public URIExtractor getExtractor() {
+		return extractor;
+	}
+
+	public void setExtractor(URIExtractor extractor) {
+		this.extractor = extractor;
+	}
+
+	public EvalContext getContext() {
+		return context;
+	}
+
+	public void setContext(EvalContext context) {
+		this.context = context;
+	}
+		
+	
+//    // Namespace methods
+//    public void setNamespaceURI(String prefix, String uri) {
+//        if (uri.length() == 0) {
+//            uri = base;
+//        }
+//        if (xmlnsMap == Collections.EMPTY_MAP) xmlnsMap = new HashMap<String, String>();
+//        xmlnsMap.put(prefix, uri);
+//    }
+
+}

Added: incubator/odf/trunk/odfdom/src/main/java/org/odftoolkit/odfdom/pkg/rdfa/MultiContentHandler.java
URL: http://svn.apache.org/viewvc/incubator/odf/trunk/odfdom/src/main/java/org/odftoolkit/odfdom/pkg/rdfa/MultiContentHandler.java?rev=1418326&view=auto
==============================================================================
--- incubator/odf/trunk/odfdom/src/main/java/org/odftoolkit/odfdom/pkg/rdfa/MultiContentHandler.java (added)
+++ incubator/odf/trunk/odfdom/src/main/java/org/odftoolkit/odfdom/pkg/rdfa/MultiContentHandler.java Fri Dec  7 14:28:07 2012
@@ -0,0 +1,124 @@
+/************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
+ * 
+ * Copyright 2008, 2010 Oracle and/or its affiliates. All rights reserved.
+ * 
+ * Use is subject to license terms.
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License. You may obtain a copy
+ * of the License at http://www.apache.org/licenses/LICENSE-2.0. You can also
+ * obtain a copy of the License at http://odftoolkit.org/docs/license.txt
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * 
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ************************************************************************/
+package org.odftoolkit.odfdom.pkg.rdfa;
+
+import java.util.ArrayList;
+
+import org.xml.sax.Attributes;
+import org.xml.sax.ContentHandler;
+import org.xml.sax.Locator;
+import org.xml.sax.SAXException;
+
+/**
+ * A proxy for delegating the parsing events to its sub ContentHandler(s).
+ */
+public class MultiContentHandler implements ContentHandler {
+	ArrayList<ContentHandler> subContentHandlers;
+
+	public MultiContentHandler(ContentHandler... subs ) {
+		subContentHandlers = new ArrayList<ContentHandler>();
+		for(ContentHandler sub : subs){
+			subContentHandlers.add(sub);
+		}
+	}
+
+	public void setDocumentLocator(Locator locator) {
+		for(ContentHandler sub: subContentHandlers){
+			sub.setDocumentLocator(locator);
+		}
+
+	}
+
+	public void startDocument() throws SAXException {
+		for(ContentHandler sub: subContentHandlers){
+			sub.startDocument();
+		}
+
+	}
+
+	public void endDocument() throws SAXException {
+		for(ContentHandler sub: subContentHandlers){
+			sub.endDocument();
+		}
+
+	}
+
+	public void startPrefixMapping(String prefix, String uri)
+			throws SAXException {
+		for(ContentHandler sub: subContentHandlers){
+			sub.startPrefixMapping(prefix, uri);
+		}
+
+	}
+
+	public void endPrefixMapping(String prefix) throws SAXException {
+		for(ContentHandler sub: subContentHandlers){
+			sub.endPrefixMapping(prefix);
+		}
+
+	}
+
+	public void startElement(String uri, String localName, String qName,
+			Attributes atts) throws SAXException {
+		for(ContentHandler sub: subContentHandlers){
+			sub.startElement(uri, localName, qName, atts);
+		}
+	}
+
+	public void endElement(String uri, String localName, String qName)
+			throws SAXException {
+		for(ContentHandler sub: subContentHandlers){
+			sub.endElement(uri, localName, qName);
+		}
+
+	}
+
+	public void characters(char[] ch, int start, int length)
+			throws SAXException {
+		for(ContentHandler sub: subContentHandlers){
+			sub.characters(ch, start, length);
+		}
+
+	}
+
+	public void ignorableWhitespace(char[] ch, int start, int length)
+			throws SAXException {
+		for(ContentHandler sub: subContentHandlers){
+			sub.ignorableWhitespace(ch, start, length);
+		}
+
+	}
+
+	public void processingInstruction(String target, String data)
+			throws SAXException {
+		for(ContentHandler sub: subContentHandlers){
+			sub.processingInstruction(target, data);
+		}
+	}
+
+	public void skippedEntity(String name) throws SAXException {
+		for(ContentHandler sub: subContentHandlers){
+			sub.skippedEntity(name);
+		}
+	}
+
+}

Added: incubator/odf/trunk/odfdom/src/main/java/org/odftoolkit/odfdom/pkg/rdfa/RDFaParser.java
URL: http://svn.apache.org/viewvc/incubator/odf/trunk/odfdom/src/main/java/org/odftoolkit/odfdom/pkg/rdfa/RDFaParser.java?rev=1418326&view=auto
==============================================================================
--- incubator/odf/trunk/odfdom/src/main/java/org/odftoolkit/odfdom/pkg/rdfa/RDFaParser.java (added)
+++ incubator/odf/trunk/odfdom/src/main/java/org/odftoolkit/odfdom/pkg/rdfa/RDFaParser.java Fri Dec  7 14:28:07 2012
@@ -0,0 +1,443 @@
+/************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
+ * 
+ * Copyright 2008, 2010 Oracle and/or its affiliates. All rights reserved.
+ * 
+ * Use is subject to license terms.
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License. You may obtain a copy
+ * of the License at http://www.apache.org/licenses/LICENSE-2.0. You can also
+ * obtain a copy of the License at http://odftoolkit.org/docs/license.txt
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * 
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ************************************************************************/
+package org.odftoolkit.odfdom.pkg.rdfa;
+
+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 net.rootdev.javardfa.Constants;
+import net.rootdev.javardfa.Setting;
+import net.rootdev.javardfa.literal.LiteralCollector;
+
+import org.xml.sax.Attributes;
+import org.xml.sax.Locator;
+
+/**
+ * A RDFa Parser modified from net.rootdev.javardfa.Parser
+ *
+ */
+class RDFaParser extends net.rootdev.javardfa.Parser {
+	
+	boolean ignore = false;
+
+	protected XMLEventFactory eventFactory;
+	protected JenaSink sink;
+	protected Set<Setting> settings;
+	protected LiteralCollector literalCollector;
+	protected URIExtractor extractor;
+	protected Locator locator;
+	protected EvalContext context;
+
+	protected RDFaParser(JenaSink sink, XMLOutputFactory outputFactory,
+			XMLEventFactory eventFactory, URIExtractor extractor) {
+		super(sink);
+		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);
+	}
+
+	protected void beginRDFaElement(String arg0, String localname,
+			String qname, Attributes arg3) {
+		if (localname.equals("bookmark-start")) {
+			ignore = true;
+			return;
+		}
+		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);
+		}
+	}
+	
+	protected void endRDFaElement(String arg0, String localname, String qname) {
+		if (localname.equals("bookmark-start")) {
+			ignore = false;
+			return;
+		}
+		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;
+	}
+	
+	protected void writeCharacters(String value) {
+		if (!ignore) {
+			if (literalCollector.isCollecting()) {
+				XMLEvent e = eventFactory.createCharacters(value);
+				literalCollector.handleEvent(e);
+			}
+		}
+	}
+	
+	/** 
+	 * Set the base uri of the DOM.
+	 */
+	public void setBase(String base) {	
+		this.context = new EvalContext(base);
+		sink.setBase(context.getBase());
+	}
+
+	protected EvalContext parse(EvalContext context, StartElement element)
+			throws XMLStreamException {
+		boolean skipElement = false;
+		String newSubject = null;
+		String currentObject = null;
+		List<String> forwardProperties = new LinkedList();
+		List<String> backwardProperties = new LinkedList();
+		String currentLanguage = context.language;
+
+		if (settings.contains(Setting.OnePointOne)) {
+
+			if (getAttributeByName(element, Constants.vocab) != null) {
+				context.vocab = getAttributeByName(element, Constants.vocab)
+						.getValue().trim();
+			}
+
+			if (getAttributeByName(element, Constants.prefix) != null) {
+				parsePrefixes(getAttributeByName(element, Constants.prefix)
+						.getValue(), context);
+			}
+		}
+
+		// 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 (getAttributeByName(element, Constants.xmllang) != null) {
+				currentLanguage = getAttributeByName(element, Constants.xmllang)
+						.getValue();
+				if (currentLanguage.length() == 0)
+					currentLanguage = null;
+			} else if (getAttributeByName(element, Constants.lang) != null) {
+				currentLanguage = getAttributeByName(element, Constants.lang)
+						.getValue();
+				if (currentLanguage.length() == 0)
+					currentLanguage = null;
+			}
+		} else if (getAttributeByName(element, Constants.xmllangNS) != null) {
+			currentLanguage = getAttributeByName(element, Constants.xmllangNS)
+					.getValue();
+			if (currentLanguage.length() == 0)
+				currentLanguage = null;
+		}
+
+		if (Constants.base.equals(element.getName())
+				&& getAttributeByName(element, Constants.href) != null) {
+			context.setBase(getAttributeByName(element, Constants.href)
+					.getValue());
+			sink.setBase(context.getBase());
+		}
+		if (getAttributeByName(element, Constants.rev) == null
+				&& getAttributeByName(element, Constants.rel) == null) {
+			Attribute nSubj = findAttribute(element, Constants.about);	
+			if (nSubj != null) {
+				newSubject = extractor.getURI(element, nSubj, context);
+			}
+			if (newSubject == null) {
+				if (Constants.body.equals(element.getName())
+						|| Constants.head.equals(element.getName())) {
+					newSubject = context.base;
+				} else if (getAttributeByName(element, Constants.typeof) != null) {
+					newSubject = createBNode();
+				} else {
+					if (context.parentObject != null) {
+						newSubject = context.parentObject;
+					}
+					if (getAttributeByName(element, Constants.property) == null) {
+						skipElement = true;
+					}
+				}
+			}
+		} else {
+			Attribute nSubj = findAttribute(element, Constants.about,
+					Constants.src);
+			if (nSubj != null) {
+				newSubject = extractor.getURI(element, nSubj, context);
+			}
+			if (newSubject == null) {
+				// if element is head or body assume about=""
+				if (Constants.head.equals(element.getName())
+						|| Constants.body.equals(element.getName())) {
+					newSubject = context.base;
+				} else if (getAttributeByName(element, Constants.typeof) != null) {
+					newSubject = createBNode();
+				} else if (context.parentObject != null) {
+					newSubject = context.parentObject;
+				}
+			}
+			Attribute cObj = findAttribute(element, Constants.resource,
+					Constants.href);
+			if (cObj != null) {
+				currentObject = extractor.getURI(element, cObj, context);
+			}
+		}
+
+		if (newSubject != null
+				&& getAttributeByName(element, Constants.typeof) != null) {
+			List<String> types = extractor.getURIs(element,
+					getAttributeByName(element, Constants.typeof), context);
+			for (String type : types) {
+				emitTriples(newSubject, Constants.rdfType, type);
+			}
+		}
+
+
+		if (currentObject != null) {
+			if (getAttributeByName(element, Constants.rel) != null) {
+				emitTriples(newSubject, extractor.getURIs(element,
+						getAttributeByName(element, Constants.rel), context),
+						currentObject);
+			}
+			if (getAttributeByName(element, Constants.rev) != null) {
+				emitTriples(currentObject, extractor.getURIs(element,
+						getAttributeByName(element, Constants.rev), context),
+						newSubject);
+			}
+		} else {
+			if (getAttributeByName(element, Constants.rel) != null) {
+				forwardProperties.addAll(extractor.getURIs(element,
+						getAttributeByName(element, Constants.rel), context));
+			}
+			if (getAttributeByName(element, Constants.rev) != null) {
+				backwardProperties.addAll(extractor.getURIs(element,
+						getAttributeByName(element, Constants.rev), context));
+			}
+			if (!forwardProperties.isEmpty() || !backwardProperties.isEmpty()) {
+				// if predicate present
+				currentObject = createBNode();
+			}
+		}
+
+		// Getting literal values. Complicated!
+		if (getAttributeByName(element, Constants.property) != null) {
+			List<String> props = extractor.getURIs(element,
+					getAttributeByName(element, Constants.property), context);
+			String dt = getDatatype(element);
+			if (getAttributeByName(element, Constants.content) != null) { // The
+																			// easy
+																			// bit
+				String lex = getAttributeByName(element, Constants.content)
+						.getValue();
+				if (dt == null || dt.length() == 0) {
+					emitTriplesPlainLiteral(newSubject, props, lex,
+							currentLanguage);
+				} else {
+					emitTriplesDatatypeLiteral(newSubject, props, lex, dt);
+				}
+			} else {
+				literalCollector
+						.collect(newSubject, props, dt, currentLanguage);
+			}
+		}
+
+		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 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);
+				extractor.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);
+	}
+
+	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();
+	}
+
+	private Attribute findAttribute(StartElement element, QName... names) {
+		for (QName aName : names) {
+			Attribute a = getAttributeByName(element, aName);
+			if (a != null) {
+				return a;
+			}
+		}
+		return null;
+	}
+
+	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]);
+			}
+		}
+	}
+
+	private Attribute getAttributeByName(StartElement element, QName name) {
+		if (name == null || element == null) {
+			return null;
+		}
+		Iterator it = element.getAttributes();
+		while (it.hasNext()) {
+			Attribute at = (Attribute) it.next();
+			if (Util.qNameEquals(at.getName(), name)) {
+				return at;
+			}
+		}
+		return null;
+	}
+
+	int bnodeId = 0;
+
+	private String createBNode() // TODO probably broken? Can you write bnodes
+									// in rdfa directly?
+	{
+		return "_:node" + (bnodeId++);
+	}
+
+	private String getDatatype(StartElement element) {
+		Attribute de = getAttributeByName(element, Constants.datatype);
+		if (de == null) {
+			return null;
+		}
+		String dt = de.getValue();
+		if (dt.length() == 0) {
+			return dt;
+		}
+		return extractor.expandCURIE(element, dt, context);
+	}
+}

Added: incubator/odf/trunk/odfdom/src/main/java/org/odftoolkit/odfdom/pkg/rdfa/SAXRDFaParser.java
URL: http://svn.apache.org/viewvc/incubator/odf/trunk/odfdom/src/main/java/org/odftoolkit/odfdom/pkg/rdfa/SAXRDFaParser.java?rev=1418326&view=auto
==============================================================================
--- incubator/odf/trunk/odfdom/src/main/java/org/odftoolkit/odfdom/pkg/rdfa/SAXRDFaParser.java (added)
+++ incubator/odf/trunk/odfdom/src/main/java/org/odftoolkit/odfdom/pkg/rdfa/SAXRDFaParser.java Fri Dec  7 14:28:07 2012
@@ -0,0 +1,169 @@
+/************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
+ * 
+ * Copyright 2008, 2010 Oracle and/or its affiliates. All rights reserved.
+ * 
+ * Use is subject to license terms.
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License. You may obtain a copy
+ * of the License at http://www.apache.org/licenses/LICENSE-2.0. You can also
+ * obtain a copy of the License at http://odftoolkit.org/docs/license.txt
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * 
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ************************************************************************/
+package org.odftoolkit.odfdom.pkg.rdfa;
+
+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.XMLConstants;
+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 net.rootdev.javardfa.Constants;
+import net.rootdev.javardfa.Setting;
+import net.rootdev.javardfa.StatementSink;
+import net.rootdev.javardfa.literal.LiteralCollector;
+import net.rootdev.javardfa.uri.IRIResolver;
+
+import org.xml.sax.Attributes;
+import org.xml.sax.Locator;
+import org.xml.sax.SAXException;
+
+/**
+ * A RDFa parser for SAX
+ */
+public class SAXRDFaParser extends RDFaParser {
+	
+
+	public static SAXRDFaParser createInstance(JenaSink sink) {
+		URIExtractor extractor = new URIExtractorImpl(new IRIResolver(), true);
+		sink.setExtractor(extractor);
+		return new SAXRDFaParser(sink, XMLOutputFactory.newInstance(),
+				XMLEventFactory.newInstance(), extractor);
+	}
+
+	private SAXRDFaParser(JenaSink sink, XMLOutputFactory outputFactory,
+			XMLEventFactory eventFactory, URIExtractor extractor) {
+		super(sink, outputFactory, eventFactory, extractor);
+	}
+
+	public void emitTriples(String subj, Collection<String> props, String obj) {
+		for (String prop : props) {
+			sink.addObject(subj, prop, obj);
+		}
+	}
+
+	public void emitTriplesPlainLiteral(String subj, Collection<String> props,
+			String lex, String language) {
+		for (String prop : props) {
+			sink.addLiteral(subj, prop, lex, language, null);
+		}
+	}
+
+	public void emitTriplesDatatypeLiteral(String subj,
+			Collection<String> props, String lex, String datatype) {
+		for (String prop : props) {
+			sink.addLiteral(subj, prop, lex, null, datatype);
+		}
+	}
+
+	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();
+		sink.setContext(context);
+	}
+
+	public void startPrefixMapping(String arg0, String arg1)
+			throws SAXException {
+		context.setNamespaceURI(arg0, arg1);
+		extractor.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 {
+		super.beginRDFaElement(arg0, localname, qname, arg3);
+	}
+
+	public void endElement(String arg0, String localname, String qname)
+			throws SAXException {
+		super.endRDFaElement(arg0, localname, qname);
+	}
+
+	public void characters(char[] arg0, int arg1, int arg2) throws SAXException {
+		super.writeCharacters(String.valueOf(arg0, arg1, arg2));
+	}
+
+	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 {
+	}
+
+}
+
+/*
+ * (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.
+ */

Added: incubator/odf/trunk/odfdom/src/main/java/org/odftoolkit/odfdom/pkg/rdfa/URIExtractor.java
URL: http://svn.apache.org/viewvc/incubator/odf/trunk/odfdom/src/main/java/org/odftoolkit/odfdom/pkg/rdfa/URIExtractor.java?rev=1418326&view=auto
==============================================================================
--- incubator/odf/trunk/odfdom/src/main/java/org/odftoolkit/odfdom/pkg/rdfa/URIExtractor.java (added)
+++ incubator/odf/trunk/odfdom/src/main/java/org/odftoolkit/odfdom/pkg/rdfa/URIExtractor.java Fri Dec  7 14:28:07 2012
@@ -0,0 +1,77 @@
+/************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
+ * 
+ * Copyright 2008, 2010 Oracle and/or its affiliates. All rights reserved.
+ * 
+ * Use is subject to license terms.
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License. You may obtain a copy
+ * of the License at http://www.apache.org/licenses/LICENSE-2.0. You can also
+ * obtain a copy of the License at http://odftoolkit.org/docs/license.txt
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * 
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ************************************************************************/
+package org.odftoolkit.odfdom.pkg.rdfa;
+
+import java.util.List;
+import java.util.Set;
+
+import javax.xml.stream.events.Attribute;
+import javax.xml.stream.events.StartElement;
+
+import net.rootdev.javardfa.Setting;
+/**
+ * URIExtractor modified from net.rootdev.javardfa.uri.URIExtractor
+ */
+public interface URIExtractor {
+
+    void setSettings(Set<Setting> settings);
+
+    String expandCURIE(StartElement element, String value, EvalContext context);
+
+    String expandSafeCURIE(StartElement element, String value, EvalContext context);
+
+    String getURI(StartElement element, Attribute attr, EvalContext context);
+
+    List<String> getURIs(StartElement element, Attribute attr, EvalContext context);
+
+    String resolveURI(String uri, EvalContext context);
+    
+    void setForSAX(boolean isForSAX);
+    
+    void setNamespaceURI(String prefix, String namespaceURI);
+}
+
+/*
+ * (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.
+ */
+



Mime
View raw message