use of javax.xml.transform.stream.StreamSource in project gocd by gocd.
the class XsltStylesheet method getTemplatesFromStreamSource.
private Templates getTemplatesFromStreamSource() throws TransformerConfigurationException {
if (stylesheet instanceof RubyString) {
StringReader reader = new StringReader((String) stylesheet.toJava(String.class));
StreamSource xsltStreamSource = new StreamSource(reader);
return factory.newTemplates(xsltStreamSource);
}
return null;
}
use of javax.xml.transform.stream.StreamSource in project gocd by gocd.
the class NUnitRDFizerTest method testShouldTransformFromXSLForNunit2Dot6ToJunitCorrectly.
@Test
public void testShouldTransformFromXSLForNunit2Dot6ToJunitCorrectly() throws Exception {
String nunitInputXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<!--\n" + "This file represents the results of running a test suite\n" + "-->\n" + "<test-results name=\"C:\\Program Files\\NUnit 2.6\\bin\\tests\\mock-assembly.dll\" total=\"21\" errors=\"1\" failures=\"1\" not-run=\"7\" inconclusive=\"1\" ignored=\"4\" skipped=\"0\" invalid=\"3\" date=\"2012-02-04\" time=\"11:46:05\">\n" + " <environment nunit-version=\"2.6.0.12035\" clr-version=\"2.0.50727.4963\" os-version=\"Microsoft Windows NT 6.1.7600.0\" platform=\"Win32NT\" cwd=\"C:\\Program Files\\NUnit 2.6\\bin\" machine-name=\"CHARLIE-LAPTOP\" user=\"charlie\" user-domain=\"charlie-laptop\" />\n" + " <culture-info current-culture=\"en-US\" current-uiculture=\"en-US\" />\n" + " <test-suite type=\"Assembly\" name=\"C:\\Program Files\\NUnit 2.6\\bin\\tests\\mock-assembly.dll\" executed=\"True\" result=\"Failure\" success=\"False\" time=\"0.094\" asserts=\"0\">\n" + " <results>\n" + " <test-suite type=\"Namespace\" name=\"NUnit\" executed=\"True\" result=\"Failure\" success=\"False\" time=\"0.078\" asserts=\"0\">\n" + " <results>\n" + " <test-suite type=\"Namespace\" name=\"Tests\" executed=\"True\" result=\"Failure\" success=\"False\" time=\"0.078\" asserts=\"0\">\n" + " <results>\n" + " <test-suite type=\"Namespace\" name=\"Assemblies\" executed=\"True\" result=\"Failure\" success=\"False\" time=\"0.031\" asserts=\"0\">\n" + " <results>\n" + " <test-suite type=\"TestFixture\" name=\"MockTestFixture\" description=\"Fake Test Fixture\" executed=\"True\" result=\"Failure\" success=\"False\" time=\"0.031\" asserts=\"0\">\n" + " <categories>\n" + " <category name=\"FixtureCategory\" />\n" + " </categories>\n" + " <results>\n" + " <test-case name=\"NUnit.Tests.Assemblies.MockTestFixture.TestWithException\" executed=\"True\" result=\"Error\" success=\"False\" time=\"0.000\" asserts=\"0\">\n" + " <failure>\n" + " <message>Intentional Error</message>\n" + " <stack-trace>Some Stack Trace</stack-trace>\n" + " </failure>\n" + " </test-case>\n" + " <test-case name=\"NUnit.Tests.Assemblies.MockTestFixture.FailingTest\" executed=\"True\" result=\"Failure\" success=\"False\" time=\"0.016\" asserts=\"0\">\n" + " <failure>\n" + " <message>Intentional failure</message>\n" + " <stack-trace>Some Stack Trace</stack-trace>\n" + " </failure>\n" + " </test-case>\n" + " <test-case name=\"NUnit.Tests.Assemblies.MockTestFixture.MockTest3\" executed=\"True\" result=\"Success\" success=\"True\" time=\"0.016\" asserts=\"0\">\n" + " <categories>\n" + " <category name=\"AnotherCategory\" />\n" + " <category name=\"MockCategory\" />\n" + " </categories>\n" + " <reason>\n" + " <message>Success</message>\n" + " </reason>\n" + " </test-case>\n" + " </results>\n" + " </test-suite>\n" + " </results>\n" + " </test-suite>\n" + " </results>\n" + " </test-suite>\n" + " </results>\n" + " </test-suite>\n" + " </results>\n" + " </test-suite>\n" + "</test-results>";
String expectedResultantJunitFormat = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<testsuites>" + "<testsuite name=\"NUnit.Tests.Assemblies.MockTestFixture\" tests=\"3\" time=\"0.031\" failures=\"1\" errors=\"1\" skipped=\"0\">" + "<testcase classname=\"NUnit.Tests.Assemblies.MockTestFixture\" name=\"TestWithException\" time=\"0.000\">" + "<error message=\"Intentional Error\">Some Stack Trace</error><" + "/testcase><testcase classname=\"NUnit.Tests.Assemblies.MockTestFixture\" name=\"FailingTest\" time=\"0.016\">" + "<failure message=\"Intentional failure\">Some Stack Trace</failure>" + "</testcase><testcase classname=\"NUnit.Tests.Assemblies.MockTestFixture\" name=\"MockTest3\" time=\"0.016\"/>" + "</testsuite>" + "</testsuites>";
try (InputStream xsl = getClass().getClassLoader().getResourceAsStream(XSLTTransformerRegistry.XUNIT_NUNIT_TO_JUNIT_XSL)) {
TransformerFactory transformerFactory = TransformerFactory.newInstance();
DocumentSource source = new DocumentSource(new SAXReader().read(new InputSource(new ByteArrayInputStream(nunitInputXml.getBytes("utf-8")))));
DocumentResult result = new DocumentResult();
Transformer transformer = transformerFactory.newTransformer(new StreamSource(xsl));
transformer.transform(source, result);
assertThat(result.getDocument().asXML(), isIdenticalTo(expectedResultantJunitFormat));
}
}
use of javax.xml.transform.stream.StreamSource in project gocd by gocd.
the class NUnitRDFizerTest method testShouldTransformFromXSLForNunit2Dot5AndEarlierToJunitCorrectly.
@Test
public void testShouldTransformFromXSLForNunit2Dot5AndEarlierToJunitCorrectly() throws Exception {
String nunitInputXml = "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"no\"?>" + "<!--This file represents the results of running a test suite-->" + "<test-results name=\"/home/erik/coding/test/nunittests/Tests.dll\" total=\"4\" failures=\"1\" not-run=\"0\" date=\"2007-07-27\" time=\"11:18:43\">" + " <environment nunit-version=\"2.2.8.0\" clr-version=\"2.0.50727.42\" os-version=\"Unix 2.6.18.4\" platform=\"Unix\" cwd=\"/home/erik/coding/test/nunittests\" machine-name=\"akira.ramfelt.se\" user=\"erik\" user-domain=\"akira.ramfelt.se\" />" + " <culture-info current-culture=\"sv-SE\" current-uiculture=\"sv-SE\" />" + " <test-suite name=\"/home/erik/coding/test/nunittests/Tests.dll\" success=\"False\" time=\"0.404\" asserts=\"0\">" + " <results>" + " <test-suite name=\"UnitTests\" success=\"False\" time=\"0.393\" asserts=\"0\">" + " <results>" + " <test-suite name=\"UnitTests.MainClassTest\" success=\"False\" time=\"0.289\" asserts=\"0\">" + " <results>" + " <test-case name=\"UnitTests.MainClassTest.TestPropertyValue\" executed=\"True\" success=\"True\" time=\"0.146\" asserts=\"1\" />" + " <test-case name=\"UnitTests.MainClassTest.TestMethodUpdateValue\" executed=\"True\" success=\"True\" time=\"0.001\" asserts=\"1\" />" + " <test-case name=\"UnitTests.MainClassTest.TestFailure\" executed=\"True\" success=\"False\" time=\"0.092\" asserts=\"1\" result=\"Failure\">" + " <failure>" + " <message><![CDATA[ Expected failure" + " Expected: 30" + " But was: 20" + "]]></message>" + " <stack-trace><![CDATA[ at UnitTests.MainClassTest.TestFailure () [0x00000] " + " at <0x00000> <unknown method>" + " at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[])" + " at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000] " + "]]></stack-trace>" + " </failure>" + " </test-case>" + " </results>" + " </test-suite>" + " </results>" + " </test-suite>" + " </results>" + " </test-suite>" + "</test-results>";
String expectedResultantJunitFormat = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<testsuites>" + "<testsuite name=\"UnitTests.MainClassTest\" tests=\"3\" time=\"0.289\" failures=\"1\" errors=\"\" skipped=\"0\">" + "<testcase classname=\"UnitTests.MainClassTest\" name=\"TestPropertyValue\" time=\"0.146\"/>" + "<testcase classname=\"UnitTests.MainClassTest\" name=\"TestMethodUpdateValue\" time=\"0.001\"/>" + "<testcase classname=\"UnitTests.MainClassTest\" name=\"TestFailure\" time=\"0.092\">" + "<failure message=\" Expected failure Expected: 30 But was: 20\"> " + "at UnitTests.MainClassTest.TestFailure () [0x00000] at <0x00000> <unknown method> at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[]) at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000] " + "</failure>" + "</testcase>" + "</testsuite>" + "</testsuites>";
try (InputStream xsl = getClass().getClassLoader().getResourceAsStream(XSLTTransformerRegistry.XUNIT_NUNIT_TO_JUNIT_XSL)) {
TransformerFactory transformerFactory = TransformerFactory.newInstance();
DocumentSource source = new DocumentSource(new SAXReader().read(new InputSource(new ByteArrayInputStream(nunitInputXml.getBytes("utf-8")))));
DocumentResult result = new DocumentResult();
Transformer transformer = transformerFactory.newTransformer(new StreamSource(xsl));
transformer.transform(source, result);
assertThat(result.getDocument().asXML(), isIdenticalTo(expectedResultantJunitFormat));
}
}
use of javax.xml.transform.stream.StreamSource in project j2objc by google.
the class DTMManagerDefault method getDTM.
/**
* Get an instance of a DTM, loaded with the content from the
* specified source. If the unique flag is true, a new instance will
* always be returned. Otherwise it is up to the DTMManager to return a
* new instance or an instance that it already created and may be being used
* by someone else.
*
* A bit of magic in this implementation: If the source is null, unique is true,
* and incremental and doIndexing are both false, we return an instance of
* SAX2RTFDTM, which see.
*
* (I think more parameters will need to be added for error handling, and entity
* resolution, and more explicit control of the RTF situation).
*
* @param source the specification of the source object.
* @param unique true if the returned DTM must be unique, probably because it
* is going to be mutated.
* @param whiteSpaceFilter Enables filtering of whitespace nodes, and may
* be null.
* @param incremental true if the DTM should be built incrementally, if
* possible.
* @param doIndexing true if the caller considers it worth it to use
* indexing schemes.
*
* @return a non-null DTM reference.
*/
public synchronized DTM getDTM(Source source, boolean unique, DTMWSFilter whiteSpaceFilter, boolean incremental, boolean doIndexing) {
if (DEBUG && null != source)
System.out.println("Starting " + (unique ? "UNIQUE" : "shared") + " source: " + source.getSystemId());
XMLStringFactory xstringFactory = m_xsf;
int dtmPos = getFirstFreeDTMID();
int documentID = dtmPos << IDENT_DTM_NODE_BITS;
if ((null != source) && source instanceof DOMSource) {
DOM2DTM dtm = new DOM2DTM(this, (DOMSource) source, documentID, whiteSpaceFilter, xstringFactory, doIndexing);
addDTM(dtm, dtmPos, 0);
return dtm;
} else {
boolean isSAXSource = (null != source) ? (source instanceof SAXSource) : true;
boolean isStreamSource = (null != source) ? (source instanceof StreamSource) : false;
if (isSAXSource || isStreamSource) {
XMLReader reader = null;
SAX2DTM dtm;
try {
InputSource xmlSource;
if (null == source) {
xmlSource = null;
} else {
reader = getXMLReader(source);
xmlSource = SAXSource.sourceToInputSource(source);
String urlOfSource = xmlSource.getSystemId();
if (null != urlOfSource) {
try {
urlOfSource = SystemIDResolver.getAbsoluteURI(urlOfSource);
} catch (Exception e) {
// %REVIEW% Is there a better way to send a warning?
System.err.println("Can not absolutize URL: " + urlOfSource);
}
xmlSource.setSystemId(urlOfSource);
}
}
if (source == null && unique && !incremental && !doIndexing) {
// Special case to support RTF construction into shared DTM.
// It should actually still work for other uses,
// but may be slightly deoptimized relative to the base
// to allow it to deal with carrying multiple documents.
//
// %REVIEW% This is a sloppy way to request this mode;
// we need to consider architectural improvements.
dtm = new SAX2RTFDTM(this, source, documentID, whiteSpaceFilter, xstringFactory, doIndexing);
} else /**************************************************************
// EXPERIMENTAL 3/22/02
else if(JKESS_XNI_EXPERIMENT && m_incremental) {
dtm = new XNI2DTM(this, source, documentID, whiteSpaceFilter,
xstringFactory, doIndexing);
}
**************************************************************/
// Create the basic SAX2DTM.
{
dtm = new SAX2DTM(this, source, documentID, whiteSpaceFilter, xstringFactory, doIndexing);
}
// Go ahead and add the DTM to the lookup table. This needs to be
// done before any parsing occurs. Note offset 0, since we've just
// created a new DTM.
addDTM(dtm, dtmPos, 0);
boolean haveXercesParser = (null != reader) && (reader.getClass().getName().equals("org.apache.xerces.parsers.SAXParser"));
if (haveXercesParser) {
// No matter what. %REVIEW%
incremental = true;
}
// build, then we still want to set up the IncrementalSAXSource stuff.
if (m_incremental && incremental) /* || ((null == reader) && incremental) */
{
IncrementalSAXSource coParser = null;
if (haveXercesParser) {
// IncrementalSAXSource_Xerces to avoid threading.
try {
coParser = (IncrementalSAXSource) Class.forName("org.apache.xml.dtm.ref.IncrementalSAXSource_Xerces").newInstance();
} catch (Exception ex) {
ex.printStackTrace();
coParser = null;
}
}
if (coParser == null) {
// Create a IncrementalSAXSource to run on the secondary thread.
if (null == reader) {
coParser = new IncrementalSAXSource_Filter();
} else {
IncrementalSAXSource_Filter filter = new IncrementalSAXSource_Filter();
filter.setXMLReader(reader);
coParser = filter;
}
}
/**************************************************************
// EXPERIMENTAL 3/22/02
if (JKESS_XNI_EXPERIMENT && m_incremental &&
dtm instanceof XNI2DTM &&
coParser instanceof IncrementalSAXSource_Xerces) {
org.apache.xerces.xni.parser.XMLPullParserConfiguration xpc=
((IncrementalSAXSource_Xerces)coParser)
.getXNIParserConfiguration();
if (xpc!=null) {
// Bypass SAX; listen to the XNI stream
((XNI2DTM)dtm).setIncrementalXNISource(xpc);
} else {
// Listen to the SAX stream (will fail, diagnostically...)
dtm.setIncrementalSAXSource(coParser);
}
} else
***************************************************************/
// Have the DTM set itself up as IncrementalSAXSource's listener.
dtm.setIncrementalSAXSource(coParser);
if (null == xmlSource) {
// Then the user will construct it themselves.
return dtm;
}
if (null == reader.getErrorHandler()) {
reader.setErrorHandler(dtm);
}
reader.setDTDHandler(dtm);
try {
// Launch parsing coroutine. Launches a second thread,
// if we're using IncrementalSAXSource.filter().
coParser.startParse(xmlSource);
} catch (RuntimeException re) {
dtm.clearCoRoutine();
throw re;
} catch (Exception e) {
dtm.clearCoRoutine();
throw new org.apache.xml.utils.WrappedRuntimeException(e);
}
} else {
if (null == reader) {
// Then the user will construct it themselves.
return dtm;
}
// not incremental
reader.setContentHandler(dtm);
reader.setDTDHandler(dtm);
if (null == reader.getErrorHandler()) {
reader.setErrorHandler(dtm);
}
try {
reader.setProperty("http://xml.org/sax/properties/lexical-handler", dtm);
} catch (SAXNotRecognizedException e) {
} catch (SAXNotSupportedException e) {
}
try {
reader.parse(xmlSource);
} catch (RuntimeException re) {
dtm.clearCoRoutine();
throw re;
} catch (Exception e) {
dtm.clearCoRoutine();
throw new org.apache.xml.utils.WrappedRuntimeException(e);
}
}
if (DUMPTREE) {
System.out.println("Dumping SAX2DOM");
dtm.dumpDTM(System.err);
}
return dtm;
} finally {
// after creating the DTM.
if (reader != null && !(m_incremental && incremental)) {
reader.setContentHandler(m_defaultHandler);
reader.setDTDHandler(m_defaultHandler);
reader.setErrorHandler(m_defaultHandler);
// Reset the LexicalHandler to null after creating the DTM.
try {
reader.setProperty("http://xml.org/sax/properties/lexical-handler", null);
} catch (Exception e) {
}
}
releaseXMLReader(reader);
}
} else {
//"Not supported: " + source);
throw new DTMException(XMLMessages.createXMLMessage(XMLErrorResources.ER_NOT_SUPPORTED, new Object[] { source }));
}
}
}
use of javax.xml.transform.stream.StreamSource in project j2objc by google.
the class TransformerIdentityImpl method transform.
/**
* Process the source tree to the output result.
* @param source The input for the source tree.
*
* @param outputTarget The output target.
*
* @throws TransformerException If an unrecoverable error occurs
* during the course of the transformation.
*/
public void transform(Source source, Result outputTarget) throws TransformerException {
createResultContentHandler(outputTarget);
/*
* According to JAXP1.2, new SAXSource()/StreamSource()
* should create an empty input tree, with a default root node.
* new DOMSource()creates an empty document using DocumentBuilder.
* newDocument(); Use DocumentBuilder.newDocument() for all 3 situations,
* since there is no clear spec. how to create an empty tree when
* both SAXSource() and StreamSource() are used.
*/
if ((source instanceof StreamSource && source.getSystemId() == null && ((StreamSource) source).getInputStream() == null && ((StreamSource) source).getReader() == null) || (source instanceof SAXSource && ((SAXSource) source).getInputSource() == null && ((SAXSource) source).getXMLReader() == null) || (source instanceof DOMSource && ((DOMSource) source).getNode() == null)) {
try {
DocumentBuilderFactory builderF = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderF.newDocumentBuilder();
String systemID = source.getSystemId();
source = new DOMSource(builder.newDocument());
// Copy system ID from original, empty Source to new Source
if (systemID != null) {
source.setSystemId(systemID);
}
} catch (ParserConfigurationException e) {
throw new TransformerException(e.getMessage());
}
}
try {
if (source instanceof DOMSource) {
DOMSource dsource = (DOMSource) source;
m_systemID = dsource.getSystemId();
Node dNode = dsource.getNode();
if (null != dNode) {
try {
if (dNode.getNodeType() == Node.ATTRIBUTE_NODE)
this.startDocument();
try {
if (dNode.getNodeType() == Node.ATTRIBUTE_NODE) {
String data = dNode.getNodeValue();
char[] chars = data.toCharArray();
characters(chars, 0, chars.length);
} else {
org.apache.xml.serializer.TreeWalker walker;
walker = new org.apache.xml.serializer.TreeWalker(this, m_systemID);
walker.traverse(dNode);
}
} finally {
if (dNode.getNodeType() == Node.ATTRIBUTE_NODE)
this.endDocument();
}
} catch (SAXException se) {
throw new TransformerException(se);
}
return;
} else {
String messageStr = XSLMessages.createMessage(XSLTErrorResources.ER_ILLEGAL_DOMSOURCE_INPUT, null);
throw new IllegalArgumentException(messageStr);
}
}
InputSource xmlSource = SAXSource.sourceToInputSource(source);
if (null == xmlSource) {
//"Can't transform a Source of type "
throw new TransformerException(XSLMessages.createMessage(XSLTErrorResources.ER_CANNOT_TRANSFORM_SOURCE_TYPE, new Object[] { source.getClass().getName() }));
//+ source.getClass().getName() + "!");
}
if (null != xmlSource.getSystemId())
m_systemID = xmlSource.getSystemId();
XMLReader reader = null;
boolean managedReader = false;
try {
if (source instanceof SAXSource) {
reader = ((SAXSource) source).getXMLReader();
}
if (null == reader) {
try {
reader = XMLReaderManager.getInstance().getXMLReader();
managedReader = true;
} catch (SAXException se) {
throw new TransformerException(se);
}
} else {
try {
reader.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
} catch (org.xml.sax.SAXException se) {
// We don't care.
}
}
// Get the input content handler, which will handle the
// parse events and create the source tree.
ContentHandler inputHandler = this;
reader.setContentHandler(inputHandler);
if (inputHandler instanceof org.xml.sax.DTDHandler)
reader.setDTDHandler((org.xml.sax.DTDHandler) inputHandler);
try {
if (inputHandler instanceof org.xml.sax.ext.LexicalHandler)
reader.setProperty("http://xml.org/sax/properties/lexical-handler", inputHandler);
if (inputHandler instanceof org.xml.sax.ext.DeclHandler)
reader.setProperty("http://xml.org/sax/properties/declaration-handler", inputHandler);
} catch (org.xml.sax.SAXException se) {
}
try {
if (inputHandler instanceof org.xml.sax.ext.LexicalHandler)
reader.setProperty("http://xml.org/sax/handlers/LexicalHandler", inputHandler);
if (inputHandler instanceof org.xml.sax.ext.DeclHandler)
reader.setProperty("http://xml.org/sax/handlers/DeclHandler", inputHandler);
} catch (org.xml.sax.SAXNotRecognizedException snre) {
}
reader.parse(xmlSource);
} catch (org.apache.xml.utils.WrappedRuntimeException wre) {
Throwable throwable = wre.getException();
while (throwable instanceof org.apache.xml.utils.WrappedRuntimeException) {
throwable = ((org.apache.xml.utils.WrappedRuntimeException) throwable).getException();
}
throw new TransformerException(wre.getException());
} catch (org.xml.sax.SAXException se) {
throw new TransformerException(se);
} catch (IOException ioe) {
throw new TransformerException(ioe);
} finally {
if (managedReader) {
XMLReaderManager.getInstance().releaseXMLReader(reader);
}
}
} finally {
if (null != m_outputStream) {
try {
m_outputStream.close();
} catch (IOException ioe) {
}
m_outputStream = null;
}
}
}
Aggregations