public static TransformerHandler createTransformerHandler(final ErrorListener errorListener, final boolean indentOutput) throws TransformerConfigurationException { final SAXTransformerFactory stf = (SAXTransformerFactory) TransformerFactoryFactory.newInstance(); if (errorListener != null) { stf.setErrorListener(errorListener); } final TransformerHandler th = stf.newTransformerHandler(); final Transformer transformer = th.getTransformer(); setCommonOutputProperties(transformer, indentOutput); if (errorListener != null) { transformer.setErrorListener(errorListener); } return th; }
public static <T> String marshal(final JAXBContext context, final T obj, final XmlAdapter<?, ?>... adapters) { if (obj == null) { return null; } try { final ByteArrayOutputStream out = new ByteArrayOutputStream(); final Marshaller marshaller = context.createMarshaller(); if (adapters != null) { for (final XmlAdapter<?, ?> adapter : adapters) { marshaller.setAdapter(adapter); } } final TransformerHandler transformerHandler = XMLUtil.createTransformerHandler(true); transformerHandler.setResult(new StreamResult(out)); marshaller.marshal(obj, transformerHandler); return out.toString(String.valueOf(StandardCharsets.UTF_8)); } catch (final Throwable t) { throw new RuntimeException(t.getMessage(), t); } }
@Override public TransformerHandler getSerializer() { try { SAXTransformerFactory transformerFactory = buildTransformerFactory(); configure(transformerFactory); TransformerHandler transformer = buildTransformer(transformerFactory); configure(transformer.getTransformer()); return transformer; } catch (TransformerConfigurationException ex) { throw new FluentXmlConfigurationException(ex); } }
private Result buildSingleTransformerPipeline(Result result) { try { SAXTransformerFactory saxTransformerFactory = (SAXTransformerFactory) SAXTransformerFactory.newInstance(); TransformerHandler transformerHandler = saxTransformerFactory.newTransformerHandler(); if (result != null) { transformerHandler.setResult(result); } return new SAXResult(transformerHandler); } catch (TransformerConfigurationException ex) { throw new FluentXmlConfigurationException(ex); } }
private SAXResult toSAXResult(Result result) { if (result instanceof SAXResult) { return (SAXResult) result; } try { SAXTransformerFactory transformerFactory = (SAXTransformerFactory) SAXTransformerFactory.newInstance(); TransformerHandler transformerHandler = transformerFactory.newTransformerHandler(); transformerHandler.setResult(result); return new SAXResult(transformerHandler); } catch (TransformerConfigurationException ex) { throw new FluentXmlConfigurationException(ex); } }
/** * Performs identity transformation. */ public static <T extends Result> T identityTransform(Source src, T result) throws TransformerException, SAXException, ParserConfigurationException, IOException { if (src instanceof StreamSource) { // work around a bug in JAXP in JDK6u4 and earlier where the namespace processing // is not turned on by default StreamSource ssrc = (StreamSource) src; TransformerHandler th = ((SAXTransformerFactory) transformerFactory.get()).newTransformerHandler(); th.setResult(result); XMLReader reader = saxParserFactory.get().newSAXParser().getXMLReader(); reader.setContentHandler(th); reader.setProperty(LEXICAL_HANDLER_PROPERTY, th); reader.parse(toInputSource(ssrc)); } else { newTransformer().transform(src, result); } return result; }
/** * Performs identity transformation. * @param <T> * @param src * @param result * @return * @throws javax.xml.transform.TransformerException * @throws java.io.IOException * @throws org.xml.sax.SAXException * @throws javax.xml.parsers.ParserConfigurationException */ public static <T extends Result> T identityTransform(Source src, T result) throws TransformerException, SAXException, ParserConfigurationException, IOException { if (src instanceof StreamSource) { // work around a bug in JAXP in JDK6u4 and earlier where the namespace processing // is not turned on by default StreamSource ssrc = (StreamSource) src; TransformerHandler th = ((SAXTransformerFactory) transformerFactory.get()).newTransformerHandler(); th.setResult(result); XMLReader reader = saxParserFactory.get().newSAXParser().getXMLReader(); reader.setContentHandler(th); reader.setProperty(LEXICAL_HANDLER_PROPERTY, th); reader.parse(toInputSource(ssrc)); } else { newTransformer().transform(src, result); } return result; }
@Test public final void testXMLStackOverflowBug() throws TransformerConfigurationException, IOException, SAXException { try { SAXTransformerFactory stf = (SAXTransformerFactory) TransformerFactory.newInstance(); TransformerHandler ser = stf.newTransformerHandler(); ser.setResult(new StreamResult(System.out)); StringBuilder sb = new StringBuilder(4096); for (int x = 4096; x > 0; x--) { sb.append((char) x); } ser.characters(sb.toString().toCharArray(), 0, sb.toString().toCharArray().length); ser.endDocument(); } catch (StackOverflowError se) { se.printStackTrace(); Assert.fail("StackOverflow"); } }
@Test public void test() throws Exception { TransformerHandler th = ((SAXTransformerFactory) TransformerFactory.newInstance()).newTransformerHandler(); DOMResult result = new DOMResult(); th.setResult(result); th.startDocument(); th.startElement("", "root", "root", new AttributesImpl()); th.characters(new char[0], 0, 0); th.endElement("", "root", "root"); th.endDocument(); // there's no point in having empty text --- we should remove it Assert.assertEquals(0, ((Document) result.getNode()).getDocumentElement().getChildNodes().getLength()); }
/** * SAXTFactory.newTransformerhandler() method which takes SAXSource as * argument can be set to XMLReader. SAXSource has input XML file as its * input source. XMLReader has a transformer handler which write out the * result to output file. Test verifies output file is same as golden file. * * @throws Exception If any errors occur. */ @Test public void testcase01() throws Exception { String outputFile = USER_DIR + "saxtf001.out"; String goldFile = GOLDEN_DIR + "saxtf001GF.out"; try (FileOutputStream fos = new FileOutputStream(outputFile)) { XMLReader reader = XMLReaderFactory.createXMLReader(); SAXTransformerFactory saxTFactory = (SAXTransformerFactory) TransformerFactory.newInstance(); TransformerHandler handler = saxTFactory.newTransformerHandler(new StreamSource(XSLT_FILE)); Result result = new StreamResult(fos); handler.setResult(result); reader.setContentHandler(handler); reader.parse(XML_FILE); } assertTrue(compareWithGold(goldFile, outputFile)); }
/** * SAXTFactory.newTransformerhandler() method which takes SAXSource as * argument can be set to XMLReader. SAXSource has input XML file as its * input source. XMLReader has a content handler which write out the result * to output file. Test verifies output file is same as golden file. * * @throws Exception If any errors occur. */ @Test public void testcase02() throws Exception { String outputFile = USER_DIR + "saxtf002.out"; String goldFile = GOLDEN_DIR + "saxtf002GF.out"; try (FileOutputStream fos = new FileOutputStream(outputFile); FileInputStream fis = new FileInputStream(XSLT_FILE)) { XMLReader reader = XMLReaderFactory.createXMLReader(); SAXTransformerFactory saxTFactory = (SAXTransformerFactory) TransformerFactory.newInstance(); SAXSource ss = new SAXSource(); ss.setInputSource(new InputSource(fis)); TransformerHandler handler = saxTFactory.newTransformerHandler(ss); Result result = new StreamResult(fos); handler.setResult(result); reader.setContentHandler(handler); reader.parse(XML_FILE); } assertTrue(compareWithGold(goldFile, outputFile)); }
/** * Unit test for newTransformerhandler(Source). DcoumentBuilderFactory is * namespace awareness, DocumentBuilder parse xslt file as DOMSource. * * @throws Exception If any errors occur. */ @Test public void testcase03() throws Exception { String outputFile = USER_DIR + "saxtf003.out"; String goldFile = GOLDEN_DIR + "saxtf003GF.out"; try (FileOutputStream fos = new FileOutputStream(outputFile)) { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder docBuilder = dbf.newDocumentBuilder(); Document document = docBuilder.parse(new File(XSLT_FILE)); Node node = (Node)document; DOMSource domSource= new DOMSource(node); XMLReader reader = XMLReaderFactory.createXMLReader(); SAXTransformerFactory saxTFactory = (SAXTransformerFactory)TransformerFactory.newInstance(); TransformerHandler handler = saxTFactory.newTransformerHandler(domSource); Result result = new StreamResult(fos); handler.setResult(result); reader.setContentHandler(handler); reader.parse(XML_FILE); } assertTrue(compareWithGold(goldFile, outputFile)); }
/** * Test newTransformerHandler with a Template Handler. * * @throws Exception If any errors occur. */ public void testcase08() throws Exception { String outputFile = USER_DIR + "saxtf008.out"; String goldFile = GOLDEN_DIR + "saxtf008GF.out"; try (FileOutputStream fos = new FileOutputStream(outputFile)) { XMLReader reader = XMLReaderFactory.createXMLReader(); SAXTransformerFactory saxTFactory = (SAXTransformerFactory)TransformerFactory.newInstance(); TemplatesHandler thandler = saxTFactory.newTemplatesHandler(); reader.setContentHandler(thandler); reader.parse(XSLT_FILE); TransformerHandler tfhandler = saxTFactory.newTransformerHandler(thandler.getTemplates()); Result result = new StreamResult(fos); tfhandler.setResult(result); reader.setContentHandler(tfhandler); reader.parse(XML_FILE); } assertTrue(compareWithGold(goldFile, outputFile)); }
/** * Test newTransformerHandler with a Template Handler along with a relative * URI in the style-sheet file. * * @throws Exception If any errors occur. */ @Test public void testcase09() throws Exception { String outputFile = USER_DIR + "saxtf009.out"; String goldFile = GOLDEN_DIR + "saxtf009GF.out"; try (FileOutputStream fos = new FileOutputStream(outputFile)) { XMLReader reader = XMLReaderFactory.createXMLReader(); SAXTransformerFactory saxTFactory = (SAXTransformerFactory)TransformerFactory.newInstance(); TemplatesHandler thandler = saxTFactory.newTemplatesHandler(); thandler.setSystemId("file:///" + XML_DIR); reader.setContentHandler(thandler); reader.parse(XSLT_INCL_FILE); TransformerHandler tfhandler= saxTFactory.newTransformerHandler(thandler.getTemplates()); Result result = new StreamResult(fos); tfhandler.setResult(result); reader.setContentHandler(tfhandler); reader.parse(XML_FILE); } assertTrue(compareWithGold(goldFile, outputFile)); }
@Override protected TransformerHandler getTransformerHandler(String xslFileName) throws SAXException, ParserConfigurationException, TransformerConfigurationException, IOException { SAXTransformerFactory factory = (SAXTransformerFactory) TransformerFactory.newInstance(); factory.setURIResolver(uriResolver); TemplatesHandler templatesHandler = factory.newTemplatesHandler(); SAXParserFactory pFactory = SAXParserFactory.newInstance(); pFactory.setNamespaceAware(true); XMLReader xmlreader = pFactory.newSAXParser().getXMLReader(); // create the stylesheet input source InputSource xslSrc = new InputSource(xslFileName); xslSrc.setSystemId(filenameToURL(xslFileName)); // hook up the templates handler as the xsl content handler xmlreader.setContentHandler(templatesHandler); // call parse on the xsl input source xmlreader.parse(xslSrc); // extract the Templates object created from the xsl input source return factory.newTransformerHandler(templatesHandler.getTemplates()); }
public TransformerHandler getRAFilter(double min, double max) throws TransformerConfigurationException, SAXException, ParserConfigurationException, IOException { double raMin = RA_MIN; // hours double raMax = RA_MAX; // hours if (min < max) { if ((min >= RA_MIN && min <= RA_MAX) && (max >= RA_MIN && max <= RA_MAX)) { raMin = min; // set value of query raMax = max; // set value of query } } else { throw new IllegalArgumentException("min must be less than max.\n" + "min=" + min + ", max=" + max); } return ffact.newRAFilter(raMin, raMax); }
public TransformerHandler getRADECFilter(double rmin, double rmax, double dmin, double dmax) throws TransformerConfigurationException, SAXException, ParserConfigurationException, IOException { double raMin = RA_MIN; // hours double raMax = RA_MAX; // hours double decMin = DEC_MIN; // degrees double decMax = DEC_MAX; // degrees if (rmin < rmax && dmin < dmax) { if ((rmin >= RA_MIN && rmin <= RA_MAX) && (rmax >= RA_MIN && rmax <= RA_MAX)) { raMin = rmin; // set value of query raMax = rmax; // set value of query } if ((dmin >= DEC_MIN && dmin <= DEC_MAX) && (dmax >= DEC_MIN && dmax <= DEC_MAX)) { decMin = dmin; // set value of query decMax = dmax; // set value of query } } else { throw new IllegalArgumentException("min must be less than max.\n" + "rmin=" + rmin + ", rmax=" + rmax + ", dmin=" + dmin + ", dmax=" + dmax); } return ffact.newRADECFilter(raMin, raMax, decMin, decMax); }
/** * Ritorna una vista HTML sul file processato. L'estrazione del testo fa * perdere di fatto la formattazione contenuta nel word o nel PDF. La * versione HTML è una versione processabile ma che mantiene il formato * * @param file file da parsare * @return vista HTML formattato del contenuto del documento (privato delle * immagini) */ public String getHtmlFromFile(File file) { try { ByteArrayOutputStream out = new ByteArrayOutputStream(); SAXTransformerFactory factory = (SAXTransformerFactory) SAXTransformerFactory.newInstance(); TransformerHandler handler = factory.newTransformerHandler(); handler.getTransformer().setOutputProperty(OutputKeys.METHOD, "html"); handler.getTransformer().setOutputProperty(OutputKeys.INDENT, "yes"); handler.getTransformer().setOutputProperty(OutputKeys.ENCODING, "UTF-8"); handler.setResult(new StreamResult(out)); ExpandedTitleContentHandler handler1 = new ExpandedTitleContentHandler(handler); InputStream is = file.toURI().toURL().openStream(); adp.parse(is, handler1, new Metadata()); is.close(); return new String(out.toByteArray(), "UTF-8").replaceAll("<img .*?</img>", "").replaceAll("<img .*?/>", ""); } catch (TransformerConfigurationException | IllegalArgumentException | IOException | SAXException | TikaException ex) { return "!ERROR: " + ex.getLocalizedMessage(); } }
public MCRTransformedContent(MCRContent source, XMLReader reader, TransformerHandler transformerHandler, long transformerLastModified, MCRParameterCollector parameter, String fileName, String mimeType, String encoding, MCRXSLTransformer instance) throws IOException { this.source = source; this.reader = reader; this.transformerHandler = transformerHandler; LOGGER.info("Transformer lastModified: {}", transformerLastModified); LOGGER.info("Source lastModified : {}", source.lastModified()); this.lastModified = (transformerLastModified >= 0 && source.lastModified() >= 0) ? Math.max(transformerLastModified, source.lastModified()) : -1; this.eTag = generateETag(source, lastModified, parameter.hashCode()); this.name = fileName; this.mimeType = mimeType; this.encoding = encoding; this.instance = instance; }
private T getJAXBObject(MCRContent source, XMLReader reader, TransformerHandler transformerHandler) throws JAXBException, IOException, SAXException { checkContext(); JAXBResult result = new JAXBResult(context); transformerHandler.setResult(result); // Parse the source XML, and send the parse events to the // TransformerHandler. reader.parse(source.getInputSource()); Object parsedResult = result.getResult(); if (parsedResult instanceof JAXBElement<?>) { @SuppressWarnings("unchecked") JAXBElement<T> jaxbElement = (JAXBElement<T>) parsedResult; return jaxbElement.getValue(); } @SuppressWarnings("unchecked") T jaxbResult = (T) result.getResult(); return jaxbResult; }
@Test @Ignore public void testStx() throws Exception{ TransformerFactory tFactory = new TransformerFactoryImpl(); SAXTransformerFactory saxTFactory = (SAXTransformerFactory) tFactory; // of course the transformation source must be different TransformerHandler tHandler1 = saxTFactory.newTransformerHandler(new StreamSource("trans.stx")); XMLReader myReader = XMLReaderFactory.createXMLReader(); myReader.setContentHandler(tHandler1); ContentHandler mySerializer = null; tHandler1.setResult(new SAXResult(mySerializer)); }
/** * Returns the SAX transformer handler associated to the transform sheet. * * @return The SAX transformer handler. * @throws IOException */ public TransformerHandler getTransformerHandler() throws IOException { TransformerHandler result = null; Templates templates = getTemplates(); if (templates != null) { try { result = getSaxTransformerFactory().newTransformerHandler( templates); } catch (TransformerConfigurationException tce) { throw new IOException("Transformer configuration exception. " + tce.getMessage()); } } return result; }
/** * Constructs a <code>JDepend</code> instance with the specified writer. * Creates a new instance of JDependProcessorXML * * * @param writer Writer. */ public JDependProcessorXML2(PrintWriter writer) { super(writer); formatter = NumberFormat.getInstance(Locale.ENGLISH); formatter.setMaximumFractionDigits(2); try { SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance(); TransformerHandler hd = tf.newTransformerHandler(); Transformer serializer = hd.getTransformer(); serializer.setOutputProperty(OutputKeys.INDENT,"yes"); // use getWriter as transform result destination hd.setResult(new StreamResult(this.getWriter()) ); // create the XmlEmitter this.xmlEmitter = new XmlEmitter( hd ); } catch (TransformerConfigurationException tce) { throw new XmlEmitterException(tce); } }
/** * Creates result set reader for processing the rows to be exported. * * @param outputWriter * writer into export file * @param transformerHandler * SAX transformer handler for generating XML. <code>null</code> * if script format is not XML. * @param scriptType * the script type * @param table * the table to read rows from * * @return result set reader for processing the rows to be exported */ private ResultSetReader createResultSetReader(OutputStreamWriter outputWriter, TransformerHandler transformerHandler, ScriptType scriptType, Table table, String filepath) throws SQLException { Session targetSession = entityGraph.getTargetSession(); if (scriptType == ScriptType.INSERT) { if (ScriptFormat.DBUNIT_FLAT_XML.equals(CommandLineParser.getInstance().getScriptFormat())) { return new FlatXMLTransformer(table, transformerHandler, targetSession.getMetaData(), targetSession.dbms); }else if(ScriptFormat.LIQUIBASE_XML.equals(CommandLineParser.getInstance().getScriptFormat())){ return new LiquibaseXMLTransformer(table,transformerHandler,targetSession.getMetaData(), entityGraph, filepath, CommandLineParser.getInstance().xmlDatePattern, CommandLineParser.getInstance().xmlTimePattern, CommandLineParser.getInstance().xmlTimeStampPattern); } else { return new DMLTransformer(table, outputWriter, CommandLineParser.getInstance().upsertOnly, CommandLineParser.getInstance().numberOfEntities, targetSession.getMetaData(), targetSession); } } else { return new DeletionTransformer(table, outputWriter, CommandLineParser.getInstance().numberOfEntities, targetSession.getMetaData(), targetSession); } }
/** * If given method is @SAX_METHOD return cached (or new) Trax compatible * instance. otherwise return null. */ private TransformerHandler _resolve (final String method, final String href, final XMLReader reader) throws SAXException { if (CSTX.DEBUG) log.debug ("sax-filter : resolve '" + method + "'"); if (!available (method)) throw new SAXException ("Not supported filter-method!"); if ((reader != null) || (href != null)) throw new SAXException ("Attribute 'filter-src' not allowed for method '" + method + "'"); return new SAXWrapperHandler (); }
private TransformerHandler _resolve (final String method, final String href, final XMLReader reader, final Hashtable <String, Object> params) throws SAXException { if (CSTX.DEBUG) log.debug ("hppt-post-filter : resolve '" + method + "'"); if (!available (method)) throw new SAXException ("Not supported filter-method!"); if (reader != null || href != null) throw new SAXException ("Attribute 'filter-src' not allowed for method '" + method + "'"); final String v = String.valueOf (params.get ("target")); if (v == null) throw new SAXException ("Missing parameter 'target' for filter " + "method '" + method + "'"); return new HttpPostHandler (v); }
public TransformerHandler resolve (final String method, final String href, final String base, final URIResolver uriResolver, final ErrorListener errorListener, final Hashtable <String, Object> params) throws SAXException { if (METHOD.equals (method)) { if (href != null) throw new SAXException ("Specification of an external source '" + href + "' not allowed for " + method); skipUri = String.valueOf (params.get ("uri")); return this; } return null; }
public final ContentHandler createContentHandler() { try { TransformerHandler handler = saxtf .newTransformerHandler(templates); handler.setResult(new SAXResult(outputHandler)); return handler; } catch (TransformerConfigurationException ex) { throw new RuntimeException(ex.toString()); } }
private static void prettyPrintXML(final Reader reader, final Writer writer) { try { final TransformerHandler handler = createTransformerHandler(new FatalErrorListener(), true); handler.setResult(new StreamResult(writer)); final SAXParser parser = PARSER_FACTORY.newSAXParser(); final XMLReader xmlReader = parser.getXMLReader(); xmlReader.setErrorHandler(new FatalErrorHandler()); xmlReader.setContentHandler(handler); xmlReader.parse(new InputSource(reader)); } catch (final Exception e) { throw new RuntimeException(e); } }
private TransformNode withStylesheet(Source xslt) { try { SAXTransformerFactory saxTransformerFactory = (SAXTransformerFactory) SAXTransformerFactory.newInstance(); TransformerHandler xsltTransformer = saxTransformerFactory.newTransformerHandler(xslt); this.transformationChain.addTransformer(xsltTransformer); return this; } catch (TransformerException ex) { throw new FluentXmlProcessingException(ex); } }
private void serialize(Source source, Result result) { try { TransformerHandler serializer = serializerConfigurer.getSerializer(); serializer.getTransformer().transform(source, result); } catch (TransformerException ex) { throw new FluentXmlProcessingException(ex); } }