use of javax.xml.transform.stream.StreamSource in project KeepScore by nolanlawson.
the class XmlHelper method prettyPrint.
public static String prettyPrint(String unformattedXml) {
try {
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
// initialize StreamResult with File object to save to file
StreamResult result = new StreamResult(new StringWriter());
StreamSource source = new StreamSource(new StringReader(unformattedXml));
transformer.transform(source, result);
return result.getWriter().toString();
} catch (Throwable t) {
// should never happen
throw new RuntimeException(t);
}
}
use of javax.xml.transform.stream.StreamSource in project logger by orhanobut.
the class LoggerPrinter method xml.
/**
* Formats the json content and print it
*
* @param xml the xml content
*/
@Override
public void xml(String xml) {
if (Helper.isEmpty(xml)) {
d("Empty/Null xml content");
return;
}
try {
Source xmlInput = new StreamSource(new StringReader(xml));
StreamResult xmlOutput = new StreamResult(new StringWriter());
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
transformer.transform(xmlInput, xmlOutput);
d(xmlOutput.getWriter().toString().replaceFirst(">", ">\n"));
} catch (TransformerException e) {
e("Invalid xml");
}
}
use of javax.xml.transform.stream.StreamSource in project robovm by robovm.
the class ProcessorInclude method parse.
/**
* Set off a new parse for an included or imported stylesheet. This will
* set the {@link StylesheetHandler} to a new state, and recurse in with
* a new set of parse events. Once this function returns, the state of
* the StylesheetHandler should be restored.
*
* @param handler non-null reference to current StylesheetHandler that is constructing the Templates.
* @param uri The Namespace URI, which should be the XSLT namespace.
* @param localName The local name (without prefix), which should be "include" or "import".
* @param rawName The qualified name (with prefix).
* @param attributes The list of attributes on the xsl:include or xsl:import element.
*
* @throws org.xml.sax.SAXException Any SAX exception, possibly
* wrapping another exception.
*/
protected void parse(StylesheetHandler handler, String uri, String localName, String rawName, Attributes attributes) throws org.xml.sax.SAXException {
TransformerFactoryImpl processor = handler.getStylesheetProcessor();
URIResolver uriresolver = processor.getURIResolver();
try {
Source source = null;
if (null != uriresolver) {
// There is a user provided URI resolver.
// At the startElement() call we would
// have tried to obtain a Source from it
// which we now retrieve
source = handler.peekSourceFromURIResolver();
if (null != source && source instanceof DOMSource) {
Node node = ((DOMSource) source).getNode();
// There is a user provided URI resolver.
// At the startElement() call we would
// have already pushed the system ID, obtained
// from either the source.getSystemId(), if non-null
// or from SystemIDResolver.getAbsoluteURI() as a backup
// which we now retrieve.
String systemId = handler.peekImportURL();
// stylesheet module onto the stack.
if (systemId != null)
handler.pushBaseIndentifier(systemId);
TreeWalker walker = new TreeWalker(handler, new org.apache.xml.utils.DOM2Helper(), systemId);
try {
walker.traverse(node);
} catch (org.xml.sax.SAXException se) {
throw new TransformerException(se);
}
if (systemId != null)
handler.popBaseIndentifier();
return;
}
}
if (null == source) {
String absURL = SystemIDResolver.getAbsoluteURI(getHref(), handler.getBaseIdentifier());
source = new StreamSource(absURL);
}
// possible callback to a class that over-rides this method.
source = processSource(handler, source);
XMLReader reader = null;
if (source instanceof SAXSource) {
SAXSource saxSource = (SAXSource) source;
// may be null
reader = saxSource.getXMLReader();
}
InputSource inputSource = SAXSource.sourceToInputSource(source);
if (null == reader) {
// Use JAXP1.1 ( if possible )
try {
javax.xml.parsers.SAXParserFactory factory = javax.xml.parsers.SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
if (handler.getStylesheetProcessor().isSecureProcessing()) {
try {
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
} catch (org.xml.sax.SAXException se) {
}
}
javax.xml.parsers.SAXParser jaxpParser = factory.newSAXParser();
reader = jaxpParser.getXMLReader();
} catch (javax.xml.parsers.ParserConfigurationException ex) {
throw new org.xml.sax.SAXException(ex);
} catch (javax.xml.parsers.FactoryConfigurationError ex1) {
throw new org.xml.sax.SAXException(ex1.toString());
} catch (NoSuchMethodError ex2) {
} catch (AbstractMethodError ame) {
}
}
if (null == reader)
reader = XMLReaderFactory.createXMLReader();
if (null != reader) {
reader.setContentHandler(handler);
// Push the absolute URI of the included/imported
// stylesheet module onto the stack.
handler.pushBaseIndentifier(inputSource.getSystemId());
try {
reader.parse(inputSource);
} finally {
handler.popBaseIndentifier();
}
}
} catch (IOException ioe) {
handler.error(XSLTErrorResources.ER_IOEXCEPTION, new Object[] { getHref() }, ioe);
} catch (TransformerException te) {
handler.error(te.getMessage(), te);
}
}
use of javax.xml.transform.stream.StreamSource in project robovm by robovm.
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;
}
}
}
use of javax.xml.transform.stream.StreamSource in project robovm by robovm.
the class SourceTreeManager method resolveURI.
/**
* This will be called by the processor when it encounters
* an xsl:include, xsl:import, or document() function.
*
* @param base The base URI that should be used.
* @param urlString Value from an xsl:import or xsl:include's href attribute,
* or a URI specified in the document() function.
*
* @return a Source that can be used to process the resource.
*
* @throws IOException
* @throws TransformerException
*/
public Source resolveURI(String base, String urlString, SourceLocator locator) throws TransformerException, IOException {
Source source = null;
if (null != m_uriResolver) {
source = m_uriResolver.resolve(urlString, base);
}
if (null == source) {
String uri = SystemIDResolver.getAbsoluteURI(urlString, base);
source = new StreamSource(uri);
}
return source;
}
Aggregations