Java Code Examples for javax.xml.transform.sax.SAXTransformerFactory#newTransformerHandler()
The following examples show how to use
javax.xml.transform.sax.SAXTransformerFactory#newTransformerHandler() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SAXTFactoryTest.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
/** * 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)); }
Example 2
Source File: SAXTFactoryTest.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
/** * 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)); }
Example 3
Source File: FindSCU.java From weasis-dicom-tools with Eclipse Public License 2.0 | 6 votes |
private TransformerHandler getTransformerHandler() throws Exception { SAXTransformerFactory tf = saxtf; if (tf == null) { saxtf = tf = (SAXTransformerFactory) TransformerFactory.newInstance(); tf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); } if (xsltFile == null) { return tf.newTransformerHandler(); } Templates tpls = xsltTpls; if (tpls == null) { xsltTpls = tpls = tf.newTemplates(new StreamSource(xsltFile)); } return tf.newTransformerHandler(tpls); }
Example 4
Source File: OpenJDK100017Test.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
@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"); } }
Example 5
Source File: SchemaToXML.java From alfresco-repository with GNU Lesser General Public License v3.0 | 6 votes |
public SchemaToXML(Schema schema, StreamResult streamResult) { final SAXTransformerFactory stf = (SAXTransformerFactory) TransformerFactory.newInstance(); try { xmlOut = stf.newTransformerHandler(); } catch (TransformerConfigurationException error) { throw new RuntimeException("Unable to create TransformerHandler.", error); } final Transformer t = xmlOut.getTransformer(); try { t.setOutputProperty("{http://xml.apache.org/xalan}indent-amount", "2"); } catch (final IllegalArgumentException e) { // It was worth a try } t.setOutputProperty(OutputKeys.INDENT, "yes"); t.setOutputProperty(OutputKeys.ENCODING, SchemaComparator.CHAR_SET); xmlOut.setResult(streamResult); this.schema = schema; }
Example 6
Source File: DomAnnotationParserFactory.java From jdk8u60 with GNU General Public License v2.0 | 5 votes |
AnnotationParserImpl(boolean disableSecureProcessing) { try { SAXTransformerFactory factory = stf.get(); factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, disableSecureProcessing); transformer = factory.newTransformerHandler(); } catch (TransformerConfigurationException e) { throw new Error(e); // impossible } }
Example 7
Source File: SAXTransformerFactoryTest.java From learnjavabug with MIT License | 5 votes |
public static void main(String[] args) throws TransformerConfigurationException { SAXTransformerFactory sf = (SAXTransformerFactory) SAXTransformerFactory.newInstance(); //todo 修复方式 // sf.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); // sf.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, ""); ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(Payloads.NO_FEEDBACK_SINGLE_LINE .getBytes()); StreamSource source = new StreamSource(byteArrayInputStream); sf.newTransformerHandler(source); }
Example 8
Source File: MessageOutputStreamTest.java From iaf with Apache License 2.0 | 5 votes |
@Test @Ignore("No contract to call endDocument() in case of an Exception") public void testX31ContentHandlerAsStreamError() throws Exception { CloseObservableOutputStream cos = new CloseObservableOutputStream() { @Override public void write(byte[] arg0, int arg1, int arg2) { throw new RuntimeException("fakeFailure"); } }; Result result = new StreamResult(cos); SAXTransformerFactory tf = (SAXTransformerFactory) TransformerFactory.newInstance(); TransformerHandler transformerHandler = tf.newTransformerHandler(); transformerHandler.setResult(result); try (MessageOutputStream stream = new MessageOutputStream(null, transformerHandler, (IForwardTarget)null, null, null)) { try { try (Writer writer = stream.asWriter()) { writer.write(testString); } fail("exception should be thrown"); } catch (Exception e) { assertThat(e.getMessage(),StringContains.containsString("fakeFailure")); } } assertTrue(cos.isCloseCalled()); }
Example 9
Source File: JAXBContextImpl.java From openjdk-jdk8u with GNU General Public License v2.0 | 5 votes |
/** * Creates a new identity transformer. */ public static TransformerHandler createTransformerHandler(boolean disableSecureProcessing) { try { SAXTransformerFactory tf = (SAXTransformerFactory)XmlFactory.createTransformerFactory(disableSecureProcessing); return tf.newTransformerHandler(); } catch (TransformerConfigurationException e) { throw new Error(e); // impossible } }
Example 10
Source File: MessageOutputStreamTest.java From iaf with Apache License 2.0 | 5 votes |
@Test @Ignore("No contract to call endDocument() in case of an Exception") public void testX32ContentHandlerAsWriterError() throws Exception { CloseObservableWriter cow = new CloseObservableWriter() { @Override public void write(char[] arg0, int arg1, int arg2) { throw new RuntimeException("fakeFailure"); } }; Result result = new StreamResult(cow); SAXTransformerFactory tf = (SAXTransformerFactory) TransformerFactory.newInstance(); TransformerHandler transformerHandler = tf.newTransformerHandler(); transformerHandler.setResult(result); try (MessageOutputStream stream = new MessageOutputStream(null, transformerHandler, (IForwardTarget)null, null, null)) { try { try (Writer writer = stream.asWriter()) { writer.write(testString); } fail("exception should be thrown"); } catch (Exception e) { assertThat(e.getMessage(),StringContains.containsString("fakeFailure")); } } assertTrue(cow.isCloseCalled()); }
Example 11
Source File: TikaPoweredContentTransformer.java From alfresco-repository with GNU Lesser General Public License v3.0 | 5 votes |
/** * Returns an appropriate Tika ContentHandler for the * requested content type. Normally you'll let this * work as default, but if you need fine-grained * control of how the Tika events become text then * override and supply your own. */ protected ContentHandler getContentHandler(String targetMimeType, Writer output) throws TransformerConfigurationException { if(MimetypeMap.MIMETYPE_TEXT_PLAIN.equals(targetMimeType)) { return new BodyContentHandler(output); } SAXTransformerFactory factory = (SAXTransformerFactory) SAXTransformerFactory.newInstance(); TransformerHandler handler = factory.newTransformerHandler(); handler.getTransformer().setOutputProperty(OutputKeys.INDENT, "yes"); handler.setResult(new StreamResult(output)); if(MimetypeMap.MIMETYPE_HTML.equals(targetMimeType)) { handler.getTransformer().setOutputProperty(OutputKeys.METHOD, "html"); return new ExpandedTitleContentHandler(handler); } else if(MimetypeMap.MIMETYPE_XHTML.equals(targetMimeType) || MimetypeMap.MIMETYPE_XML.equals(targetMimeType)) { handler.getTransformer().setOutputProperty(OutputKeys.METHOD, "xml"); } else { throw new TransformerInfoException( WRONG_FORMAT_MESSAGE_ID, new IllegalArgumentException("Requested target type " + targetMimeType + " not supported") ); } return handler; }
Example 12
Source File: JAXBContextImpl.java From jdk8u60 with GNU General Public License v2.0 | 5 votes |
/** * Creates a new identity transformer. */ public static TransformerHandler createTransformerHandler(boolean disableSecureProcessing) { try { SAXTransformerFactory tf = (SAXTransformerFactory)XmlFactory.createTransformerFactory(disableSecureProcessing); return tf.newTransformerHandler(); } catch (TransformerConfigurationException e) { throw new Error(e); // impossible } }
Example 13
Source File: PipeTest.java From rice with Educational Community License v2.0 | 5 votes |
@Test public void testPipe() 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(PipeTest.class.getResourceAsStream("foo1.xsl"))); TransformerHandler tHandler2 = saxTFactory.newTransformerHandler(new StreamSource(PipeTest.class.getResourceAsStream("foo2.xsl"))); TransformerHandler tHandler3 = saxTFactory.newTransformerHandler(new StreamSource(PipeTest.class.getResourceAsStream("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(new InputSource(PipeTest.class.getResourceAsStream("foo.xml"))); } }
Example 14
Source File: XCalWriter.java From biweekly with BSD 2-Clause "Simplified" License | 5 votes |
private XCalWriter(Writer writer, Node parent, Map<String, String> outputProperties) { this.writer = writer; if (parent instanceof Document) { Node root = parent.getFirstChild(); if (root != null) { parent = root; } } this.icalendarElementExists = isICalendarElement(parent); try { SAXTransformerFactory factory = (SAXTransformerFactory) TransformerFactory.newInstance(); handler = factory.newTransformerHandler(); } catch (TransformerConfigurationException e) { throw new RuntimeException(e); } Transformer transformer = handler.getTransformer(); /* * Using Transformer#setOutputProperties(Properties) doesn't work for * some reason for setting the number of indentation spaces. */ for (Map.Entry<String, String> entry : outputProperties.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); transformer.setOutputProperty(key, value); } Result result = (writer == null) ? new DOMResult(parent) : new StreamResult(writer); handler.setResult(result); }
Example 15
Source File: TikaLambdaHandler.java From tika-lambda with Apache License 2.0 | 5 votes |
private String doTikaStuff(String bucket, String key, InputStream objectData) throws IOException, TransformerConfigurationException, SAXException { _logger.log("Extracting text with Tika"); String extractedText = ""; SAXTransformerFactory factory = (SAXTransformerFactory)SAXTransformerFactory.newInstance(); TransformerHandler handler = factory.newTransformerHandler(); handler.getTransformer().setOutputProperty(OutputKeys.METHOD, "text"); handler.getTransformer().setOutputProperty(OutputKeys.INDENT, "yes"); StringWriter sw = new StringWriter(); handler.setResult(new StreamResult(sw)); AutoDetectParser parser = new AutoDetectParser(); ParseContext parseContext = new ParseContext(); parseContext.set(Parser.class, parser); Tika tika = new Tika(); Metadata tikaMetadata = new Metadata(); try { // for synthetic transactions if( key.toLowerCase().endsWith("tika.exception.testing.pdf")) { throw new TikaException("Test Tika Exception"); } parser.parse(objectData, handler, tikaMetadata, parseContext); extractedText = sw.toString(); } catch( TikaException e) { _logger.log("TikaException thrown while parsing: " + e.getLocalizedMessage()); return assembleExceptionResult(bucket, key, e); } _logger.log("Tika parsing success"); return assembleExtractionResult(bucket, key, extractedText, tikaMetadata); }
Example 16
Source File: JAXBContextImpl.java From hottub with GNU General Public License v2.0 | 5 votes |
/** * Creates a new identity transformer. */ public static TransformerHandler createTransformerHandler(boolean disableSecureProcessing) { try { SAXTransformerFactory tf = (SAXTransformerFactory)XmlFactory.createTransformerFactory(disableSecureProcessing); return tf.newTransformerHandler(); } catch (TransformerConfigurationException e) { throw new Error(e); // impossible } }
Example 17
Source File: JAXBContextImpl.java From TencentKona-8 with GNU General Public License v2.0 | 5 votes |
/** * Creates a new identity transformer. */ public static TransformerHandler createTransformerHandler(boolean disableSecureProcessing) { try { SAXTransformerFactory tf = (SAXTransformerFactory)XmlFactory.createTransformerFactory(disableSecureProcessing); return tf.newTransformerHandler(); } catch (TransformerConfigurationException e) { throw new Error(e); // impossible } }
Example 18
Source File: TableToXML.java From ramus with GNU General Public License v3.0 | 4 votes |
public void store() throws IOException, TransformerConfigurationException, SAXException { SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory .newInstance(); th = tf.newTransformerHandler(); StreamResult result = new StreamResult(stream); th.setResult(result); th.startDocument(); attrs.addAttribute("", "", "generate-from-table", "CDATA", tableName); attrs.addAttribute("", "", "generate-time", "CDATA", new Date() .toString()); attrs.addAttribute("", "", "prefix", "CDATA", prefix); startElement("table"); attrs.clear(); template.execute(new JDBCCallback() { @Override public Object execute(Connection connection) throws SQLException { Statement st = connection.createStatement(); ResultSet rs = st.executeQuery("SELECT * FROM " + prefix + tableName); ResultSetMetaData meta = rs.getMetaData(); startElement("fields"); int cc = meta.getColumnCount(); Converter[] converters = new Converter[cc]; for (int i = 0; i < cc; i++) { attrs.addAttribute("", "", "id", "CDATA", Integer .toString(i)); attrs.addAttribute("", "", "name", "CDATA", meta .getColumnName(i + 1)); attrs.addAttribute("", "", "type", "CDATA", meta .getColumnTypeName(i + 1)); startElement("field"); attrs.clear(); endElement("field"); if ((meta.getColumnType(i + 1) == Types.BLOB) || (meta.getColumnType(i + 1) == Types.VARBINARY) || (meta.getColumnTypeName(i + 1) .equalsIgnoreCase("bytea"))) { converters[i] = new ByteAConverter(); } else if (meta.getColumnType(i + 1) == Types.CLOB) { converters[i] = new ToStringConverter(); } else if (meta.getColumnTypeName(i + 1).equalsIgnoreCase( "bool")) { converters[i] = new BoolConverter(); } else if (meta.getColumnTypeName(i + 1).equalsIgnoreCase( "timestamp")) { converters[i] = new DateConverter(); } else { converters[i] = new ToStringConverter(); } } endElement("fields"); startElement("data"); while (resultSetNext(rs)) { startElement("row"); for (int i = 0; i < cc; i++) { Object object; if (converters[i] instanceof BoolConverter) object = rs.getBoolean(i + 1); else if (converters[i] instanceof ToStringConverter) object = rs.getString(i + 1); else if (converters[i] instanceof ByteAConverter) object = rs.getBytes(i + 1); else object = rs.getObject(i + 1); if (object != null) { attrs.addAttribute("", "", "id", "CDATA", Integer .toString(i)); startElement("f"); attrs.clear(); characters(converters[i].toString(object)); endElement("f"); } } endElement("row"); } endElement("data"); rs.close(); st.close(); return null; } }); endElement("table"); th.endDocument(); }
Example 19
Source File: TransformerUtil.java From jlibs with Apache License 2.0 | 3 votes |
/** * Creates TransformerHandler * * @param source source of xsl document, use null for identity transformer * @param omitXMLDeclaration omit xml declaration or not * @param indentAmount the number fo spaces used for indentation. * use <=0, in case you dont want indentation * @param encoding required encoding. use null to don't set any encoding * * @return the same transformer which is passed as argument */ public static TransformerHandler newTransformerHandler(Source source, boolean omitXMLDeclaration, int indentAmount, String encoding) throws TransformerConfigurationException{ SAXTransformerFactory factory = (SAXTransformerFactory)TransformerFactory.newInstance(); TransformerHandler handler = source!=null ? factory.newTransformerHandler(source) : factory.newTransformerHandler(); setOutputProperties(handler.getTransformer(), omitXMLDeclaration, indentAmount, encoding); return handler; }
Example 20
Source File: UserParameterSaveHandler.java From mzmine3 with GNU General Public License v2.0 | 2 votes |
/** * Function which creates an XML file with user parameters */ void saveParameters() throws SAXException, IOException, TransformerConfigurationException { logger.info("Saving user parameters"); StreamResult streamResult = new StreamResult(finalStream); SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance(); TransformerHandler hd = tf.newTransformerHandler(); Transformer serializer = hd.getTransformer(); serializer.setOutputProperty(OutputKeys.INDENT, "yes"); serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); hd.setResult(streamResult); hd.startDocument(); UserParameter<?, ?> projectParameters[] = project.getParameters(); AttributesImpl atts = new AttributesImpl(); atts.addAttribute("", "", UserParameterElementName.COUNT.getElementName(), "CDATA", String.valueOf(projectParameters.length)); hd.startElement("", "", UserParameterElementName.PARAMETERS.getElementName(), atts); atts.clear(); // <PARAMETER> for (UserParameter<?, ?> parameter : project.getParameters()) { if (canceled) return; logger.finest("Saving user parameter " + parameter.getName()); atts.addAttribute("", "", UserParameterElementName.NAME.getElementName(), "CDATA", parameter.getName()); atts.addAttribute("", "", UserParameterElementName.TYPE.getElementName(), "CDATA", parameter.getClass().getSimpleName()); hd.startElement("", "", UserParameterElementName.PARAMETER.getElementName(), atts); atts.clear(); fillParameterElement(parameter, hd); hd.endElement("", "", UserParameterElementName.PARAMETER.getElementName()); completedParameters++; } hd.endElement("", "", UserParameterElementName.PARAMETERS.getElementName()); hd.endDocument(); }