use of javax.xml.transform.sax.SAXSource in project camel by apache.
the class XsltBuilderTest method testXsltSource.
public void testXsltSource() throws Exception {
File file = new File("src/test/resources/org/apache/camel/builder/xml/example.xsl");
Source styleSheet = new SAXSource(new InputSource(new FileInputStream(file)));
XsltBuilder builder = XsltBuilder.xslt(styleSheet);
Exchange exchange = new DefaultExchange(context);
exchange.getIn().setBody("<hello>world!</hello>");
builder.process(exchange);
assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?><goodbye>world!</goodbye>", exchange.getOut().getBody());
}
use of javax.xml.transform.sax.SAXSource in project camel by apache.
the class XsltBuilder method getSource.
/**
* Converts the inbound body to a {@link Source}, if the body is <b>not</b> already a {@link Source}.
* <p/>
* This implementation will prefer to source in the following order:
* <ul>
* <li>StAX - If StAX is allowed</li>
* <li>SAX - SAX as 2nd choice</li>
* <li>Stream - Stream as 3rd choice</li>
* <li>DOM - DOM as 4th choice</li>
* </ul>
*/
protected Source getSource(Exchange exchange, Object body) {
// body may already be a source
if (body instanceof Source) {
return (Source) body;
}
Source source = null;
if (body != null) {
if (isAllowStAX()) {
// try StAX if enabled
source = exchange.getContext().getTypeConverter().tryConvertTo(StAXSource.class, exchange, body);
}
if (source == null) {
// then try SAX
source = exchange.getContext().getTypeConverter().tryConvertTo(SAXSource.class, exchange, body);
tryAddEntityResolver((SAXSource) source);
}
if (source == null) {
// then try stream
source = exchange.getContext().getTypeConverter().tryConvertTo(StreamSource.class, exchange, body);
}
if (source == null) {
// and fallback to DOM
source = exchange.getContext().getTypeConverter().tryConvertTo(DOMSource.class, exchange, body);
}
// now we just put the call of source converter at last
if (source == null) {
TypeConverter tc = exchange.getContext().getTypeConverterRegistry().lookup(Source.class, body.getClass());
if (tc != null) {
source = tc.convertTo(Source.class, exchange, body);
}
}
}
if (source == null) {
if (isFailOnNullBody()) {
throw new ExpectedBodyTypeException(exchange, Source.class);
} else {
try {
source = converter.toDOMSource(converter.createDocument());
} catch (ParserConfigurationException e) {
throw new RuntimeTransformException(e);
}
}
}
return source;
}
use of javax.xml.transform.sax.SAXSource in project camel by apache.
the class XsltBuilder method process.
public void process(Exchange exchange) throws Exception {
notNull(getTemplate(), "template");
if (isDeleteOutputFile()) {
// add on completion so we can delete the file when the Exchange is done
String fileName = ExchangeHelper.getMandatoryHeader(exchange, Exchange.XSLT_FILE_NAME, String.class);
exchange.addOnCompletion(new XsltBuilderOnCompletion(fileName));
}
Transformer transformer = getTransformer();
configureTransformer(transformer, exchange);
ResultHandler resultHandler = resultHandlerFactory.createResult(exchange);
Result result = resultHandler.getResult();
// let's copy the headers before we invoke the transform in case they modify them
Message out = exchange.getOut();
out.copyFrom(exchange.getIn());
// the underlying input stream, which we need to close to avoid locking files or other resources
InputStream is = null;
try {
Source source;
// only convert to input stream if really needed
if (isInputStreamNeeded(exchange)) {
is = exchange.getIn().getBody(InputStream.class);
source = getSource(exchange, is);
} else {
Object body = exchange.getIn().getBody();
source = getSource(exchange, body);
}
if (source instanceof StAXSource) {
// Always convert StAXSource to SAXSource.
// * Xalan and Saxon-B don't support StAXSource.
// * The JDK default implementation (XSLTC) doesn't handle CDATA events
// (see com.sun.org.apache.xalan.internal.xsltc.trax.StAXStream2SAX).
// * Saxon-HE/PE/EE seem to support StAXSource, but don't advertise this
// officially (via TransformerFactory.getFeature(StAXSource.FEATURE))
source = new StAX2SAXSource(((StAXSource) source).getXMLStreamReader());
}
LOG.trace("Using {} as source", source);
transformer.transform(source, result);
LOG.trace("Transform complete with result {}", result);
resultHandler.setBody(out);
} finally {
releaseTransformer(transformer);
// IOHelper can handle if is is null
IOHelper.close(is);
}
}
use of javax.xml.transform.sax.SAXSource in project robovm by robovm.
the class StylesheetPIHandler method processingInstruction.
/**
* Handle the xml-stylesheet processing instruction.
*
* @param target The processing instruction target.
* @param data The processing instruction data, or null if
* none is supplied.
* @throws org.xml.sax.SAXException Any SAX exception, possibly
* wrapping another exception.
* @see org.xml.sax.ContentHandler#processingInstruction
* @see <a href="http://www.w3.org/TR/xml-stylesheet/">Associating Style Sheets with XML documents, Version 1.0</a>
*/
public void processingInstruction(String target, String data) throws org.xml.sax.SAXException {
if (target.equals("xml-stylesheet")) {
// CDATA #REQUIRED
String href = null;
// CDATA #REQUIRED
String type = null;
// CDATA #IMPLIED
String title = null;
// CDATA #IMPLIED
String media = null;
// CDATA #IMPLIED
String charset = null;
// (yes|no) "no"
boolean alternate = false;
StringTokenizer tokenizer = new StringTokenizer(data, " \t=\n", true);
boolean lookedAhead = false;
Source source = null;
String token = "";
while (tokenizer.hasMoreTokens()) {
if (!lookedAhead)
token = tokenizer.nextToken();
else
lookedAhead = false;
if (tokenizer.hasMoreTokens() && (token.equals(" ") || token.equals("\t") || token.equals("=")))
continue;
String name = token;
if (name.equals("type")) {
token = tokenizer.nextToken();
while (tokenizer.hasMoreTokens() && (token.equals(" ") || token.equals("\t") || token.equals("="))) token = tokenizer.nextToken();
type = token.substring(1, token.length() - 1);
} else if (name.equals("href")) {
token = tokenizer.nextToken();
while (tokenizer.hasMoreTokens() && (token.equals(" ") || token.equals("\t") || token.equals("="))) token = tokenizer.nextToken();
href = token;
if (tokenizer.hasMoreTokens()) {
token = tokenizer.nextToken();
// already have the next token.
while (token.equals("=") && tokenizer.hasMoreTokens()) {
href = href + token + tokenizer.nextToken();
if (tokenizer.hasMoreTokens()) {
token = tokenizer.nextToken();
lookedAhead = true;
} else {
break;
}
}
}
href = href.substring(1, href.length() - 1);
try {
// Add code to use a URIResolver. Patch from Dmitri Ilyin.
if (m_uriResolver != null) {
source = m_uriResolver.resolve(href, m_baseID);
} else {
href = SystemIDResolver.getAbsoluteURI(href, m_baseID);
source = new SAXSource(new InputSource(href));
}
} catch (TransformerException te) {
throw new org.xml.sax.SAXException(te);
}
} else if (name.equals("title")) {
token = tokenizer.nextToken();
while (tokenizer.hasMoreTokens() && (token.equals(" ") || token.equals("\t") || token.equals("="))) token = tokenizer.nextToken();
title = token.substring(1, token.length() - 1);
} else if (name.equals("media")) {
token = tokenizer.nextToken();
while (tokenizer.hasMoreTokens() && (token.equals(" ") || token.equals("\t") || token.equals("="))) token = tokenizer.nextToken();
media = token.substring(1, token.length() - 1);
} else if (name.equals("charset")) {
token = tokenizer.nextToken();
while (tokenizer.hasMoreTokens() && (token.equals(" ") || token.equals("\t") || token.equals("="))) token = tokenizer.nextToken();
charset = token.substring(1, token.length() - 1);
} else if (name.equals("alternate")) {
token = tokenizer.nextToken();
while (tokenizer.hasMoreTokens() && (token.equals(" ") || token.equals("\t") || token.equals("="))) token = tokenizer.nextToken();
alternate = token.substring(1, token.length() - 1).equals("yes");
}
}
if ((null != type) && (type.equals("text/xsl") || type.equals("text/xml") || type.equals("application/xml+xslt")) && (null != href)) {
if (null != m_media) {
if (null != media) {
if (!media.equals(m_media))
return;
} else
return;
}
if (null != m_charset) {
if (null != charset) {
if (!charset.equals(m_charset))
return;
} else
return;
}
if (null != m_title) {
if (null != title) {
if (!title.equals(m_title))
return;
} else
return;
}
m_stylesheets.addElement(source);
}
}
}
use of javax.xml.transform.sax.SAXSource in project robovm by robovm.
the class TransformerImpl method transform.
/**
* Process the source tree to SAX parse events.
* @param source The input for the source tree.
* @param shouldRelease Flag indicating whether to release DTMManager.
*
* @throws TransformerException
*/
public void transform(Source source, boolean shouldRelease) throws TransformerException {
try {
// here or in reset(). -is
if (getXPathContext().getNamespaceContext() == null) {
getXPathContext().setNamespaceContext(getStylesheet());
}
String base = source.getSystemId();
// If no systemID of the source, use the base of the stylesheet.
if (null == base) {
base = m_stylesheetRoot.getBaseIdentifier();
}
// As a last resort, use the current user dir.
if (null == base) {
String currentDir = "";
try {
currentDir = System.getProperty("user.dir");
}// user.dir not accessible from applet
catch (SecurityException se) {
}
if (currentDir.startsWith(java.io.File.separator))
base = "file://" + currentDir;
else
base = "file:///" + currentDir;
base = base + java.io.File.separatorChar + source.getClass().getName();
}
setBaseURLOfSource(base);
DTMManager mgr = m_xcontext.getDTMManager();
/*
* 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) {
fatalError(e);
}
}
DTM dtm = mgr.getDTM(source, false, this, true, true);
dtm.setDocumentBaseURI(base);
// %REVIEW% I have to think about this. -sb
boolean hardDelete = true;
try {
// NOTE: This will work because this is _NOT_ a shared DTM, and thus has
// only a single Document node. If it could ever be an RTF or other
// shared DTM, look at dtm.getDocumentRoot(nodeHandle).
this.transformNode(dtm.getDocument());
} finally {
if (shouldRelease)
mgr.release(dtm, hardDelete);
}
// Kick off the parse. When the ContentHandler gets
// the startDocument event, it will call transformNode( node ).
// reader.parse( xmlSource );
// This has to be done to catch exceptions thrown from
// the transform thread spawned by the STree handler.
Exception e = getExceptionThrown();
if (null != e) {
if (e instanceof javax.xml.transform.TransformerException) {
throw (javax.xml.transform.TransformerException) e;
} else if (e instanceof org.apache.xml.utils.WrappedRuntimeException) {
fatalError(((org.apache.xml.utils.WrappedRuntimeException) e).getException());
} else {
throw new javax.xml.transform.TransformerException(e);
}
} else if (null != m_serializationHandler) {
m_serializationHandler.endDocument();
}
} 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();
}
fatalError(throwable);
}// Patch attributed to David Eisenberg <david@catcode.com>
catch (org.xml.sax.SAXParseException spe) {
fatalError(spe);
} catch (org.xml.sax.SAXException se) {
m_errorHandler.fatalError(new TransformerException(se));
} finally {
m_hasTransformThreadErrorCatcher = false;
// This looks to be redundent to the one done in TransformNode.
reset();
}
}
Aggregations