KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > ozoneDB > xml > cli > resources > XMLResourceImpl


1 // You can redistribute this software and/or modify it under the terms of
2
// the Ozone Library License version 1 published by ozone-db.org.
3
//
4
// The original code and portions created by SMB are
5
// Copyright (C) 1997-@year@ by SMB GmbH. All rights reserved.
6
//
7
// $Id: XMLResourceImpl.java,v 1.1 2003/11/22 19:29:51 per_nyfelt Exp $
8

9 package org.ozoneDB.xml.cli.resources;
10
11
12 import java.io.StringReader JavaDoc;
13 import java.io.StringWriter JavaDoc;
14
15 import org.ozoneDB.ExternalDatabase;
16 import org.ozoneDB.ExternalTransaction;
17 import org.ozoneDB.xml.util.XMLContainer;
18 import org.ozoneDB.xml.cli.CollectionImpl;
19
20 import org.w3c.dom.Node JavaDoc;
21 import org.w3c.dom.Document JavaDoc;
22 //import org.apache.xerces.parsers.SAXParser;
23
import javax.xml.parsers.SAXParser JavaDoc;
24 import org.xml.sax.helpers.ParserAdapter JavaDoc;
25 import org.xml.sax.ContentHandler JavaDoc;
26 import org.xml.sax.InputSource JavaDoc;
27 import org.xml.sax.SAXException JavaDoc;
28 //import org.xml.sax.helpers.XMLReaderFactory;
29
import javax.xml.parsers.SAXParserFactory JavaDoc;
30 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
31 import javax.xml.parsers.DocumentBuilder JavaDoc;
32
33 import org.xmldb.api.base.Collection;
34 import org.xmldb.api.base.ErrorCodes;
35 import org.xmldb.api.base.XMLDBException;
36 import org.xmldb.api.modules.XMLResource;
37
38 import org.apache.xml.serialize.XMLSerializer;
39 import org.apache.xml.serialize.OutputFormat;
40 import org.apache.log4j.Logger;
41
42 /**
43  * This is a database persistent XML class for XML:DB, possible of
44  * returning XML content back as DOM, SAX or String. Performance is
45  * best using DOM. Please note that getContent() is overridden to
46  * return a <code>String</code> back and can always be cast to a String.
47  *
48  * @author <a HREF="http://www.smb-tec.com">SMB</a>, Per Nyfelt
49  * @version $Revision: 1.1 $
50  */

51 public class XMLResourceImpl implements XMLResource {
52
53     private static final Logger logger = Logger.getLogger(XMLResourceImpl.class);
54     // the SAX parser we use in setContent
55
private final SAXParserFactory JavaDoc parserFactory = new org.apache.xerces.jaxp.SAXParserFactoryImpl();
56     private ExternalDatabase database;
57     // the XML document this class operates on
58
private XMLContainer container;
59     // the Collection this resource resides in
60
private Collection collection;
61     // since there is no setId() in the interface we have to get the id in the construction
62
private String JavaDoc id;
63
64
65     public XMLResourceImpl( String JavaDoc id, ExternalDatabase database, Collection collection,
66                                     XMLContainer container ) {
67         logger.debug("XMLResourceImpl CREATED ***********");
68         this.database = database;
69         this.container = container;
70         this.collection = collection;
71         this.id = id;
72
73     }
74
75    /**
76     * Returns the <code>Collection</code> instance that this resource is
77     * associated with.
78     *
79     * @return the collection associated with the resource.
80     */

81     public Collection getParentCollection() throws XMLDBException {
82         return collection;
83     }
84
85    /**
86     * Returns the unique id for this Resource or null if the resource has
87     * not yet been given one.
88     *
89     * @return the id for the Resource or null if no id exists.
90     */

91     public String JavaDoc getId() throws XMLDBException {
92         return id;
93     }
94
95    /**
96     * Sets the content of the <code>Resource</code> using a either a
97     * String or a DOM Node as the source.
98     *
99     * @param value The new content value
100     */

101     public void setContent( Object JavaDoc value ) throws XMLDBException {
102         if (value instanceof String JavaDoc) {
103             ExternalTransaction tx = database.newTransaction();
104             // we assume it's a valid XML doc and parse it
105
try {
106                 StringReader JavaDoc in = new StringReader JavaDoc((String JavaDoc)value);
107                 InputSource JavaDoc source = new InputSource JavaDoc(in);
108                 SAXParser JavaDoc parser = parserFactory.newSAXParser();
109                 ParserAdapter JavaDoc adapter = new ParserAdapter JavaDoc( parser.getParser() );
110                 tx.begin();
111                 adapter.setContentHandler( container.storeSAX() );
112                 adapter.parse( source );
113                 tx.commit();
114             }
115             catch (SAXException JavaDoc e) {
116                 try {
117                     if (tx.getStatus() == tx.STATUS_ACTIVE)
118                         tx.rollback();
119                     throw new XMLDBException(ErrorCodes.INVALID_RESOURCE, e.getMessage());
120                 }
121                 catch (Exception JavaDoc rollbackException) {
122                     throw new XMLDBException(ErrorCodes.VENDOR_ERROR, rollbackException.toString());
123                 }
124             }
125             catch (Exception JavaDoc e) {
126                 try {
127                     if (tx.getStatus() == tx.STATUS_ACTIVE)
128                         tx.rollback();
129                     throw new XMLDBException(ErrorCodes.VENDOR_ERROR, e.getMessage());
130                 }
131                 catch (Exception JavaDoc rollbackException) {
132                     throw new XMLDBException(ErrorCodes.VENDOR_ERROR, rollbackException.toString());
133                 }
134             }
135         }
136         else if (value instanceof Node JavaDoc) {
137             setContentAsDOM((Node JavaDoc)value);
138         }
139         else
140             throw new XMLDBException( ErrorCodes.VENDOR_ERROR, ErrorCodes.UNKNOWN_RESOURCE_TYPE );
141     }
142
143     /**
144      * Returns a String representation of the XML content
145      * usage exampel : <BR/>
146      * String content = (String)xmlResource.getContent(); <BR/>
147      * @return a String representation of the XML content
148      */

149     public Object JavaDoc getContent() throws XMLDBException {
150         try {
151             return toString( "xml", "UTF-8", true );
152         }
153         catch (Exception JavaDoc e) {
154             throw new XMLDBException( ErrorCodes.VENDOR_ERROR, e.getMessage());
155         }
156     }
157
158    /**
159     * Returns the resource type for this Resource.
160     *
161     * @return the resource type for the Resource.
162     */

163     public String JavaDoc getResourceType() throws XMLDBException {
164         return XMLResource.RESOURCE_TYPE;
165     }
166
167    /**
168     * Returns the content of the <code>Resource</code> as a DOM Node.
169     *
170     * @return The XML content as a DOM <code>Node</code>
171     */

172     public Node JavaDoc getContentAsDOM() throws XMLDBException {
173         ExternalTransaction tx = database.newTransaction();
174         try {
175             tx.begin();
176             DocumentBuilderFactory JavaDoc builderFactory = new org.apache.xerces.jaxp.DocumentBuilderFactoryImpl();
177             DocumentBuilder JavaDoc documentBuilder = builderFactory.newDocumentBuilder();
178             Document JavaDoc doc = container.extractDOM(documentBuilder.newDocument());
179             tx.commit();
180             return doc;
181         }
182         catch (Exception JavaDoc e) {
183             try {
184                 if (tx.getStatus() == tx.STATUS_ACTIVE)
185                     tx.rollback();
186                 throw new XMLDBException( ErrorCodes.VENDOR_ERROR, e.getMessage());
187             }
188             catch (Exception JavaDoc rollbackException) {
189                 throw new XMLDBException(ErrorCodes.VENDOR_ERROR, rollbackException.toString());
190             }
191         }
192     }
193
194    /**
195     * Sets the content of the <code>Resource</code> using a DOM Node as the
196     * source.
197     *
198     * @param content The new content value
199     */

200     public void setContentAsDOM( Node JavaDoc content ) throws XMLDBException {
201         ExternalTransaction tx = database.newTransaction();
202         try {
203             if (content == null) {
204                 logger.debug("XMLResourceImpl.setContentAsDOM() - Content is null");
205                 throw new XMLDBException(ErrorCodes.INVALID_RESOURCE);
206             }
207             if (content instanceof Document JavaDoc) {
208                 Document JavaDoc doc = (Document JavaDoc)content;
209                 tx.begin();
210                 container.storeDOM(doc);
211                 tx.commit();
212             }
213             else {
214                 logger.info("Cannot store Nodes right now, must be a Document");
215             }
216         }
217         catch (Exception JavaDoc e) {
218             e.printStackTrace();
219             try {
220                 logger.debug("XMLResourceImpl.setContentAsDOM() - Transaction status is " + tx.getStatus());
221                 if (tx.getStatus() == tx.STATUS_ACTIVE)
222                     tx.rollback();
223                 throw new XMLDBException( ErrorCodes.VENDOR_ERROR, e.getMessage());
224             }
225             catch (Exception JavaDoc rollbackException) {
226                 throw new XMLDBException(ErrorCodes.VENDOR_ERROR, rollbackException.getMessage());
227             }
228         }
229     }
230
231    /**
232     * Allows you to use a <code>ContentHandler</code> to parse the XML data from
233     * the database for use in an application.
234     *
235     * @param handler the SAX <code>ContentHandler</code> to use to handle the
236     * <code>Resource</code> content.
237     */

238     public void getContentAsSAX( ContentHandler JavaDoc handler ) throws XMLDBException {
239         ExternalTransaction tx = database.newTransaction();
240         try {
241             tx.begin();
242             container.extractSAX(handler);
243             tx.commit();
244         }
245         catch (Exception JavaDoc e) {
246             try {
247                 if (tx.getStatus() == tx.STATUS_ACTIVE)
248                     tx.rollback();
249                 throw new XMLDBException( ErrorCodes.VENDOR_ERROR, e.getMessage());
250             }
251             catch (Exception JavaDoc rollbackException) {
252                 throw new XMLDBException(ErrorCodes.VENDOR_ERROR, rollbackException.toString());
253             }
254         }
255     }
256
257    /**
258     * Sets the content of the <code>Resource</code> using a SAX
259     * <code>ContentHandler</code>.
260     *
261     * @return a SAX <code>ContentHandler</code> that can be used to add content
262     * into the <code>Resource</code>.
263     */

264     public ContentHandler JavaDoc setContentAsSAX() throws XMLDBException {
265         ExternalTransaction tx = database.newTransaction();
266         try {
267             tx.begin();
268             ContentHandler JavaDoc handler = container.storeSAX();
269             tx.commit();
270             return handler;
271         }
272         catch (Exception JavaDoc e) {
273             try {
274                 if (tx.getStatus() == tx.STATUS_ACTIVE)
275                     tx.rollback();
276                 throw new XMLDBException( ErrorCodes.VENDOR_ERROR, e.getMessage());
277             }
278             catch (Exception JavaDoc rollbackException) {
279                 throw new XMLDBException(ErrorCodes.VENDOR_ERROR, rollbackException.toString());
280             }
281         }
282     }
283
284     /** returns a String representation of the Document with the method to be used ,
285      * the encoding type specified and whether to indent or not <br/>
286      * Example: String content = toString( "xml", "UTF-8", true );
287      *
288      */

289     private String JavaDoc toString(String JavaDoc type, String JavaDoc encoding, boolean indenting) throws Exception JavaDoc {
290         int depth = -1;
291         ExternalTransaction tx = database.newTransaction();
292         tx.begin();
293         try {
294             StringWriter JavaDoc writer = new StringWriter JavaDoc();
295             XMLSerializer serializer = new XMLSerializer( writer, new OutputFormat(type, encoding, indenting) );
296             ContentHandler JavaDoc handler = serializer.asContentHandler();
297             container.extractSAX( handler, null, depth );
298             writer.flush();
299             tx.commit();
300             return writer.toString();
301         }
302         catch (Exception JavaDoc e) {
303             if (tx.getStatus() == tx.STATUS_ACTIVE)
304                 tx.rollback();
305             throw e;
306         }
307     }
308 }
309
Popular Tags