Java Code Examples for javax.xml.transform.sax.SAXResult#setHandler()

The following examples show how to use javax.xml.transform.sax.SAXResult#setHandler() . 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: DocumentBuilderFactoryTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Test for the isIgnoringElementContentWhitespace and the
 * setIgnoringElementContentWhitespace. The xml file has all kinds of
 * whitespace,tab and newline characters, it uses the MyNSContentHandler
 * which does not invoke the characters callback when this
 * setIgnoringElementContentWhitespace is set to true.
 * @throws Exception If any errors occur.
 */
@Test
public void testCheckElementContentWhitespace() throws Exception {
    String goldFile = GOLDEN_DIR + "dbfactory02GF.out";
    String outputFile = USER_DIR + "dbfactory02.out";
    MyErrorHandler eh = MyErrorHandler.newInstance();
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(true);
    assertFalse(dbf.isIgnoringElementContentWhitespace());
    dbf.setIgnoringElementContentWhitespace(true);
    DocumentBuilder db = dbf.newDocumentBuilder();
    db.setErrorHandler(eh);
    Document doc = db.parse(new File(XML_DIR, "DocumentBuilderFactory06.xml"));
    assertFalse(eh.isErrorOccured());
    DOMSource domSource = new DOMSource(doc);
    TransformerFactory tfactory = TransformerFactory.newInstance();
    Transformer transformer = tfactory.newTransformer();
    SAXResult saxResult = new SAXResult();
    try(MyCHandler handler = MyCHandler.newInstance(new File(outputFile))) {
        saxResult.setHandler(handler);
        transformer.transform(domSource, saxResult);
    }
    assertTrue(compareWithGold(goldFile, outputFile));
}
 
Example 2
Source File: XSLTTransformer.java    From syncope with Apache License 2.0 5 votes vote down vote up
@Override
protected void setSAXConsumer(final SAXConsumer consumer) {
    TransformerHandler transformerHandler;
    try {
        transformerHandler = TRAX_FACTORY.newTransformerHandler(this.templates);
    } catch (Exception e) {
        throw new SetupException("Could not initialize transformer handler.", e);
    }

    if (this.parameters != null) {
        final Transformer transformer = transformerHandler.getTransformer();

        this.parameters.forEach((name, values) -> {
            // is valid XSLT parameter name
            if (XSLT_PARAMETER_NAME_PATTERN.matcher(name).matches()) {
                transformer.setParameter(name, values);
            }
        });
    }

    final SAXResult result = new SAXResult();
    result.setHandler(consumer);
    // According to TrAX specs, all TransformerHandlers are LexicalHandlers
    result.setLexicalHandler(consumer);
    transformerHandler.setResult(result);

    final SAXConsumerAdapter saxConsumerAdapter = new SAXConsumerAdapter();
    saxConsumerAdapter.setContentHandler(transformerHandler);
    super.setSAXConsumer(saxConsumerAdapter);
}
 
Example 3
Source File: TransformerFilter.java    From iaf with Apache License 2.0 5 votes vote down vote up
public TransformerFilter(INamedObject owner, TransformerHandler transformerHandler, ThreadLifeCycleEventListener<Object> threadLifeCycleEventListener, IPipeLineSession session, boolean expectChildThreads, ContentHandler handler) {
	super(transformerHandler);
	if (expectChildThreads) {
		handler = new ThreadConnectingFilter(owner, threadLifeCycleEventListener, session, handler);
	}
	SAXResult transformedStream = new SAXResult();
	transformedStream.setHandler(handler);
	if (handler instanceof LexicalHandler) {
		transformedStream.setLexicalHandler((LexicalHandler)handler);
	}
	this.transformerHandler=transformerHandler;
	transformerHandler.setResult(transformedStream);
}
 
Example 4
Source File: XsltStreamingTest.java    From iaf with Apache License 2.0 5 votes vote down vote up
@Test()
public void testStreamingXsltViaStreamSource() throws SAXException, DomBuilderException, TransformerException, IOException {
	/*
	 * create transformer
	 * feed SAX source events
	 * receive SAX destination events
	 * received events and source events should be mixed
	 */
	Assume.assumeTrue("Streaming XSLT switched off", AppConstants.getInstance().getBoolean("xslt.streaming.default", true));
	SwitchCounter sc = new SwitchCounter();
	
	String xpath="/root/a";
	TransformerPool tp = TransformerPool.getInstance(XmlUtils.createXPathEvaluatorSource(null, xpath,"xml", false, null, false, false, null, 1));
	
	SAXResult result = new SAXResult();
	SaxLogger resultfilter = new SaxLogger("out>", sc);
	result.setHandler(resultfilter);

	String input="<root>";
	for (int i=0;i<5;i++) {
		input+="<a>"+i+"</a>"+"<b>opvulling</b>";
	}
	input+="</root>";
	
	ByteArrayInputStream bais = new ByteArrayInputStream(input.getBytes());
	Source source = new StreamSource(new LoggingInputStream(bais,sc));
	
	tp.transform(source, result);
	assertTrue("switch count ["+sc.count+"] should be larger than 2",sc.count>2);
}
 
Example 5
Source File: ValidatorTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
private Result getSAXResult() {
    SAXResult saxResult = new SAXResult();
    saxResult.setHandler(new DefaultHandler());
    return saxResult;
}
 
Example 6
Source File: TransformTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
private SAXResult getHandlerSAXResult() {
    SAXResult res = new SAXResult();
    MyContentHandler myContentHandler = new MyContentHandler(transOutputStream());
    res.setHandler(myContentHandler);
    return res;
}
 
Example 7
Source File: XSLTEntityHandler.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
public ContentHandler getOutputHandler(OutputStream out) throws IOException
{
	if (!isAvailable()) return null;

	try
	{
		XSLTTransform xsltTransform = (XSLTTransform) transformerHolder.get();
		if (xsltTransform == null)
		{
			xsltTransform = new XSLTTransform();
			xsltTransform.setXslt(new InputSource(this.getClass()
					.getResourceAsStream(xslt)));
			transformerHolder.set(xsltTransform);
		}
		SAXResult sr = new SAXResult();
		
		TransformerHandler th = xsltTransform.getContentHandler();
		
		Transformer transformer = th.getTransformer();
		if (transformParameters != null) {
			for (Map.Entry<String, String> entry: transformParameters.entrySet()) {
				transformer.setParameter(entry.getKey(), entry.getValue());
			}
		}

		Properties p = OutputPropertiesFactory.getDefaultMethodProperties("xml");
		p.putAll(outputProperties);
		
		/*
		S_KEY_CONTENT_HANDLER:{http://xml.apache.org/xalan}content-handler
			S_KEY_ENTITIES:{http://xml.apache.org/xalan}entities
			S_KEY_INDENT_AMOUNT:{http://xml.apache.org/xalan}indent-amount
			S_OMIT_META_TAG:{http://xml.apache.org/xalan}omit-meta-tag
			S_USE_URL_ESCAPING:{http://xml.apache.org/xalan}use-url-escaping
		*/
		
		Serializer s = SerializerFactory.getSerializer(p);
		s.setOutputStream(out);
		sr.setHandler(s.asContentHandler());
		th.setResult(sr);
		return th;
	}
	catch (Exception ex)
	{
		throw new RuntimeException("Failed to create Content Handler", ex); //$NON-NLS-1$
		/*
		 * String stackTrace = null; try { StringWriter exw = new
		 * StringWriter(); PrintWriter pw = new PrintWriter(exw);
		 * log.error(ex.getMessage(), ex); stackTrace = exw.toString(); } catch
		 * (Exception ex2) { stackTrace =
		 * MessageFormat.format(defaultStackTrace, new Object[] {
		 * ex.getMessage() }); } out.write(MessageFormat.format(errorFormat,
		 * new Object[] { ex.getMessage(), stackTrace }));
		 */
	}
}
 
Example 8
Source File: XSLTEntityHandler.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
public ContentHandler getOutputHandler(OutputStream out) throws IOException
{
	if (!isAvailable()) return null;

	try
	{
		XSLTTransform xsltTransform = (XSLTTransform) transformerHolder.get();
		if (xsltTransform == null)
		{
			xsltTransform = new XSLTTransform();
			xsltTransform.setXslt(new InputSource(this.getClass()
					.getResourceAsStream(xslt)));
			transformerHolder.set(xsltTransform);
		}
		SAXResult sr = new SAXResult();
		
		TransformerHandler th = xsltTransform.getContentHandler();
		
		Transformer transformer = th.getTransformer();
		if (transformParameters != null) {
			for (Map.Entry<String, String> entry: transformParameters.entrySet()) {
				transformer.setParameter(entry.getKey(), entry.getValue());
			}
		}

		Properties p = OutputPropertiesFactory.getDefaultMethodProperties("xml");
		p.putAll(outputProperties);
		
		/*
		S_KEY_CONTENT_HANDLER:{http://xml.apache.org/xalan}content-handler
			S_KEY_ENTITIES:{http://xml.apache.org/xalan}entities
			S_KEY_INDENT_AMOUNT:{http://xml.apache.org/xalan}indent-amount
			S_OMIT_META_TAG:{http://xml.apache.org/xalan}omit-meta-tag
			S_USE_URL_ESCAPING:{http://xml.apache.org/xalan}use-url-escaping
		*/
		
		Serializer s = SerializerFactory.getSerializer(p);
		s.setOutputStream(out);
		sr.setHandler(s.asContentHandler());
		th.setResult(sr);
		return th;
	}
	catch (Exception ex)
	{
		throw new RuntimeException("Failed to create Content Handler", ex); //$NON-NLS-1$
		/*
		 * String stackTrace = null; try { StringWriter exw = new
		 * StringWriter(); PrintWriter pw = new PrintWriter(exw);
		 * log.error(ex.getMessage(), ex); stackTrace = exw.toString(); } catch
		 * (Exception ex2) { stackTrace =
		 * MessageFormat.format(defaultStackTrace, new Object[] {
		 * ex.getMessage() }); } out.write(MessageFormat.format(errorFormat,
		 * new Object[] { ex.getMessage(), stackTrace }));
		 */
	}
}