use of javax.xml.parsers.SAXParserFactory in project camel by apache.
the class XmlLineNumberParser method parseXml.
/**
* Parses the XML.
*
* @param is the XML content as an input stream
* @param rootNames one or more root names that is used as baseline for beginning the parsing, for example camelContext to start parsing
* when Camel is discovered. Multiple names can be defined separated by comma
* @param forceNamespace an optional namespace to force assign to each node. This may be needed for JAXB unmarshalling from XML -> POJO.
* @return the DOM model
* @throws Exception is thrown if error parsing
*/
public static Document parseXml(final InputStream is, final String rootNames, final String forceNamespace) throws Exception {
final Document doc;
SAXParser parser;
final SAXParserFactory factory = SAXParserFactory.newInstance();
parser = factory.newSAXParser();
final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
// turn off validator and loading external dtd
dbf.setValidating(false);
dbf.setNamespaceAware(true);
dbf.setFeature("http://xml.org/sax/features/namespaces", false);
dbf.setFeature("http://xml.org/sax/features/validation", false);
dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
dbf.setFeature("http://xml.org/sax/features/external-general-entities", false);
final DocumentBuilder docBuilder = dbf.newDocumentBuilder();
doc = docBuilder.newDocument();
final Stack<Element> elementStack = new Stack<Element>();
final StringBuilder textBuffer = new StringBuilder();
final DefaultHandler handler = new DefaultHandler() {
private Locator locator;
private boolean found;
@Override
public void setDocumentLocator(final Locator locator) {
// Save the locator, so that it can be used later for line tracking when traversing nodes.
this.locator = locator;
this.found = rootNames == null;
}
private boolean isRootName(String qName) {
for (String root : rootNames.split(",")) {
if (qName.equals(root)) {
return true;
}
}
return false;
}
@Override
public void startElement(final String uri, final String localName, final String qName, final Attributes attributes) throws SAXException {
addTextIfNeeded();
if (rootNames != null && !found) {
if (isRootName(qName)) {
found = true;
}
}
if (found) {
Element el;
if (forceNamespace != null) {
el = doc.createElementNS(forceNamespace, qName);
} else {
el = doc.createElement(qName);
}
for (int i = 0; i < attributes.getLength(); i++) {
el.setAttribute(attributes.getQName(i), attributes.getValue(i));
}
el.setUserData(LINE_NUMBER, String.valueOf(this.locator.getLineNumber()), null);
el.setUserData(COLUMN_NUMBER, String.valueOf(this.locator.getColumnNumber()), null);
elementStack.push(el);
}
}
@Override
public void endElement(final String uri, final String localName, final String qName) {
if (!found) {
return;
}
addTextIfNeeded();
final Element closedEl = elementStack.isEmpty() ? null : elementStack.pop();
if (closedEl != null) {
if (elementStack.isEmpty()) {
// Is this the root element?
doc.appendChild(closedEl);
} else {
final Element parentEl = elementStack.peek();
parentEl.appendChild(closedEl);
}
closedEl.setUserData(LINE_NUMBER_END, String.valueOf(this.locator.getLineNumber()), null);
closedEl.setUserData(COLUMN_NUMBER_END, String.valueOf(this.locator.getColumnNumber()), null);
}
}
@Override
public void characters(final char[] ch, final int start, final int length) throws SAXException {
textBuffer.append(ch, start, length);
}
@Override
public InputSource resolveEntity(String publicId, String systemId) throws IOException, SAXException {
// do not resolve external dtd
return new InputSource(new StringReader(""));
}
// Outputs text accumulated under the current node
private void addTextIfNeeded() {
if (textBuffer.length() > 0) {
final Element el = elementStack.isEmpty() ? null : elementStack.peek();
if (el != null) {
final Node textNode = doc.createTextNode(textBuffer.toString());
el.appendChild(textNode);
textBuffer.delete(0, textBuffer.length());
}
}
}
};
parser.parse(is, handler);
return doc;
}
use of javax.xml.parsers.SAXParserFactory in project hive by apache.
the class JUnitReportParser method parse.
private void parse() {
populateTestFileList(directory);
for (File file : testOutputFiles) {
FileInputStream stream = null;
try {
stream = new FileInputStream(file);
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
saxParser.parse(new InputSource(stream), new DefaultHandler() {
private String name;
private boolean failedOrErrored;
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) {
if ("testcase".equals(qName)) {
name = attributes.getValue("classname");
failedOrErrored = false;
if (name == null || "junit.framework.TestSuite".equals(name)) {
name = attributes.getValue("name");
} else {
name = name + "." + attributes.getValue("name");
}
} else if (name != null) {
if ("failure".equals(qName) || "error".equals(qName)) {
failedOrErrored = true;
} else if ("skipped".equals(qName)) {
name = null;
}
}
}
@Override
public void endElement(String uri, String localName, String qName) {
if ("testcase".equals(qName)) {
if (name != null) {
executedTests.add(name);
if (failedOrErrored) {
failedTests.add(name);
}
}
}
}
});
} catch (Exception e) {
logger.error("Error parsing file " + file, e);
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
logger.warn("Error closing file " + file, e);
}
}
}
}
}
use of javax.xml.parsers.SAXParserFactory in project tomcat by apache.
the class JspDocumentParser method getSAXParser.
/*
* Gets SAXParser.
*
* @param validating Indicates whether the requested SAXParser should
* be validating
* @param jspDocParser The JSP document parser
*
* @return The SAXParser
*/
private static SAXParser getSAXParser(boolean validating, JspDocumentParser jspDocParser) throws Exception {
ClassLoader original;
if (Constants.IS_SECURITY_ENABLED) {
PrivilegedGetTccl pa = new PrivilegedGetTccl();
original = AccessController.doPrivileged(pa);
} else {
original = Thread.currentThread().getContextClassLoader();
}
try {
if (Constants.IS_SECURITY_ENABLED) {
PrivilegedSetTccl pa = new PrivilegedSetTccl(JspDocumentParser.class.getClassLoader());
AccessController.doPrivileged(pa);
} else {
Thread.currentThread().setContextClassLoader(JspDocumentParser.class.getClassLoader());
}
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
// Preserve xmlns attributes
factory.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
factory.setValidating(validating);
if (validating) {
// Enable DTD validation
factory.setFeature("http://xml.org/sax/features/validation", true);
// Enable schema validation
factory.setFeature("http://apache.org/xml/features/validation/schema", true);
}
// Configure the parser
SAXParser saxParser = factory.newSAXParser();
XMLReader xmlReader = saxParser.getXMLReader();
xmlReader.setProperty(LEXICAL_HANDLER_PROPERTY, jspDocParser);
xmlReader.setErrorHandler(jspDocParser);
return saxParser;
} finally {
if (Constants.IS_SECURITY_ENABLED) {
PrivilegedSetTccl pa = new PrivilegedSetTccl(original);
AccessController.doPrivileged(pa);
} else {
Thread.currentThread().setContextClassLoader(original);
}
}
}
use of javax.xml.parsers.SAXParserFactory in project bigbluebutton by bigbluebutton.
the class GetAllUsersCommand method handleResponse.
public void handleResponse(EslMessage response, ConferenceEventListener eventListener) {
//Test for Known Conference
String firstLine = response.getBodyLines().get(0);
if (!firstLine.startsWith("<?xml")) {
// System.out.println("Not XML: [{}]", firstLine);
return;
}
XMLResponseConferenceListParser confXML = new XMLResponseConferenceListParser();
//get a factory
SAXParserFactory spf = SAXParserFactory.newInstance();
try {
//get a new instance of parser
SAXParser sp = spf.newSAXParser();
//Hack turning body lines back into string then to ByteStream.... BLAH!
String responseBody = StringUtils.join(response.getBodyLines(), "\n");
//http://mark.koli.ch/2009/02/resolving-orgxmlsaxsaxparseexception-content-is-not-allowed-in-prolog.html
//This Sux!
responseBody = responseBody.trim().replaceFirst("^([\\W]+)<", "<");
ByteArrayInputStream bs = new ByteArrayInputStream(responseBody.getBytes());
sp.parse(bs, confXML);
//Maybe move this to XMLResponseConferenceListParser, sendConfrenceEvents ?
VoiceUserJoinedEvent pj;
for (ConferenceMember member : confXML.getConferenceList()) {
//Foreach found member in conference create a JoinedEvent
String callerId = member.getCallerId();
String callerIdName = member.getCallerIdName();
String voiceUserId = callerIdName;
Matcher matcher = CALLERNAME_PATTERN.matcher(callerIdName);
if (matcher.matches()) {
voiceUserId = matcher.group(1).trim();
callerIdName = matcher.group(2).trim();
}
pj = new VoiceUserJoinedEvent(voiceUserId, member.getId().toString(), confXML.getConferenceRoom(), callerId, callerIdName, member.getMuted(), member.getSpeaking(), null);
eventListener.handleConferenceEvent(pj);
}
} catch (SAXException se) {
// System.out.println("Cannot parse repsonce. ", se);
} catch (ParserConfigurationException pce) {
// System.out.println("ParserConfigurationException. ", pce);
} catch (IOException ie) {
// System.out.println("Cannot parse repsonce. IO Exception. ", ie);
}
}
use of javax.xml.parsers.SAXParserFactory in project blade by biezhi.
the class XmlParser method setValidating.
/* ------------------------------------------------------------ */
public void setValidating(boolean validating) {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setValidating(validating);
_parser = factory.newSAXParser();
try {
if (validating)
_parser.getXMLReader().setFeature("http://apache.org/xml/features/validation/schema", validating);
} catch (Exception e) {
if (validating)
LOG.warn("Schema validation may not be supported: ", e);
else
LOG.ignore(e);
}
_parser.getXMLReader().setFeature("http://xml.org/sax/features/validation", validating);
_parser.getXMLReader().setFeature("http://xml.org/sax/features/namespaces", true);
_parser.getXMLReader().setFeature("http://xml.org/sax/features/namespace-prefixes", false);
try {
if (validating)
_parser.getXMLReader().setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", validating);
} catch (Exception e) {
LOG.warn(e.getMessage());
}
} catch (Exception e) {
LOG.warn(Log.EXCEPTION, e);
throw new Error(e.toString());
}
}
Aggregations