use of javax.xml.transform.sax.SAXSource 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.sax.SAXSource 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;
}
}
}
use of javax.xml.transform.sax.SAXSource in project jdk8u_jdk by JetBrains.
the class XSLTExFuncTest method testTemplatesEnableExtFunc.
/**
* use Templates template = factory.newTemplates(new StreamSource( new
* FileInputStream(xslFilename))); // Use the template to create a
* transformer Transformer xformer = template.newTransformer();
*
* @param factory
* @return
*/
/**
* Security is enabled, use new feature: enableExtensionFunctions Use the
* template to create a transformer
*/
public void testTemplatesEnableExtFunc() {
Policy p = new SimplePolicy(new AllPermission());
Policy.setPolicy(p);
System.setSecurityManager(new SecurityManager());
TransformerFactory factory = TransformerFactory.newInstance();
/**
* Use of the extension function 'http://exslt.org/strings:tokenize' is
* not allowed when the secure processing feature is set to true.
* Attempt to use the new property to enable extension function
*/
boolean isExtensionSupported = enableExtensionFunction(factory);
try {
SAXSource xslSource = new SAXSource(new InputSource(xslFile));
xslSource.setSystemId(xslFileId);
Templates template = factory.newTemplates(xslSource);
Transformer transformer = template.newTransformer();
StringWriter stringResult = new StringWriter();
Result result = new StreamResult(stringResult);
transformer.transform(new SAXSource(new InputSource(xmlFile)), result);
System.out.println("testTemplatesEnableExtFunc: OK");
} catch (TransformerConfigurationException e) {
fail(e.getMessage());
} catch (TransformerException e) {
fail(e.getMessage());
} finally {
System.setSecurityManager(null);
}
}
use of javax.xml.transform.sax.SAXSource in project opennms by OpenNMS.
the class RrdtoolXportFetchStrategy method fetchMeasurements.
/**
* {@inheritDoc}
*/
@Override
protected FetchResults fetchMeasurements(long start, long end, long step, int maxrows, Map<Source, String> rrdsBySource, Map<String, Object> constants) throws RrdException {
String rrdBinary = System.getProperty("rrd.binary");
if (rrdBinary == null) {
throw new RrdException("No RRD binary is set.");
}
final long startInSeconds = (long) Math.floor(start / 1000);
final long endInSeconds = (long) Math.floor(end / 1000);
long stepInSeconds = (long) Math.floor(step / 1000);
// The step must be strictly positive
if (stepInSeconds <= 0) {
stepInSeconds = 1;
}
final CommandLine cmdLine = new CommandLine(rrdBinary);
cmdLine.addArgument("xport");
cmdLine.addArgument("--step");
cmdLine.addArgument("" + stepInSeconds);
cmdLine.addArgument("--start");
cmdLine.addArgument("" + startInSeconds);
cmdLine.addArgument("--end");
cmdLine.addArgument("" + endInSeconds);
if (maxrows > 0) {
cmdLine.addArgument("--maxrows");
cmdLine.addArgument("" + maxrows);
}
// Use labels without spaces when executing the xport command
// These are mapped back to the requested labels in the response
final Map<String, String> labelMap = Maps.newHashMap();
int k = 0;
for (final Map.Entry<Source, String> entry : rrdsBySource.entrySet()) {
final Source source = entry.getKey();
final String rrdFile = entry.getValue();
final String tempLabel = Integer.toString(++k);
labelMap.put(tempLabel, source.getLabel());
cmdLine.addArgument(String.format("DEF:%s=%s:%s:%s", tempLabel, Utils.escapeColons(rrdFile), Utils.escapeColons(source.getEffectiveDataSource()), source.getAggregation()));
cmdLine.addArgument(String.format("XPORT:%s:%s", tempLabel, tempLabel));
}
// Use commons-exec to execute rrdtool
final DefaultExecutor executor = new DefaultExecutor();
// Capture stdout/stderr
final ByteArrayOutputStream stdout = new ByteArrayOutputStream();
final ByteArrayOutputStream stderr = new ByteArrayOutputStream();
executor.setStreamHandler(new PumpStreamHandler(stdout, stderr, null));
// Fail if we get a non-zero exit code
executor.setExitValue(0);
// Fail if the process takes too long
final ExecuteWatchdog watchdog = new ExecuteWatchdog(XPORT_TIMEOUT_MS);
executor.setWatchdog(watchdog);
// Export
RrdXport rrdXport;
try {
LOG.debug("Executing: {}", cmdLine);
executor.execute(cmdLine);
final XMLReader xmlReader = XMLReaderFactory.createXMLReader();
xmlReader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
final SAXSource source = new SAXSource(xmlReader, new InputSource(new StringReader(stdout.toString())));
final JAXBContext jc = JAXBContext.newInstance(RrdXport.class);
final Unmarshaller u = jc.createUnmarshaller();
rrdXport = (RrdXport) u.unmarshal(source);
} catch (IOException e) {
throw new RrdException("An error occured while executing '" + StringUtils.join(cmdLine.toStrings(), " ") + "' with stderr: " + stderr.toString(), e);
} catch (SAXException | JAXBException e) {
throw new RrdException("The output generated by 'rrdtool xport' could not be parsed.", e);
}
final int numRows = rrdXport.getRows().size();
final int numColumns = rrdXport.getMeta().getLegends().size();
final long xportStartInMs = rrdXport.getMeta().getStart() * 1000;
final long xportStepInMs = rrdXport.getMeta().getStep() * 1000;
final long[] timestamps = new long[numRows];
final double[][] values = new double[numColumns][numRows];
// Convert rows to columns
int i = 0;
for (final XRow row : rrdXport.getRows()) {
// Derive the timestamp from the start and step since newer versions
// of rrdtool no longer include it as part of the rows
timestamps[i] = xportStartInMs + xportStepInMs * i;
for (int j = 0; j < numColumns; j++) {
if (row.getValues() == null) {
// NMS-7710: Avoid NPEs, in certain cases the list of values may be null
throw new RrdException("The output generated by 'rrdtool xport' was not recognized. Try upgrading your rrdtool binaries.");
}
values[j][i] = row.getValues().get(j);
}
i++;
}
// Map the columns by label
// The legend entries are in the same order as the column values
final Map<String, double[]> columns = Maps.newHashMapWithExpectedSize(numColumns);
i = 0;
for (String label : rrdXport.getMeta().getLegends()) {
columns.put(labelMap.get(label), values[i++]);
}
return new FetchResults(timestamps, columns, xportStepInMs, constants);
}
use of javax.xml.transform.sax.SAXSource in project voltdb by VoltDB.
the class JDBCSQLXML method getSource.
/**
* Returns a Source for reading the XML value designated by this SQLXML instance.
* Sources are used as inputs to XML parsers and XSLT transformers.
* <p>
* Sources for XML parsers will have namespace processing on by default.
* The systemID of the Source is implementation dependent.
* <p>
* The SQL XML object becomes not readable when this method is called and
* may also become not writable depending on implementation.
* <p>
* Note that SAX is a callback architecture, so a returned
* SAXSource should then be set with a content handler that will
* receive the SAX events from parsing. The content handler
* will receive callbacks based on the contents of the XML.
* <pre>
* SAXSource saxSource = sqlxml.getSource(SAXSource.class);
* XMLReader xmlReader = saxSource.getXMLReader();
* xmlReader.setContentHandler(myHandler);
* xmlReader.parse(saxSource.getInputSource());
* </pre>
*
* @param sourceClass The class of the source, or null.
* If the class is null, a vendor specifc Source implementation will be returned.
* The following classes are supported at a minimum:
* <pre>
* javax.xml.transform.dom.DOMSource - returns a DOMSource
* javax.xml.transform.sax.SAXSource - returns a SAXSource
* javax.xml.transform.stax.StAXSource - returns a StAXSource
* javax.xml.transform.stream.StreamSource - returns a StreamSource
* </pre>
* @return a Source for reading the XML value.
* @throws SQLException if there is an error processing the XML value
* or if this feature is not supported.
* The getCause() method of the exception may provide a more detailed exception, for example,
* if an XML parser exception occurs.
* An exception is thrown if the state is not readable.
* @exception SQLFeatureNotSupportedException if the JDBC driver does not support
* this method
* @since JDK 1.6 Build 79
*/
@SuppressWarnings("unchecked")
public synchronized <T extends Source> T getSource(Class<T> sourceClass) throws SQLException {
checkClosed();
checkReadable();
final Source source = getSourceImpl(sourceClass);
setReadable(false);
setWritable(false);
return (T) source;
}
Aggregations