KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > xquark > xquery > xdbc > XResultSetImpl


1 /*
2  * This file belongs to the XQuark distribution.
3  * Copyright (C) 2003 Universite de Versailles Saint-Quentin.
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2.1 of the License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307.
18  * You can also get it at http://www.gnu.org/licenses/lgpl.html
19  *
20  * For more information on this software, see http://www.xquark.org.
21  */

22
23 package org.xquark.xquery.xdbc;
24
25 import java.io.StringWriter JavaDoc;
26 import java.io.Writer JavaDoc;
27 import java.util.ArrayList JavaDoc;
28 import java.util.Iterator JavaDoc;
29 import java.util.Map JavaDoc;
30
31 import javax.xml.parsers.DocumentBuilder JavaDoc;
32 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
33 import javax.xml.parsers.ParserConfigurationException JavaDoc;
34
35 import org.w3c.dom.Document JavaDoc;
36 import org.xml.sax.*;
37 import org.xml.sax.ext.LexicalHandler JavaDoc;
38 import org.xquark.schema.SchemaManager;
39 import org.xquark.schema.validation.PSVInfoSetProvider;
40 import org.xquark.schema.validation.SchemaValidationContext;
41 import org.xquark.schema.validation.ValidatingSchemaHandler;
42 import org.xquark.serialize.XMLSerializer;
43 import org.xquark.util.DOMBuilder;
44 import org.xquark.util.NamespaceContextStack;
45 import org.xquark.xml.xdbc.*;
46 import org.xquark.xquery.metadata.DynamicContext;
47 import org.xquark.xquery.parser.*;
48 import org.xquark.xquery.parser.util.Constants;
49 import org.xquark.xquery.reconstruction.ReconstructionVisitor;
50
51 /**
52  * Common base implementation of the XBDC result set. It is used as this
53  * by the Extractor.
54  */

55 public class XResultSetImpl implements XMLResultSet {
56     private static final String JavaDoc RCSRevision = "$Revision: 1.24 $";
57     private static final String JavaDoc RCSName = "$Name: $";
58     protected ContentHandler contentHandler = null;
59     protected LexicalHandler JavaDoc lexicalhandler = null;
60     protected ErrorHandler errorhandler = null;
61     protected XMLStatement statement = null;
62     protected XDBCResultSetInterface xdbcResulSet = null;
63     protected ReconstructionVisitor reconstructionvisitor = null;
64     protected XQueryExpression reconstructExpression = null;
65     private boolean noNext = false;
66
67     private int validationMode = Constants.VALIDATION_SKIP;
68     private SchemaManager schemamanager = null;
69     private ValidatingSchemaHandler vsh = null;
70
71     private ArrayList JavaDoc varList = null;
72
73     private int position = 0;
74     private boolean firstHasNext = true;
75
76     private XMLSerializer serializer = null;
77     private DOMBuilder builder = null;
78     private Document JavaDoc document = null;
79     private static DocumentBuilder JavaDoc DOMCreator;
80     
81     // for dynamic context
82
private DynamicContext dc = null;
83
84     private PSVInfoSetProvider psvisp = null;
85     /**********************************************************************************************/
86
87     public XResultSetImpl(XDBCResultSetInterface xdbcResulSet, XQueryExpression reconstructExpression, ArrayList JavaDoc varList, XMLStatement statement) throws XQueryException {
88         this.xdbcResulSet = xdbcResulSet;
89         this.reconstructExpression = reconstructExpression;
90         if (reconstructExpression.getParentModule().getValidation() != -1)
91             this.validationMode = reconstructExpression.getParentModule().getValidation();
92         this.schemamanager = reconstructExpression.getParentModule().getSchemaManager();
93         this.varList = varList;
94         this.statement = statement;
95         this.dc = new DynamicContext();
96         // fill dynamic context
97
XQueryModule module = reconstructExpression.getParentModule();
98         Map JavaDoc map = module.getImportModules();
99         if (map != null) {
100             for (Iterator JavaDoc it = map.values().iterator();it.hasNext();) {
101                 dc.addImportModule(((ImportModule)it.next()).getModule());
102             }
103         }
104         if (validationMode == Constants.VALIDATION_PRESERVE)
105             psvisp = (PSVInfoSetProvider)new SchemaValidationContext(schemamanager);
106         this.reconstructionvisitor = new ReconstructionVisitor(this, varList);
107         this.reconstructionvisitor.setDynamicContext(dc);
108     }
109
110     /**********************************************************************************************/
111
112     /**
113      * @see XMLResultSet#setContentHandler
114      */

115     public void setContentHandler(ContentHandler contentHandler) {
116         if (contentHandler == null)
117             throw new IllegalArgumentException JavaDoc("ContentHandler cannot be null.");
118         this.contentHandler = contentHandler;
119         if (validationMode == Constants.VALIDATION_STRICT || validationMode == Constants.VALIDATION_LAX) {
120             // Creates new manager to remove schema without namespace (that contains the default relational schema for Bridge)
121
// Thus, elements with no namespace are not validated during reconstruction
122
SchemaManager reconstructionManager = new SchemaManager(schemamanager);
123             reconstructionManager.removeSchema(null);
124             vsh = new ValidatingSchemaHandler(new SchemaValidationContext(reconstructionManager), validationMode == Constants.VALIDATION_STRICT);
125             vsh.setContentHandler(contentHandler);
126             if (errorhandler == null) {
127                 vsh.setErrorHandler(new ErrorHandler() {
128                     public void fatalError(SAXParseException spe) throws SAXException {
129                     };
130                     public void warning(SAXParseException spe) throws SAXException {
131                     };
132                     public void error(SAXParseException spe) throws SAXException {
133                         throw spe;
134                     };
135                 });
136             } else {
137                 vsh.setErrorHandler(errorhandler);
138             }
139         }
140         if (xdbcResulSet != null)
141             xdbcResulSet.setContentHandler((vsh == null) ? contentHandler : vsh);
142         reconstructionvisitor.setContentHandler((vsh == null) ? contentHandler : vsh);
143     }
144
145     /**
146      * @see ResultSet#setLexicalHandler
147      */

148     public void setLexicalHandler(LexicalHandler JavaDoc lexicalhandler) {
149         if (lexicalhandler == null)
150             throw new IllegalArgumentException JavaDoc("LexicalHandler cannot be null.");
151         this.lexicalhandler = lexicalhandler;
152         if (xdbcResulSet != null)
153             xdbcResulSet.setLexicalHandler(lexicalhandler);
154         reconstructionvisitor.setLexicalHandler(lexicalhandler);
155     }
156
157     /**
158      * @see ResultSet#setErrorHandler
159      */

160     public void setErrorHandler(ErrorHandler errorhandler) {
161         if (errorhandler == null)
162             throw new IllegalArgumentException JavaDoc("ErrorHandler cannot be null.");
163         this.errorhandler = errorhandler;
164         if (xdbcResulSet != null)
165             xdbcResulSet.setErrorHandler(errorhandler);
166         reconstructionvisitor.setErrorHandler(errorhandler);
167         if (vsh != null)
168             vsh.setErrorHandler(errorhandler);
169     }
170
171     /**
172      * @see ResultSet#setErrorHandler
173      */

174     public ContentHandler getContentHandler() {
175         return (vsh == null) ? contentHandler : vsh;
176     }
177
178     /**
179      * @see ResultSet#setErrorHandler
180      */

181     public LexicalHandler JavaDoc getLexicalHandler() {
182         return lexicalhandler;
183     }
184
185     /**
186      * @see ResultSet#setErrorHandler
187      */

188     public ErrorHandler getErrorHandler() {
189         return errorhandler;
190     }
191
192     /**********************************************************************************************/
193
194     /**
195      * @see XMLResultSet#getStatement
196      */

197     public XMLStatement getStatement() throws XMLDBCException {
198         return statement;
199     }
200
201     /**
202      * @see XMLResultSet#close
203      */

204     public void close() throws XMLDBCException {
205         if (xdbcResulSet != null) {
206             xdbcResulSet.close();
207             xdbcResulSet = null;
208         }
209     }
210
211     /**********************************************************************************************/
212
213     /**
214      * @see XMLResultSet#isBeforeFirst
215      */

216     public boolean isBeforeFirst() throws XMLDBCException {
217         return 0 == position ? true : false;
218     }
219
220     /**
221      * @see XMLResultSet#nextAsDOM
222      */

223     public Document JavaDoc nextAsDocument() throws XMLDBCException {
224         try {
225             createDOMBuilder();
226             Document JavaDoc document = DOMCreator.newDocument();
227             if (builder == null)
228                 builder = new DOMBuilder(document);
229             else
230                 builder.setDocument(document);
231             setContentHandler(builder);
232             setLexicalHandler(builder);
233             nextAsSAX();
234             return document;
235         } catch (SAXException e) {
236             throw new XMLDBCException(e.getMessage(), e);
237         }
238     }
239
240     public org.w3c.dom.Node JavaDoc nextAsDOM() throws XMLDBCException {
241         return nextAsDocument().getFirstChild();
242     }
243
244     public void nextAsDOM(org.w3c.dom.Element JavaDoc parent) throws XMLDBCException {
245         try {
246             if (builder == null)
247                 builder = new DOMBuilder(parent);
248             else
249                 builder.setElement(parent);
250             setContentHandler(builder);
251             setLexicalHandler(builder);
252             nextAsSAX();
253         } catch (SAXException e) {
254             throw new XMLDBCException(e.getMessage(), e);
255         }
256     }
257
258     /**
259      * @see XMLResultSet#nextAsString
260      */

261     public java.lang.String JavaDoc nextAsString() throws XMLDBCException {
262         StringWriter JavaDoc stringWriter = new StringWriter JavaDoc();
263         nextAsStream(stringWriter);
264         return stringWriter.toString();
265     }
266
267     public void nextAsStream(Writer JavaDoc out) throws XMLDBCException {
268         try {
269             if (serializer == null)
270                 serializer = new XMLSerializer(out);
271             else {
272                 serializer.reset();
273                 serializer.setWriter(out);
274             }
275             setContentHandler(serializer);
276             setLexicalHandler(serializer);
277             nextAsSAX();
278         } catch (SAXException e) {
279             throw new XMLDBCException(e.getMessage(), e);
280         }
281     }
282
283     /**
284      * @see XMLResultSet#nextAsSAX
285      */

286     public void nextAsSAX() throws XMLDBCException, SAXException {
287         firstHasNext = false;
288         boolean add = false;
289         try {
290             if (!reconstructionvisitor.getNoNext() && hasNext()) {
291                 xdbcResulSet.next();
292                 add = true;
293             }
294             if (reconstructExpression != null && reconstructionvisitor != null && !reconstructionvisitor.getNoReconstructor()) {
295                 // for prefix mapping
296
NamespaceContextStack declarations = reconstructExpression.getParentModule().getDeclarations();
297                 if (contentHandler != null && declarations != null) {
298                     reconstructionvisitor.setNamespaceDecl(declarations);
299                 }
300                 reconstructExpression.accept(reconstructionvisitor);
301                 reconstructionvisitor.reInit();
302                 add = true;
303             }
304             if (add) position++;
305         } catch (XQueryException e) {
306             throw new XMLDBCException(e.getMessage(), e);
307         }
308     }
309
310     /**
311      * @see XMLResultSet#hasNext
312      */

313     public boolean hasNext() throws XMLDBCException {
314         boolean hasnext = false;
315         if (xdbcResulSet != null)
316             hasnext = xdbcResulSet.hasNext();
317         if (hasnext == false && reconstructExpression.getRoot() && firstHasNext) {
318             reconstructionvisitor.setNoResultSet(true);
319             hasnext = true;
320         }
321         return hasnext;
322     }
323
324     /**
325      * @see XMLResultSet#getPosition
326      */

327     public int getPosition() throws XMLDBCException {
328         return 0 == position ? -1 : position;
329     }
330
331     /**********************************************************************************************/
332
333     public XDBCResultSetInterface getXDBCResultSet() {
334         return xdbcResulSet;
335     }
336
337     public boolean hasRootTag() {
338         if (varList != null && !varList.isEmpty()) {
339             Variable tmpVar = (Variable) varList.get(0);
340             XQueryExpression tmpExpr = tmpVar.getExpression();
341             if ((reconstructExpression instanceof Element) && ((tmpExpr instanceof ValueInteger) || reconstructExpression.getLoop()))
342                 return true;
343         } else if (reconstructExpression instanceof Element && (reconstructExpression.getParentExpression() == null || reconstructExpression.getParentExpression().isEmpty()))
344             return true;
345         return false;
346     }
347
348     public boolean isDocument() {
349         if (reconstructExpression instanceof org.xquark.xquery.parser.Document)
350             return true;
351         return false;
352     }
353
354     public PSVInfoSetProvider getPSVInfoSetProvider() {
355         return psvisp;
356     }
357
358     public void setPSVInfoSetProvider(PSVInfoSetProvider psvisp) {
359         this.psvisp = psvisp;
360     }
361     
362     /**
363      * Returns the result set prefix map (as prefix-namespace pairs).
364      * This map is used to produce each result in the set.
365      * @return the result set prefix map.
366      * @throws XMLDBCException if a data source access error occurs.
367      * @deprecated
368      */

369     public java.util.Map JavaDoc getPrefixMap() throws XMLDBCException {
370         return java.util.Collections.EMPTY_MAP;
371     }
372
373     /**
374      * Returns the fragments contained in the result set as a single XML document, with
375      * a document root element having the specified namespace, local name and qualified name.
376      * Note: this convenience method can only be called if the cursor is before the
377      * first element. It will process the complete result set in one step.
378      * @param namespace the namespace of the document root element.
379      * @param localName the local name of the document root element.
380      * @param qName the qualified name of the document root element.
381      * @return an XML document containing the fragments of the result set, as children of
382      * the specified document root element.
383      * @throws XMLDBCException if a data source access error occurs.
384      */

385     public XMLDocument getFragmentsAsDocument(String JavaDoc namespace, String JavaDoc localName, String JavaDoc qName) throws XMLDBCException {
386         if (isBeforeFirst()) {
387             XMLDocumentImpl xmlDocument = new XMLDocumentImpl(this, namespace, localName, qName);
388             xmlDocument.setContentHandler(contentHandler);
389             xmlDocument.setLexicalHandler(lexicalhandler);
390             xmlDocument.setErrorHandler(errorhandler);
391             return xmlDocument;
392         } else {
393             throw new XMLDBCException("The cursor moved, it is not anymore before the first element.");
394         }
395     }
396
397     /**
398      * Returns the result set metadata (the XML Schema that models the returned data)
399      * as an XMLDocument.
400      * This schema describes the XML type of each result in the set.
401      * @return the result set metadata (a XML Schema).
402      * @throws XMLDBCException if a data source access error occurs.
403      */

404     public XMLDocument getMetaData() throws XMLDBCException {
405         return null;
406     }
407
408     private synchronized void createDOMBuilder() {
409         if (DOMCreator == null) {
410             DocumentBuilderFactory JavaDoc DOMFactory = DocumentBuilderFactory.newInstance();
411             DOMFactory.setNamespaceAware(true);
412             try {
413                 DOMCreator = DOMFactory.newDocumentBuilder();
414             } catch (ParserConfigurationException JavaDoc pce) {
415                 throw new RuntimeException JavaDoc("Could not create an empty DOM level 2 document using JAXP. Check a JAXP DOM implementation is in your classpath.");
416             }
417         }
418     }
419 }
420
Popular Tags