1 2 import com.saxonica.validate.SchemaAwareConfiguration; 3 import net.sf.saxon.event.Sink; 4 import net.sf.saxon.Configuration; 5 import net.sf.saxon.TransformerFactoryImpl; 6 import net.sf.saxon.tree.TreeBuilder; 7 import net.sf.saxon.event.PipelineConfiguration; 8 import net.sf.saxon.event.Receiver; 9 import net.sf.saxon.event.ResultWrapper; 10 import net.sf.saxon.event.Sink; 11 import net.sf.saxon.om.NodeInfo; 12 import net.sf.saxon.om.Validation; 13 import net.sf.saxon.pull.*; 14 import net.sf.saxon.query.DynamicQueryContext; 15 import net.sf.saxon.query.StaticQueryContext; 16 import net.sf.saxon.query.XQueryExpression; 17 import net.sf.saxon.tinytree.TinyBuilder; 18 import net.sf.saxon.trans.XPathException; 19 import net.sf.saxon.value.Value; 20 21 import javax.xml.transform.*; 22 import javax.xml.transform.stream.StreamResult ; 23 import javax.xml.transform.stream.StreamSource ; 24 import java.io.*; 25 import java.util.Properties ; 26 27 35 36 public class PullExamples { 37 38 private Configuration config; 39 40 43 44 public void serialize(PullProvider in, OutputStream out) throws XPathException, IOException { 45 Properties props = new Properties (); 46 props.setProperty(OutputKeys.METHOD, "xml"); 47 props.setProperty(OutputKeys.INDENT, "yes"); 48 Receiver receiver = ResultWrapper.getReceiver(new StreamResult (out), 49 in.getPipelineConfiguration(), 50 props); 51 new PullPushCopier(in, receiver).copy(); 52 } 53 54 58 59 public void validate(PullProvider in) throws XPathException, IOException { 60 SchemaAwareConfiguration config = new SchemaAwareConfiguration(); 61 in.getPipelineConfiguration().setConfiguration(config); 62 Receiver sink = new Sink(); 63 sink.setPipelineConfiguration(in.getPipelineConfiguration()); 64 Receiver validator = config.getDocumentValidator( 65 sink, in.getSourceLocator().getSystemId(), config.getNamePool(), Validation.STRICT, null); 66 validator.setPipelineConfiguration(in.getPipelineConfiguration()); 67 new PullPushCopier(in, validator).copy(); 69 } 70 71 74 75 public void transform(PullProvider in, File stylesheet, OutputStream out) throws TransformerException { 76 TransformerFactory factory = new TransformerFactoryImpl(); 77 Templates templates = factory.newTemplates(new StreamSource (stylesheet)); 78 Transformer transformer = templates.newTransformer(); 79 transformer.transform( 80 new PullSource(in), 81 new StreamResult (out) 82 ); 83 } 84 85 88 89 public void query(PullProvider in, String query, OutputStream out) throws XPathException { 90 final StaticQueryContext sqc = new StaticQueryContext(config); 91 final XQueryExpression exp = sqc.compileQuery(query); 92 final DynamicQueryContext dynamicContext = new DynamicQueryContext(config); 93 dynamicContext.setContextNode(sqc.buildDocument(new PullSource(in))); 94 Properties props = new Properties (); 95 props.setProperty(OutputKeys.INDENT, "yes"); 96 exp.run(dynamicContext, new StreamResult (out), props); 97 } 98 99 102 103 public NodeInfo build(PullProvider in) throws XPathException { 104 TinyBuilder builder = new TinyBuilder(); 105 builder.setPipelineConfiguration(in.getPipelineConfiguration()); 106 new PullPushCopier(in, builder).copy(); 107 return builder.getCurrentRoot(); 108 } 109 110 113 114 public NodeInfo buildStandardTree(PullProvider in) throws XPathException { 115 TreeBuilder builder = new TreeBuilder(); 116 builder.setPipelineConfiguration(in.getPipelineConfiguration()); 117 builder.open(); 118 new PullPushCopier(in, builder).copy(); 119 builder.close(); 120 return builder.getCurrentRoot(); 121 } 122 123 126 127 public PullProvider getParser(File input) throws FileNotFoundException, XPathException { 128 StaxBridge parser = new StaxBridge(); 129 parser.setInputStream(input.toURI().toString(), new FileInputStream(input)); 130 parser.setPipelineConfiguration(config.makePipelineConfiguration()); 131 return parser; 132 } 133 134 137 138 public PullProvider getTreeWalker(NodeInfo root) { 139 return TreeWalker.makeTreeWalker(root); 140 } 141 142 146 147 public PullProvider pullQueryResults(NodeInfo source, String query) throws XPathException { 148 final StaticQueryContext sqc = new StaticQueryContext(config); 149 final XQueryExpression exp = sqc.compileQuery(query); 150 final DynamicQueryContext dynamicContext = new DynamicQueryContext(config); 151 dynamicContext.setContextNode(source); 152 PullProvider pull = new PullFromIterator(exp.iterator(dynamicContext)); 153 pull = new PullNamespaceReducer(pull); 154 pull.setPipelineConfiguration(config.makePipelineConfiguration()); 155 return pull; 156 } 157 158 162 163 public void removePriceElements(PullProvider in, OutputStream out) throws IOException, XPathException { 164 final int priceElement = config.getNamePool().allocate("", "", "PRICE"); 165 PullFilter filter = new PullFilter(in) { 166 public int next() throws XPathException { 167 currentEvent = super.next(); 168 if (currentEvent == START_ELEMENT && getFingerprint() == priceElement) { 169 super.skipToMatchingEnd(); 170 currentEvent = next(); 171 } 172 return currentEvent; 173 } 174 }; 175 serialize(filter, out); 176 } 177 178 182 183 public void displayAveragePrice(PullProvider in, OutputStream out) throws IOException, XPathException { 184 final int priceElement = config.getNamePool().allocate("", "", "PRICE"); 185 double total = 0; 186 int count = 0; 187 while (true) { 188 int event = in.next(); 189 if (event == PullProvider.END_OF_INPUT) { 190 break; 191 } 192 if (event == PullProvider.START_ELEMENT && in.getFingerprint() == priceElement) { 193 double value = Value.stringToNumber(in.getStringValue()); 194 total += value; 195 count++; 196 } 197 } 198 double average = (count==0 ? Double.NaN : total/count); 199 String result = "<result>" + average + "</result>"; 200 OutputStreamWriter writer = new OutputStreamWriter(out); 201 writer.write(result); 202 writer.flush(); 203 } 204 205 215 216 public static void main(String [] args) throws Exception { 217 String examples; 218 if (args.length < 1 || args[0].equals("#")) { 219 examples = "abcdefghijklmnopqrstuvwxyz"; 220 } else { 221 examples = args[0]; 222 } 223 File input = null; 224 OutputStream output = null; 225 String query = null; 226 File stylesheet = null; 227 228 for (int i=1; i<args.length; i++) { 229 if (args[i].equals("-s")) { 230 input = new File(args[++i]); 231 } else if (args[i].equals("-o")) { 232 output = new FileOutputStream(new File(args[++i])); 233 } else if (args[i].equals("-q")) { 234 query = readFile(new File(args[++i])); 235 } else if (args[i].equals("-xsl")) { 236 stylesheet = new File(args[++i]); 237 } else { 238 System.err.println("Unknown argument " + args[i]); 239 } 240 } 241 242 if (input==null) { 243 input = new File("../data/books.xml"); 244 } 245 246 if (output==null) { 247 output = System.out; 248 } 249 250 PullExamples o = new PullExamples(); 251 Configuration config = new Configuration(); 252 config.setLazyConstructionMode(true); 253 o.config = config; 254 255 PipelineConfiguration pipe = config.makePipelineConfiguration(); 256 for (int i=0; i<examples.length(); i++) { 257 char ex = examples.charAt(i); 258 switch (ex) { 259 case 'a': { 260 System.out.println("\n\n=== Serialize the input to the output ===\n"); 261 262 PullProvider p = o.getParser(input); 263 p.setPipelineConfiguration(pipe); 264 o.serialize(p, output); 265 break; 266 } 267 case 'b': { 268 System.out.println("\n\n=== Validate the input ===\n"); 269 270 PullProvider p = o.getParser(input); 271 p.setPipelineConfiguration(pipe); 272 o.validate(p); 273 break; 274 } 275 case 'c': { 276 System.out.println("\n\n=== Transform the input to the output ===\n"); 277 278 if (stylesheet == null) { 279 System.err.println("** No stylesheet supplied"); 280 break; 281 } 282 PullProvider p = o.getParser(input); 283 p.setPipelineConfiguration(pipe); 284 o.transform(p, stylesheet, output); 285 break; 286 } 287 case 'd': { 288 System.out.println("\n\n=== Run XQuery against the input ===\n"); 289 if (query == null) { 290 query = "<result>{.}</result>"; 291 } 292 PullProvider p = o.getParser(input); 293 p.setPipelineConfiguration(pipe); 294 o.query(p, query, output); 295 break; 296 } 297 case 'e': { 298 System.out.println("\n\n=== Remove PRICE elements from the input ===\n"); 299 300 PullProvider p = o.getParser(input); 301 p.setPipelineConfiguration(pipe); 302 o.removePriceElements(p, output); 303 break; 304 } 305 case 'f': { 306 System.out.println("\n\n=== Compute average of PRICE elements in the input ===\n"); 307 308 PullProvider p = o.getParser(input); 309 p.setPipelineConfiguration(pipe); 310 o.displayAveragePrice(p, output); 311 break; 312 } 313 case 'g': { 314 System.out.println("\n\n=== Obtain query results using a pull iterator ===\n"); 315 316 NodeInfo node = new StaticQueryContext(config) 317 .buildDocument(new StreamSource (input)); 318 PullProvider p = o.pullQueryResults(node, 319 320 "declare function local:f() {"+ 321 "for $var1 in (<abc/>, <def/>)"+ 322 "return <e xmlns:x='x1'><f xmlns:y='y1' xmlns:x='x2'>xyz</f></e>};"+ 323 "local:f()" 324 325 ); 326 o.serialize(new PullTracer(p), output); 327 break; 328 } 329 case 'h': { 330 System.out.println("\n\n=== Obtain query results using a pull iterator on a 'standard' tree ===\n"); 331 332 PullProvider p1 = o.getParser(input); 333 p1.setPipelineConfiguration(pipe); 334 NodeInfo node = o.buildStandardTree(p1); 335 PullProvider p2 = o.pullQueryResults(node, 336 "//CATEGORIES" 337 ); 338 o.serialize(p2, output); 339 } 340 } 341 } 342 } 343 344 347 348 public static String readFile(File file) throws IOException { 349 Reader reader = new FileReader(file); 350 char[] buffer = new char[4096]; 351 StringBuffer sb = new StringBuffer (4096); 352 while (true) { 353 int n = reader.read(buffer); 354 if (n>0) { 355 sb.append(buffer, 0, n); 356 } else { 357 break; 358 } 359 } 360 return sb.toString(); 361 } 362 363 364 365 } 366 367 | Popular Tags |