001package org.dom4j.persistence.nativ; 002 003import java.net.URL; 004 005import org.dom4j.Node; 006import org.dom4j.Document; 007import org.dom4j.persistence.DocumentMarshalling; 008import org.dom4j.persistence.MarshallingContext; 009import org.dom4j.io.SAXContentHandler; 010import org.dom4j.io.SAXReader; 011import org.dom4j.io.SAXWriter; 012 013import org.xmldb.api.base.Database; 014import org.xmldb.api.DatabaseManager; 015import org.xmldb.api.base.*; 016import org.xmldb.api.modules.XMLResource; 017import org.xmldb.api.modules.SAXResource; 018import org.xmldb.api.modules.TransactionService; 019 020import org.xml.sax.*; 021import org.xml.sax.helpers.XMLReaderFactory; 022 023 024/** 025 * 026 * @author Tobias Rademacher 027 * @version 1.0 028 */ 029 030public class XMLDBStrategy extends DocumentMarshalling { 031 032 protected SAXContentHandler extractContent; 033 protected SAXWriter resolver; 034 protected MarshallingContext context; 035 protected TransactionService transactionService; 036 protected Collection collection; 037 038 public XMLDBStrategy(MarshallingContext context) throws IllegalAccessException, java.lang.InstantiationException { 039 this.context = context; 040 Database database = (Database) this.context.getDatabaseDriver().newInstance(); 041 this.collection = DatabaseManager.getCollection(this.context.getDatabaseLocation().toExternalForm()); 042 TransactionService transaction = 043 (TransactionService) this.collection.getService("TransactionService", "1.0"); 044 } 045 046 public void marshal(String aId, Node aNode) throws Exception { 047 this.resolve(aNode); 048 SAXResource resource = (SAXResource) this.collection.createResource(aId, "SAXResource"); 049 resource.setContentHandler(this.extractContent); 050 this.collection.storeResource(resource); 051 if(this.context.isAutoCommiting()) 052 transactionService.commit(); 053 } 054 055 public Node unmarshal(String systemId) { 056 XMLResource resource = (XMLResource) this.collection.getResource(systemId); 057 resource.getContentAsSAX(this.extractContent); 058 return this.extractContent.getDocument(); 059 } 060 061 protected void resolve(Node aNode) throws SAXException { 062 this.extractContent = new SAXContentHandler(); 063 this.resolver = new SAXWriter(this.extractContent); 064 this.resolver.write((Document)aNode); 065 } 066 067 public void setContext(MarshallingContext aContext) { 068 this.context = aContext; 069 } 070 071 072}