javax.xml.transform.sax.SAXTransformerFactory Java Examples

The following examples show how to use javax.xml.transform.sax.SAXTransformerFactory. 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: XmlUtil.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #2
Source File: SAXTFactoryTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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 #3
Source File: TemplatesFilterFactoryImpl.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@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());
}
 
Example #4
Source File: XmlUtil.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #5
Source File: XmlUtil.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #6
Source File: XmlUtil.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #7
Source File: Bug4515660.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testSAXTransformerFactory() throws TransformerConfigurationException {
    final String xsl = "<?xml version='1.0'?>\n" + "<xsl:stylesheet" + " xmlns:xsl='http://www.w3.org/1999/XSL/Transform'" + " version='1.0'>\n"
            + "   <xsl:template match='/'>Hello World!</xsl:template>\n" + "</xsl:stylesheet>\n";

    ReaderStub.used = false;

    TransformerFactory transFactory = TransformerFactory.newInstance();
    assertTrue(transFactory.getFeature(SAXTransformerFactory.FEATURE));

    InputSource in = new InputSource(new StringReader(xsl));
    SAXSource source = new SAXSource(in);

    transFactory.newTransformer(source);
    assertTrue(ReaderStub.used);

}
 
Example #8
Source File: XmlUtil.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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).newTransformerHandler();
        th.setResult(result);
        XMLReader reader = saxParserFactory.newSAXParser().getXMLReader();
        reader.setContentHandler(th);
        reader.setProperty(LEXICAL_HANDLER_PROPERTY, th);
        reader.parse(toInputSource(ssrc));
    } else {
        newTransformer().transform(src, result);
    }
    return result;
}
 
Example #9
Source File: XmlUtil.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #10
Source File: SchemaToXML.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
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 #11
Source File: XSLTTransformer.java    From syncope with Apache License 2.0 6 votes vote down vote up
private void load(final Source source, final String localCacheKey, final Map<String, Object> attributes) {
    LOG.debug("{} local cache miss: {}", getClass().getSimpleName(), localCacheKey);

    // XSLT has to be parsed
    final SAXTransformerFactory transformerFactory;
    if (attributes == null || attributes.isEmpty()) {
        transformerFactory = TRAX_FACTORY;
    } else {
        transformerFactory = createNewSAXTransformerFactory();
        attributes.forEach(transformerFactory::setAttribute);
    }

    try {
        this.templates = transformerFactory.newTemplates(source);
    } catch (TransformerConfigurationException e) {
        throw new SetupException("Impossible to read XSLT from '" + source + "', see nested exception", e);
    }
}
 
Example #12
Source File: SAXTFactoryTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Unit test for contentHandler setter/getter with parent.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testcase11() throws Exception {
    String outputFile = USER_DIR + "saxtf011.out";
    String goldFile = GOLDEN_DIR + "saxtf011GF.out";
    // The transformer will use a SAX parser as it's reader.
    XMLReader reader = XMLReaderFactory.createXMLReader();
    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);

    SAXTransformerFactory saxTFactory
            = (SAXTransformerFactory)TransformerFactory.newInstance();
    XMLFilter filter = saxTFactory.newXMLFilter(domSource);

    filter.setParent(reader);
    filter.setContentHandler(new MyContentHandler(outputFile));

    // Now, when you call transformer.parse, it will set itself as
    // the content handler for the parser object (it's "parent"), and
    // will then call the parse method on the parser.
    filter.parse(new InputSource(XML_FILE));
    assertTrue(compareWithGold(goldFile, outputFile));
}
 
Example #13
Source File: DbObjectXMLTransformerTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Before
public void setUp()
{   
    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.STANDALONE, "no");

    writer = new StringWriter();
    xmlOut.setResult(new StreamResult(writer));
    
    transformer = new DbObjectXMLTransformer(xmlOut);        
}
 
Example #14
Source File: GeneralToSMTRunnerEventsConvertorTest.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void testPreserveFullOutputAfterImport() throws Exception {

    mySuite.addChild(mySimpleTest);
    for (int i = 0; i < 550; i++) {
      String message = "line" + i + "\n";
      mySimpleTest.addLast(printer -> printer.print(message, ConsoleViewContentType.NORMAL_OUTPUT));
    }
    mySimpleTest.setFinished();
    mySuite.setFinished();

    SAXTransformerFactory transformerFactory = (SAXTransformerFactory)TransformerFactory.newInstance();
    TransformerHandler handler = transformerFactory.newTransformerHandler();
    handler.getTransformer().setOutputProperty(OutputKeys.INDENT, "yes");
    handler.getTransformer().setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
    File output = FileUtil.createTempFile("output", "");
    try {
      FileUtilRt.createParentDirs(output);
      handler.setResult(new StreamResult(new FileWriter(output)));
      MockRuntimeConfiguration configuration = new MockRuntimeConfiguration(getProject());
      TestResultsXmlFormatter.execute(mySuite, configuration, new SMTRunnerConsoleProperties(configuration, "framework", new DefaultRunExecutor()), handler);

      String savedText = FileUtil.loadFile(output);
      assertTrue(savedText.split("\n").length > 550);

      myEventsProcessor.onStartTesting();
      ImportedToGeneralTestEventsConverter.parseTestResults(() -> new StringReader(savedText), myEventsProcessor);
      myEventsProcessor.onFinishTesting();

      List<? extends SMTestProxy> children = myResultsViewer.getTestsRootNode().getChildren();
      assertSize(1, children);
      SMTestProxy testProxy = children.get(0);
      MockPrinter mockPrinter = new MockPrinter();
      testProxy.printOn(mockPrinter);
      assertSize(550, mockPrinter.getAllOut().split("\n"));
    }
    finally {
      FileUtil.delete(output);
    }
  }
 
Example #15
Source File: TransformerPool.java    From iaf with Apache License 2.0 5 votes vote down vote up
public TransformerHandler getTransformerHandler() throws TransformerConfigurationException {
      TransformerHandler handler = ((SAXTransformerFactory)tFactory).newTransformerHandler(templates);
      Transformer transformer = handler.getTransformer();
      transformer.setErrorListener(new TransformerErrorListener());
		// Set URIResolver on transformer for Xalan. Setting it on the factory
		// doesn't work for Xalan. See
		// https://www.oxygenxml.com/archives/xsl-list/200306/msg00021.html
      transformer.setURIResolver(classLoaderURIResolver);
      return handler;
}
 
Example #16
Source File: JAXBContextImpl.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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: XCalWriter.java    From biweekly with BSD 2-Clause "Simplified" License 5 votes vote down vote up
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 #18
Source File: JAXBContextImpl.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates a new identity transformer.
 */
static Transformer createTransformer(boolean disableSecureProcessing) {
    try {
        SAXTransformerFactory tf = (SAXTransformerFactory)XmlFactory.createTransformerFactory(disableSecureProcessing);
        return tf.newTransformer();
    } catch (TransformerConfigurationException e) {
        throw new Error(e); // impossible
    }
}
 
Example #19
Source File: DomAnnotationParserFactory.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
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 #20
Source File: PipeTest.java    From rice with Educational Community License v2.0 5 votes vote down vote up
@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 #21
Source File: FormatUtils.java    From Gander with Apache License 2.0 5 votes vote down vote up
public static CharSequence formatXml(String xml) {
    try {
        Transformer serializer = SAXTransformerFactory.newInstance().newTransformer();
        serializer.setOutputProperty(OutputKeys.INDENT, "yes");
        serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        Source xmlSource = new SAXSource(new InputSource(new ByteArrayInputStream(xml.getBytes())));
        StreamResult res = new StreamResult(new ByteArrayOutputStream());
        serializer.transform(xmlSource, res);
        return new String(((ByteArrayOutputStream) res.getOutputStream()).toByteArray());
    } catch (Exception e) {
        Logger.e("non xml content", e);
        return xml;
    }
}
 
Example #22
Source File: SAXTFactoryTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Unit test newTransformerHandler with a DOMSource.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testcase06() throws Exception {
    String outputFile = USER_DIR + "saxtf006.out";
    String goldFile = GOLDEN_DIR + "saxtf006GF.out";

    try (FileOutputStream fos = new FileOutputStream(outputFile)) {
        XMLReader reader = XMLReaderFactory.createXMLReader();
        SAXTransformerFactory saxTFactory
                = (SAXTransformerFactory)TransformerFactory.newInstance();

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DocumentBuilder docBuilder = dbf.newDocumentBuilder();
        Node node = (Node)docBuilder.parse(new File(XSLT_INCL_FILE));

        DOMSource domSource = new DOMSource(node, "file:///" + XML_DIR);
        TransformerHandler handler =
                    saxTFactory.newTransformerHandler(domSource);

        Result result = new StreamResult(fos);
        handler.setResult(result);
        reader.setContentHandler(handler);
        reader.parse(XML_FILE);
    }
    assertTrue(compareWithGold(goldFile, outputFile));
}
 
Example #23
Source File: DomAnnotationParserFactory.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
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 #24
Source File: MessageOutputStreamTest.java    From iaf with Apache License 2.0 5 votes vote down vote up
@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 #25
Source File: JAXBContextImpl.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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 #26
Source File: MCRXSLTransformer.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
public synchronized void setTransformerFactory(String factoryClass) throws TransformerFactoryConfigurationError {
    TransformerFactory transformerFactory = Optional.ofNullable(factoryClass)
        .map(c -> TransformerFactory.newInstance(c, MCRClassTools.getClassLoader()))
        .orElseGet(TransformerFactory::newInstance);
    LOGGER.debug("Transformerfactory: {}", transformerFactory.getClass().getName());
    transformerFactory.setURIResolver(URI_RESOLVER);
    transformerFactory.setErrorListener(MCRErrorListener.getInstance());
    if (transformerFactory.getFeature(SAXSource.FEATURE) && transformerFactory.getFeature(SAXResult.FEATURE)) {
        this.tFactory = (SAXTransformerFactory) transformerFactory;
    } else {
        throw new MCRConfigurationException("Transformer Factory " + transformerFactory.getClass().getName()
            + " does not implement SAXTransformerFactory");
    }
}
 
Example #27
Source File: Bug5072946.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Tests if the identity transformer correctly sets the output node.
 */
@Test
public void test2() throws Exception {
    SAXTransformerFactory sf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
    TransformerHandler th = sf.newTransformerHandler();
    DOMResult r = new DOMResult();
    th.setResult(r);

    XMLReader reader = XMLReaderFactory.createXMLReader();
    reader.setContentHandler(th);
    reader.parse(new InputSource(Bug5072946.class.getResourceAsStream("Bug5072946.xml")));

    Assert.assertNotNull(r.getNode());
}
 
Example #28
Source File: IvyArtifactReport.java    From ant-ivy with Apache License 2.0 5 votes vote down vote up
private TransformerHandler createTransformerHandler(FileOutputStream fileOutputStream)
        throws TransformerFactoryConfigurationError, TransformerConfigurationException {
    SAXTransformerFactory transformerFact = (SAXTransformerFactory) SAXTransformerFactory
            .newInstance();
    TransformerHandler saxHandler = transformerFact.newTransformerHandler();
    saxHandler.getTransformer().setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    saxHandler.getTransformer().setOutputProperty(OutputKeys.INDENT, "yes");
    saxHandler.setResult(new StreamResult(fileOutputStream));
    return saxHandler;
}
 
Example #29
Source File: TransformerChainFactory.java    From citygml4j with Apache License 2.0 5 votes vote down vote up
public TransformerChainFactory(Templates[] templates) throws TransformerConfigurationException {
	if (templates == null || templates.length == 0)
		throw new IllegalArgumentException("no transformation templates provided.");
			
	this.templates = templates;		
	this.factory = (SAXTransformerFactory)TransformerFactory.newInstance();
}
 
Example #30
Source File: DOMResultTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Unit test for simple DOM parsing.
 * @throws Exception If any errors occur.
 */
@Test
public void testcase01() throws Exception {
    String resultFile = USER_DIR  + "domresult01.out";
    String goldFile = GOLDEN_DIR  + "domresult01GF.out";
    String xsltFile = XML_DIR + "cities.xsl";
    String xmlFile = XML_DIR + "cities.xml";

    XMLReader reader = XMLReaderFactory.createXMLReader();
    SAXTransformerFactory saxTFactory
            = (SAXTransformerFactory) TransformerFactory.newInstance();
    SAXSource saxSource = new SAXSource(new InputSource(xsltFile));
    TransformerHandler handler
            = saxTFactory.newTransformerHandler(saxSource);

    DOMResult result = new DOMResult();

    handler.setResult(result);
    reader.setContentHandler(handler);
    reader.parse(xmlFile);

    Node node = result.getNode();
    try (BufferedWriter writer = new BufferedWriter(new FileWriter(resultFile))) {
        writeNodes(node, writer);
    }
    assertTrue(compareWithGold(goldFile, resultFile));
}