KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > sf > saxon > query > QueryResult


1 package net.sf.saxon.query;
2
3 import net.sf.saxon.Configuration;
4 import net.sf.saxon.event.*;
5 import net.sf.saxon.om.DocumentInfo;
6 import net.sf.saxon.om.Item;
7 import net.sf.saxon.om.NodeInfo;
8 import net.sf.saxon.om.SequenceIterator;
9 import net.sf.saxon.tinytree.TinyBuilder;
10 import net.sf.saxon.trans.DynamicError;
11 import net.sf.saxon.trans.XPathException;
12 import net.sf.saxon.type.Type;
13 import net.sf.saxon.value.QNameValue;
14
15 import javax.xml.transform.OutputKeys JavaDoc;
16 import javax.xml.transform.Result JavaDoc;
17 import javax.xml.transform.stream.StreamResult JavaDoc;
18 import java.io.OutputStream JavaDoc;
19 import java.io.OutputStreamWriter JavaDoc;
20 import java.io.PrintWriter JavaDoc;
21 import java.io.UnsupportedEncodingException JavaDoc;
22 import java.util.Properties JavaDoc;
23
24 /**
25  * This utility class takes the result sequence produced by a query, and wraps it as
26  * an XML document. The class is never instantiated.
27  */

28 public class QueryResult {
29
30     public static String JavaDoc RESULT_NS = "http://saxon.sf.net/xquery-results";
31
32     private QueryResult() {
33     }
34
35     /**
36      * Take the results of a query (or any other SequenceIterator) and create
37      * an XML document containing copies of all items in the sequence, suitably wrapped
38      * @param iterator The values to be wrapped
39      * @param config The Saxon configuration used to evaluate the query
40      * @return the document containing the wrapped results
41      * @throws XPathException
42      */

43
44     public static DocumentInfo wrap(SequenceIterator iterator, Configuration config) throws XPathException {
45         PipelineConfiguration pipe = config.makePipelineConfiguration();
46         TinyBuilder builder = new TinyBuilder();
47
48         NamespaceReducer reducer = new NamespaceReducer();
49         reducer.setUnderlyingReceiver(builder);
50         Receiver tree = reducer;
51
52         tree.setPipelineConfiguration(pipe);
53         builder.setPipelineConfiguration(pipe);
54         sendWrappedSequence(iterator, tree);
55         return (DocumentInfo)builder.getCurrentRoot();
56     }
57
58     /**
59      * Take a sequence supplied in the form of an iterator and generate a wrapped represention of the
60      * items in the sequence, the wrapped representation being a sequence of events sent to a supplied
61      * Receiver.
62      * @param iterator the input sequence
63      * @param destination the Receiver to accept the wrapped output
64      */

65
66     public static void sendWrappedSequence(SequenceIterator iterator, Receiver destination) throws XPathException {
67         SequenceCopier.copySequence(iterator, new SequenceWrapper(destination));
68     }
69
70     /**
71      * Serialize a document containing wrapped query results (or any other document, in fact)
72      * as XML.
73      * @param node The document or element to be serialized
74      * @param destination The Result object to contain the serialized form
75      * @param outputProperties Serialization options
76      * @param config The Configuration
77      * @throws XPathException If serialization fails
78      */

79
80     public static void serialize(NodeInfo node, Result JavaDoc destination, Properties JavaDoc outputProperties, Configuration config)
81     throws XPathException {
82         PipelineConfiguration pipe = config.makePipelineConfiguration();
83         int type = node.getNodeKind();
84         if (type==Type.DOCUMENT || type==Type.ELEMENT) {
85             DocumentSender sender = new DocumentSender(node);
86             Receiver receiver =
87                     ResultWrapper.getReceiver(destination,
88                                               pipe,
89                                               outputProperties);
90             NamespaceReducer reducer = new NamespaceReducer();
91             reducer.setUnderlyingReceiver(receiver);
92             reducer.setPipelineConfiguration(pipe);
93             sender.send(reducer);
94         } else {
95             throw new DynamicError("Node to be serialized must be a Document or Element node");
96         }
97     }
98
99     /**
100      * Serialize an arbitrary sequence, without any special wrapping.
101      * @param results the sequence to be serialized
102      * @param config the configuration (gives access to information such as the NamePool)
103      * @param destination the output stream to which the output is to be written
104      * @param outputProps a set of serialization properties as defined in JAXP
105      * @throws XPathException if any failure occurs
106      */

107
108     public static void serializeSequence(SequenceIterator results, Configuration config,
109                                           OutputStream JavaDoc destination, Properties JavaDoc outputProps)
110             throws XPathException {
111         String JavaDoc encoding = outputProps.getProperty(OutputKeys.ENCODING);
112         if (encoding==null) {
113             encoding = "UTF-8";
114         }
115         PrintWriter JavaDoc writer;
116         try {
117             writer = new PrintWriter JavaDoc(
118                 new OutputStreamWriter JavaDoc(destination, encoding));
119         } catch (UnsupportedEncodingException JavaDoc err) {
120             throw new DynamicError(err);
121         }
122         while (true) {
123             Item item = results.next();
124             if (item == null) break;
125             if (item instanceof NodeInfo) {
126                 switch (((NodeInfo)item).getNodeKind()) {
127                 case Type.DOCUMENT:
128                 case Type.ELEMENT:
129                     serialize((NodeInfo)item,
130                             new StreamResult JavaDoc(writer),
131                             outputProps,
132                             config);
133                     writer.println("");
134                     break;
135                 case Type.ATTRIBUTE:
136                     writer.println(((NodeInfo)item).getLocalPart() +
137                                    "=\"" +
138                                    item.getStringValue() +
139                                    '\"');
140                     break;
141                 case Type.COMMENT:
142                     writer.println("<!--" + item.getStringValue() + "-->");
143                     break;
144                 case Type.PROCESSING_INSTRUCTION:
145                     writer.println("<?" +
146                                    ((NodeInfo)item).getLocalPart() +
147                                    ' ' +
148                                    item.getStringValue() +
149                                    "?>");
150                     break;
151                 default:
152                     writer.println(item.getStringValue());
153                 }
154             } else if (item instanceof QNameValue) {
155                 writer.println(((QNameValue)item).getClarkName());
156             } else {
157                 writer.println(item.getStringValue());
158             }
159         }
160         writer.flush();
161     }
162
163 // public static void main(String[] params) throws Exception {
164
// StaticQueryContext env = new StaticQueryContext(new Configuration());
165
// QueryProcessor qp = new QueryProcessor(env);
166
// XQueryExpression exp = qp.compileQuery("<a><b/></a>");
167
// SequenceIterator iter = exp.iterator(new DynamicQueryContext());
168
// NodeInfo node = (NodeInfo)iter.next();
169
// serialize(node, new SAXResult(new ExampleContentHandler()), new Properties());
170
//
171
// }
172
}
173
174 //
175
// The contents of this file are subject to the Mozilla Public License Version 1.0 (the "License");
176
// you may not use this file except in compliance with the License. You may obtain a copy of the
177
// License at http://www.mozilla.org/MPL/
178
//
179
// Software distributed under the License is distributed on an "AS IS" basis,
180
// WITHOUT WARRANTY OF ANY KIND, either express or implied.
181
// See the License for the specific language governing rights and limitations under the License.
182
//
183
// The Original Code is: all this file.
184
//
185
// The Initial Developer of the Original Code is Michael H. Kay
186
//
187
// Portions created by (your name) are Copyright (C) (your legal entity). All Rights Reserved.
188
//
189
// Contributor(s): none.
190
//
191
Popular Tags