List of usage examples for javax.xml.transform.sax SAXResult SAXResult
public SAXResult(ContentHandler handler)
From source file:Main.java
public static void main(String[] argv) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(true);//from www .java2s . c o m factory.setExpandEntityReferences(false); Document doc = factory.newDocumentBuilder().parse(new File("filename")); Source source = new DOMSource(doc); URI uri = new File("infilename.xml").toURI(); source.setSystemId(uri.toString()); DefaultHandler handler = new MyHandler(); SAXResult result = new SAXResult(handler); Transformer xformer = TransformerFactory.newInstance().newTransformer(); xformer.transform(source, result); }
From source file:Pipe.java
public static void main(String[] args) throws TransformerException, TransformerConfigurationException, SAXException, IOException { // Instantiate a TransformerFactory. TransformerFactory tFactory = TransformerFactory.newInstance(); // Determine whether the TransformerFactory supports The use uf SAXSource // and SAXResult if (tFactory.getFeature(SAXSource.FEATURE) && tFactory.getFeature(SAXResult.FEATURE)) { // Cast the TransformerFactory to SAXTransformerFactory. SAXTransformerFactory saxTFactory = ((SAXTransformerFactory) tFactory); // Create a TransformerHandler for each stylesheet. TransformerHandler tHandler1 = saxTFactory.newTransformerHandler(new StreamSource("foo1.xsl")); TransformerHandler tHandler2 = saxTFactory.newTransformerHandler(new StreamSource("foo2.xsl")); TransformerHandler tHandler3 = saxTFactory.newTransformerHandler(new StreamSource("foo3.xsl")); // Create an XMLReader. XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setContentHandler(tHandler1); reader.setProperty("http://xml.org/sax/properties/lexical-handler", tHandler1); tHandler1.setResult(new SAXResult(tHandler2)); tHandler2.setResult(new SAXResult(tHandler3)); // transformer3 outputs SAX events to the serializer. java.util.Properties xmlProps = OutputPropertiesFactory.getDefaultMethodProperties("xml"); xmlProps.setProperty("indent", "yes"); xmlProps.setProperty("standalone", "no"); Serializer serializer = SerializerFactory.getSerializer(xmlProps); serializer.setOutputStream(System.out); tHandler3.setResult(new SAXResult(serializer.asContentHandler())); // Parse the XML input document. The input ContentHandler and output ContentHandler // work in separate threads to optimize performance. reader.parse("foo.xml"); }/*from w w w. j ava2s .c om*/ }
From source file:SAX2SAX.java
public static void main(String[] args) throws TransformerException, TransformerConfigurationException, SAXException, IOException { // Instantiate a TransformerFactory. TransformerFactory tFactory = TransformerFactory.newInstance(); // Determine whether the TransformerFactory supports The use of SAXSource // and SAXResult if (tFactory.getFeature(SAXSource.FEATURE) && tFactory.getFeature(SAXResult.FEATURE)) { // Cast the TransformerFactory. SAXTransformerFactory saxTFactory = ((SAXTransformerFactory) tFactory); // Create a ContentHandler to handle parsing of the stylesheet. TemplatesHandler templatesHandler = saxTFactory.newTemplatesHandler(); // Create an XMLReader and set its ContentHandler. XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setContentHandler(templatesHandler); // Parse the stylesheet. reader.parse("birds.xsl"); //Get the Templates object from the ContentHandler. Templates templates = templatesHandler.getTemplates(); // Create a ContentHandler to handle parsing of the XML source. TransformerHandler handler = saxTFactory.newTransformerHandler(templates); // Reset the XMLReader's ContentHandler. reader.setContentHandler(handler); // Set the ContentHandler to also function as a LexicalHandler, which // includes "lexical" events (e.g., comments and CDATA). reader.setProperty("http://xml.org/sax/properties/lexical-handler", handler); FileOutputStream fos = new FileOutputStream("birds.out"); java.util.Properties xmlProps = OutputPropertiesFactory.getDefaultMethodProperties("xml"); xmlProps.setProperty("indent", "yes"); xmlProps.setProperty("standalone", "no"); Serializer serializer = SerializerFactory.getSerializer(xmlProps); serializer.setOutputStream(fos); // Set the result handling to be a serialization to the file output stream. Result result = new SAXResult(serializer.asContentHandler()); handler.setResult(result);/* w w w.ja v a2 s . c om*/ // Parse the XML input document. reader.parse("birds.xml"); System.out.println("************* The result is in birds.out *************"); } else System.out.println("The TransformerFactory does not support SAX input and SAX output"); }
From source file:net.fenyo.gnetwatch.Documentation.java
/** * General entry point.//from w w w . ja v a 2 s . co m * @param args command line arguments. * @return void. * @throws IOException io exception. */ public static void main(String[] args) throws IOException, TransformerConfigurationException, TransformerException, FileNotFoundException, FOPException { final String docbook_stylesheets_path = args[0]; // Get configuration properties. final Config config = new Config(); // Read general logging rules. GenericTools.initLogEngine(config); log.info(config.getString("log_engine_initialized")); log.info(config.getString("begin")); Transformer docbookTransformerHTML = TransformerFactory.newInstance() .newTransformer(new StreamSource(new File(docbook_stylesheets_path + "/html/docbook.xsl"))); // docbookTransformerHTML.setParameter("draft.mode", "no"); docbookTransformerHTML.transform(new StreamSource(new FileReader(new File("gnetwatch-documentation.xml"))), new StreamResult(new FileWriter(new File("c:/temp/gnetwatch-documentation.html")))); Transformer docbookTransformerFO = TransformerFactory.newInstance() .newTransformer(new StreamSource(new File(docbook_stylesheets_path + "/fo/docbook.xsl"))); // docbookTransformerFO.setParameter("draft.mode", "no"); docbookTransformerFO.transform(new StreamSource(new FileReader(new File("gnetwatch-documentation.xml"))), new StreamResult(new FileWriter(new File("c:/temp/gnetwatch-documentation.fo")))); // for very old FOP version (0.20): // Driver driver = new Driver(); // driver.setRenderer(Driver.RENDER_PDF); // driver.setInputSource(new InputSource(new FileReader(new File("c:/temp/gnetwatch-documentation.fo")))); // driver.setOutputStream(new FileOutputStream(new File("c:/temp/gnetwatch-documentation.pdf"))); // driver.run(); // with new FOP version: OutputStream outStream = new BufferedOutputStream( new FileOutputStream("c:/temp/gnetwatch-documentation.pdf")); final FopFactory fopFactory = FopFactory.newInstance(new File(".").toURI()); Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, outStream); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); Source source = new StreamSource(new FileReader(new File("c:/temp/gnetwatch-documentation.fo"))); Result result = new SAXResult(fop.getDefaultHandler()); transformer.transform(source, result); outStream.close(); }
From source file:com.semsaas.jsonxml.tools.JsonXpath.java
public static void main(String[] args) { /*// w w w . j a v a 2 s . co m * Process options */ LinkedList<String> files = new LinkedList<String>(); LinkedList<String> expr = new LinkedList<String>(); boolean help = false; String activeOption = null; String error = null; for (int i = 0; i < args.length && error == null && !help; i++) { if (activeOption != null) { if (activeOption.equals("-e")) { expr.push(args[i]); } else if (activeOption.equals("-h")) { help = true; } else { error = "Unknown option " + activeOption; } activeOption = null; } else { if (args[i].startsWith("-")) { activeOption = args[i]; } else { files.push(args[i]); } } } if (error != null) { System.err.println(error); showHelp(); } else if (help) { showHelp(); } else { try { TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); for (String f : files) { System.out.println("*** " + f + " ***"); try { // Create a JSON XML reader XMLReader reader = XMLReaderFactory.createXMLReader("com.semsaas.jsonxml.JsonXMLReader"); // Prepare a reader with the JSON file as input InputStreamReader stringReader = new InputStreamReader(new FileInputStream(f)); SAXSource saxSource = new SAXSource(reader, new InputSource(stringReader)); // Prepare a DOMResult which will hold the DOM of the xjson DOMResult domResult = new DOMResult(); // Run SAX processing through a transformer // (This could be done more simply, but we have here the opportunity to pass our xjson through // an XSLT and get a legacy XML output ;) ) transformer.transform(saxSource, domResult); Node dom = domResult.getNode(); XPathFactory xpathFactory = XPathFactory.newInstance(); for (String x : expr) { try { XPath xpath = xpathFactory.newXPath(); xpath.setNamespaceContext(new NamespaceContext() { public Iterator getPrefixes(String namespaceURI) { return null; } public String getPrefix(String namespaceURI) { return null; } public String getNamespaceURI(String prefix) { if (prefix == null) { return XJSON.XMLNS; } else if ("j".equals(prefix)) { return XJSON.XMLNS; } else { return null; } } }); NodeList nl = (NodeList) xpath.evaluate(x, dom, XPathConstants.NODESET); System.out.println("-- Found " + nl.getLength() + " nodes for xpath '" + x + "' in file '" + f + "'"); for (int i = 0; i < nl.getLength(); i++) { System.out.println(" +(" + i + ")+ "); XMLJsonGenerator handler = new XMLJsonGenerator(); StringWriter buffer = new StringWriter(); handler.setOutputWriter(buffer); SAXResult result = new SAXResult(handler); transformer.transform(new DOMSource(nl.item(i)), result); System.out.println(buffer.toString()); } } catch (XPathExpressionException e) { System.err.println("-- Error evaluating '" + x + "' on file '" + f + "'"); e.printStackTrace(); } catch (TransformerException e) { System.err.println("-- Error evaluating '" + x + "' on file '" + f + "'"); e.printStackTrace(); } } } catch (FileNotFoundException e) { System.err.println("File '" + f + "' was not found"); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (TransformerException e) { e.printStackTrace(); } } } catch (TransformerConfigurationException e) { e.printStackTrace(); } } }
From source file:IOUtils.java
/** * Parse a file and send the sax events to the content handler. * @param file// w w w .j av a2 s.c o m * @param handler * @throws IOException * @throws TransformerException */ public static final void parse(File file, ContentHandler handler) throws IOException, TransformerException { final Transformer transformer = FACTORY.newTransformer(); transformer.transform(new StreamSource(new FileReader(file)), new SAXResult(handler)); }
From source file:net.sf.mcf2pdf.mcfelements.util.PdfUtil.java
/** * Converts an FO file to a PDF file using Apache FOP. * * @param fo the FO file//from w ww .jav a2s . co m * @param pdf the target PDF file * @param dpi the DPI resolution to use for bitmaps in the PDF * @throws IOException In case of an I/O problem * @throws FOPException In case of a FOP problem * @throws TransformerException In case of XML transformer problem */ @SuppressWarnings("rawtypes") public static void convertFO2PDF(InputStream fo, OutputStream pdf, int dpi) throws IOException, FOPException, TransformerException { FopFactory fopFactory = FopFactory.newInstance(); FOUserAgent foUserAgent = fopFactory.newFOUserAgent(); // configure foUserAgent as desired foUserAgent.setTargetResolution(dpi); // Setup output stream. Note: Using BufferedOutputStream // for performance reasons (helpful with FileOutputStreams). OutputStream out = new BufferedOutputStream(pdf); // Construct fop with desired output format Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out); // Setup JAXP using identity transformer TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(); // identity // transformer // Setup input stream Source src = new StreamSource(fo); // Resulting SAX events (the generated FO) must be piped through to FOP Result res = new SAXResult(fop.getDefaultHandler()); // Start XSLT transformation and FOP processing transformer.transform(src, res); // Result processing FormattingResults foResults = fop.getResults(); java.util.List pageSequences = foResults.getPageSequences(); for (java.util.Iterator it = pageSequences.iterator(); it.hasNext();) { PageSequenceResults pageSequenceResults = (PageSequenceResults) it.next(); log.debug("PageSequence " + (String.valueOf(pageSequenceResults.getID()).length() > 0 ? pageSequenceResults.getID() : "<no id>") + " generated " + pageSequenceResults.getPageCount() + " pages."); } log.info("Generated " + foResults.getPageCount() + " PDF pages in total."); out.flush(); }
From source file:org.opi.web.view.AbstractXslFoView.java
/** * Perform the actual transformation, writing to the HTTP response via the * FOP Driver.//from ww w. j a v a2 s.c o m */ protected void doTransform(Map model, Source source, HttpServletRequest request, HttpServletResponse response) throws Exception { response.setHeader("Content-Disposition", "inline"); response.setContentType("application/pdf"); FopFactory fopFactory = FopFactory.newInstance(); if (log.isInfoEnabled()) { log.info("ContextPath = " + request.getSession().getServletContext().getRealPath("/")); } OutputStream os = response.getOutputStream(); Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, os); Result intermediateFile = new SAXResult(fop.getDefaultHandler()); // Delegate to the superclass for the actual output having constructed the result. super.doTransform(source, getParameters(request), intermediateFile, response.getCharacterEncoding()); log.info("success"); }
From source file:gov.nih.nci.cabig.caaers.api.BasePDFGenerator.java
public synchronized void generatePdf(String xml, String pdfOutFileName, String XSLFile) throws Exception { FopFactory fopFactory = FopFactory.newInstance(); FOUserAgent foUserAgent = fopFactory.newFOUserAgent(); // configure foUserAgent as desired // Setup output OutputStream out = new java.io.FileOutputStream(pdfOutFileName); out = new java.io.BufferedOutputStream(out); try {// w w w . j a v a 2 s .c o m // Construct fop with desired output format Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out); // Setup XSLT TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = null; transformer = factory.newTransformer( new StreamSource(BasePDFGenerator.class.getClassLoader().getResourceAsStream(XSLFile))); // Set the value of a <param> in the stylesheet transformer.setParameter("versionParam", "2.0"); // Setup XML String as input for XSLT transformation Source src = new StreamSource(new ByteArrayInputStream(xml.getBytes("UTF-8"))); // Resulting SAX events (the generated FO) must be piped through to FOP Result res = new SAXResult(fop.getDefaultHandler()); // Start XSLT transformation and FOP processing transformer.transform(src, res); } finally { out.close(); } }
From source file:no.dusken.barweb.view.InvoiceView.java
protected void renderMergedOutputModel(Map model, HttpServletRequest request, HttpServletResponse response) throws Exception { response.setContentType("application/pdf"); response.setCharacterEncoding("UTF-8"); response.setHeader("Content-Disposition", "attachment; filename=faktura.pdf"); Map<BarPerson, Integer> persons = (Map<BarPerson, Integer>) model.get("persons"); Gjeng g = (Gjeng) model.get("gjeng"); Invoice invoice = (Invoice) model.get("invoice"); //Setup FOP/* ww w .j av a 2 s. c om*/ Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, response.getOutputStream()); //Setup Transformer Source xsltSrc = new StreamSource( this.getClass().getResourceAsStream("/no/dusken/barweb/stylesheets/" + styleSheet)); Transformer transformer = tFactory.newTransformer(xsltSrc); //Make sure the XSL transformation's result is piped through to FOP Result res = new SAXResult(fop.getDefaultHandler()); //Setup input DOMSource src = new DOMSource(generateXml(persons, g, invoice)); //Start the transformation and rendering process transformer.transform(src, res); response.getOutputStream().flush(); }