use of org.xml.sax.Locator in project camel by apache.
the class RouteCoverageXmlParser method parseXml.
/**
* Parses the XML.
*
* @param camelContext the CamelContext
* @param is the XML content as an input stream
* @return the DOM model of the routes with coverage information stored as attributes
* @throws Exception is thrown if error parsing
*/
public static Document parseXml(final CamelContext camelContext, final InputStream is) throws Exception {
final SAXParserFactory factory = SAXParserFactory.newInstance();
final SAXParser parser = factory.newSAXParser();
final DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
final DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
final Document doc = docBuilder.newDocument();
final Stack<Element> elementStack = new Stack<Element>();
final StringBuilder textBuffer = new StringBuilder();
final DefaultHandler handler = new DefaultHandler() {
@Override
public void setDocumentLocator(final Locator locator) {
// noop
}
@Override
public void startElement(final String uri, final String localName, final String qName, final Attributes attributes) throws SAXException {
addTextIfNeeded();
final Element el = doc.createElement(qName);
// add other elements
for (int i = 0; i < attributes.getLength(); i++) {
el.setAttribute(attributes.getQName(i), attributes.getValue(i));
}
String id = el.getAttribute("id");
if (id != null) {
try {
if ("route".equals(qName)) {
ManagedRouteMBean route = camelContext.getManagedRoute(id, ManagedRouteMBean.class);
if (route != null) {
long total = route.getExchangesTotal();
el.setAttribute("exchangesTotal", "" + total);
long totalTime = route.getTotalProcessingTime();
el.setAttribute("totalProcessingTime", "" + totalTime);
}
} else if ("from".equals(qName)) {
// TODO: include the stats from the route mbean as that would be the same
} else {
ManagedProcessorMBean processor = camelContext.getManagedProcessor(id, ManagedProcessorMBean.class);
if (processor != null) {
long total = processor.getExchangesTotal();
el.setAttribute("exchangesTotal", "" + total);
long totalTime = processor.getTotalProcessingTime();
el.setAttribute("totalProcessingTime", "" + totalTime);
}
}
} catch (Exception e) {
// ignore
}
}
// we do not want customId in output
el.removeAttribute("customId");
elementStack.push(el);
}
@Override
public void endElement(final String uri, final String localName, final String qName) {
addTextIfNeeded();
final Element closedEl = elementStack.pop();
if (elementStack.isEmpty()) {
// is this the root element?
doc.appendChild(closedEl);
} else {
final Element parentEl = elementStack.peek();
parentEl.appendChild(closedEl);
}
}
@Override
public void characters(final char[] ch, final int start, final int length) throws SAXException {
textBuffer.append(ch, start, length);
}
/**
* outputs text accumulated under the current node
*/
private void addTextIfNeeded() {
if (textBuffer.length() > 0) {
final Element el = elementStack.peek();
final Node textNode = doc.createTextNode(textBuffer.toString());
el.appendChild(textNode);
textBuffer.delete(0, textBuffer.length());
}
}
};
parser.parse(is, handler);
return doc;
}
use of org.xml.sax.Locator in project robovm by robovm.
the class ParserAdapterTest method testSetDocumentLocator.
public void testSetDocumentLocator() {
Locator l = new LocatorImpl();
adapter.setDocumentLocator(l);
assertEquals(logger.size(), 1);
assertEquals("setDocumentLocator", logger.getMethod());
assertEquals(new Object[] { l }, logger.getArgs());
adapter.setDocumentLocator(null);
assertEquals(logger.size(), 2);
assertEquals("setDocumentLocator", logger.getMethod());
assertEquals(new Object[] { null }, logger.getArgs());
}
use of org.xml.sax.Locator in project robovm by robovm.
the class ProcessorLRE method startElement.
/**
* Receive notification of the start of an element.
*
* @param handler non-null reference to current StylesheetHandler that is constructing the Templates.
* @param uri The Namespace URI, or an empty string.
* @param localName The local name (without prefix), or empty string if not namespace processing.
* @param rawName The qualified name (with prefix).
* @param attributes The specified or defaulted attributes.
*/
public void startElement(StylesheetHandler handler, String uri, String localName, String rawName, Attributes attributes) throws org.xml.sax.SAXException {
try {
ElemTemplateElement p = handler.getElemTemplateElement();
boolean excludeXSLDecl = false;
boolean isLREAsStyleSheet = false;
if (null == p) {
// Literal Result Template as stylesheet.
XSLTElementProcessor lreProcessor = handler.popProcessor();
XSLTElementProcessor stylesheetProcessor = handler.getProcessorFor(Constants.S_XSLNAMESPACEURL, "stylesheet", "xsl:stylesheet");
handler.pushProcessor(lreProcessor);
Stylesheet stylesheet;
try {
stylesheet = getStylesheetRoot(handler);
} catch (TransformerConfigurationException tfe) {
throw new TransformerException(tfe);
}
// stylesheet.setDOMBackPointer(handler.getOriginatingNode());
// ***** Note that we're assigning an empty locator. Is this necessary?
SAXSourceLocator slocator = new SAXSourceLocator();
Locator locator = handler.getLocator();
if (null != locator) {
slocator.setLineNumber(locator.getLineNumber());
slocator.setColumnNumber(locator.getColumnNumber());
slocator.setPublicId(locator.getPublicId());
slocator.setSystemId(locator.getSystemId());
}
stylesheet.setLocaterInfo(slocator);
stylesheet.setPrefixes(handler.getNamespaceSupport());
handler.pushStylesheet(stylesheet);
isLREAsStyleSheet = true;
AttributesImpl stylesheetAttrs = new AttributesImpl();
AttributesImpl lreAttrs = new AttributesImpl();
int n = attributes.getLength();
for (int i = 0; i < n; i++) {
String attrLocalName = attributes.getLocalName(i);
String attrUri = attributes.getURI(i);
String value = attributes.getValue(i);
if ((null != attrUri) && attrUri.equals(Constants.S_XSLNAMESPACEURL)) {
stylesheetAttrs.addAttribute(null, attrLocalName, attrLocalName, attributes.getType(i), attributes.getValue(i));
} else if ((attrLocalName.startsWith("xmlns:") || attrLocalName.equals("xmlns")) && value.equals(Constants.S_XSLNAMESPACEURL)) {
// ignore
} else {
lreAttrs.addAttribute(attrUri, attrLocalName, attributes.getQName(i), attributes.getType(i), attributes.getValue(i));
}
}
attributes = lreAttrs;
// allowed on a stylesheet.
try {
stylesheetProcessor.setPropertiesFromAttributes(handler, "stylesheet", stylesheetAttrs, stylesheet);
} catch (Exception e) {
if (stylesheet.getDeclaredPrefixes() == null || !declaredXSLNS(stylesheet)) {
throw new org.xml.sax.SAXException(XSLMessages.createWarning(XSLTErrorResources.WG_OLD_XSLT_NS, null));
} else {
throw new org.xml.sax.SAXException(e);
}
}
handler.pushElemTemplateElement(stylesheet);
ElemTemplate template = new ElemTemplate();
if (slocator != null)
template.setLocaterInfo(slocator);
appendAndPush(handler, template);
XPath rootMatch = new XPath("/", stylesheet, stylesheet, XPath.MATCH, handler.getStylesheetProcessor().getErrorListener());
template.setMatch(rootMatch);
// template.setDOMBackPointer(handler.getOriginatingNode());
stylesheet.setTemplate(template);
p = handler.getElemTemplateElement();
excludeXSLDecl = true;
}
XSLTElementDef def = getElemDef();
Class classObject = def.getClassObject();
boolean isExtension = false;
boolean isComponentDecl = false;
boolean isUnknownTopLevel = false;
while (null != p) {
// System.out.println("Checking: "+p);
if (p instanceof ElemLiteralResult) {
ElemLiteralResult parentElem = (ElemLiteralResult) p;
isExtension = parentElem.containsExtensionElementURI(uri);
} else if (p instanceof Stylesheet) {
Stylesheet parentElem = (Stylesheet) p;
isExtension = parentElem.containsExtensionElementURI(uri);
if ((false == isExtension) && (null != uri) && (uri.equals(Constants.S_BUILTIN_EXTENSIONS_URL) || uri.equals(Constants.S_BUILTIN_OLD_EXTENSIONS_URL))) {
isComponentDecl = true;
} else {
isUnknownTopLevel = true;
}
}
if (isExtension)
break;
p = p.getParentElem();
}
ElemTemplateElement elem = null;
try {
if (isExtension) {
// System.out.println("Creating extension(1): "+uri);
elem = new ElemExtensionCall();
} else if (isComponentDecl) {
elem = (ElemTemplateElement) classObject.newInstance();
} else if (isUnknownTopLevel) {
// TBD: Investigate, not sure about this. -sb
elem = (ElemTemplateElement) classObject.newInstance();
} else {
elem = (ElemTemplateElement) classObject.newInstance();
}
elem.setDOMBackPointer(handler.getOriginatingNode());
elem.setLocaterInfo(handler.getLocator());
elem.setPrefixes(handler.getNamespaceSupport(), excludeXSLDecl);
if (elem instanceof ElemLiteralResult) {
((ElemLiteralResult) elem).setNamespace(uri);
((ElemLiteralResult) elem).setLocalName(localName);
((ElemLiteralResult) elem).setRawName(rawName);
((ElemLiteralResult) elem).setIsLiteralResultAsStylesheet(isLREAsStyleSheet);
}
} catch (InstantiationException ie) {
//"Failed creating ElemLiteralResult instance!", ie);
handler.error(XSLTErrorResources.ER_FAILED_CREATING_ELEMLITRSLT, null, ie);
} catch (IllegalAccessException iae) {
//"Failed creating ElemLiteralResult instance!", iae);
handler.error(XSLTErrorResources.ER_FAILED_CREATING_ELEMLITRSLT, null, iae);
}
setPropertiesFromAttributes(handler, rawName, attributes, elem);
// bit of a hack here...
if (!isExtension && (elem instanceof ElemLiteralResult)) {
isExtension = ((ElemLiteralResult) elem).containsExtensionElementURI(uri);
if (isExtension) {
// System.out.println("Creating extension(2): "+uri);
elem = new ElemExtensionCall();
elem.setLocaterInfo(handler.getLocator());
elem.setPrefixes(handler.getNamespaceSupport());
((ElemLiteralResult) elem).setNamespace(uri);
((ElemLiteralResult) elem).setLocalName(localName);
((ElemLiteralResult) elem).setRawName(rawName);
setPropertiesFromAttributes(handler, rawName, attributes, elem);
}
}
appendAndPush(handler, elem);
} catch (TransformerException te) {
throw new org.xml.sax.SAXException(te);
}
}
use of org.xml.sax.Locator in project robovm by robovm.
the class TreeWalker method startNode.
/**
* Start processing given node
*
*
* @param node Node to process
*
* @throws org.xml.sax.SAXException
*/
protected void startNode(Node node) throws org.xml.sax.SAXException {
if (node instanceof Locator) {
Locator loc = (Locator) node;
m_locator.setColumnNumber(loc.getColumnNumber());
m_locator.setLineNumber(loc.getLineNumber());
m_locator.setPublicId(loc.getPublicId());
m_locator.setSystemId(loc.getSystemId());
} else {
m_locator.setColumnNumber(0);
m_locator.setLineNumber(0);
}
switch(node.getNodeType()) {
case Node.COMMENT_NODE:
{
String data = ((Comment) node).getData();
if (m_contentHandler instanceof LexicalHandler) {
LexicalHandler lh = ((LexicalHandler) this.m_contentHandler);
lh.comment(data.toCharArray(), 0, data.length());
}
}
break;
case Node.DOCUMENT_FRAGMENT_NODE:
// ??;
break;
case Node.DOCUMENT_NODE:
break;
case Node.ELEMENT_NODE:
Element elem_node = (Element) node;
{
// Make sure the namespace node
// for the element itself is declared
// to the ContentHandler
String uri = elem_node.getNamespaceURI();
if (uri != null) {
String prefix = elem_node.getPrefix();
if (prefix == null)
prefix = "";
this.m_contentHandler.startPrefixMapping(prefix, uri);
}
}
NamedNodeMap atts = elem_node.getAttributes();
int nAttrs = atts.getLength();
// each attribute is declared to the ContentHandler
for (int i = 0; i < nAttrs; i++) {
final Node attr = atts.item(i);
final String attrName = attr.getNodeName();
final int colon = attrName.indexOf(':');
final String prefix;
// System.out.println("TreeWalker#startNode: attr["+i+"] = "+attrName+", "+attr.getNodeValue());
if (attrName.equals("xmlns") || attrName.startsWith("xmlns:")) {
// to "Steven Murray" <smurray@ebt.com>.
if (colon < 0)
prefix = "";
else
prefix = attrName.substring(colon + 1);
this.m_contentHandler.startPrefixMapping(prefix, attr.getNodeValue());
} else if (colon > 0) {
prefix = attrName.substring(0, colon);
String uri = attr.getNamespaceURI();
if (uri != null)
this.m_contentHandler.startPrefixMapping(prefix, uri);
}
}
String ns = m_dh.getNamespaceOfNode(node);
if (null == ns)
ns = "";
this.m_contentHandler.startElement(ns, m_dh.getLocalNameOfNode(node), node.getNodeName(), new AttList(atts, m_dh));
break;
case Node.PROCESSING_INSTRUCTION_NODE:
{
ProcessingInstruction pi = (ProcessingInstruction) node;
String name = pi.getNodeName();
// String data = pi.getData();
if (name.equals("xslt-next-is-raw")) {
nextIsRaw = true;
} else {
this.m_contentHandler.processingInstruction(pi.getNodeName(), pi.getData());
}
}
break;
case Node.CDATA_SECTION_NODE:
{
boolean isLexH = (m_contentHandler instanceof LexicalHandler);
LexicalHandler lh = isLexH ? ((LexicalHandler) this.m_contentHandler) : null;
if (isLexH) {
lh.startCDATA();
}
dispatachChars(node);
{
if (isLexH) {
lh.endCDATA();
}
}
}
break;
case Node.TEXT_NODE:
{
if (nextIsRaw) {
nextIsRaw = false;
m_contentHandler.processingInstruction(javax.xml.transform.Result.PI_DISABLE_OUTPUT_ESCAPING, "");
dispatachChars(node);
m_contentHandler.processingInstruction(javax.xml.transform.Result.PI_ENABLE_OUTPUT_ESCAPING, "");
} else {
dispatachChars(node);
}
}
break;
case Node.ENTITY_REFERENCE_NODE:
{
EntityReference eref = (EntityReference) node;
if (m_contentHandler instanceof LexicalHandler) {
((LexicalHandler) this.m_contentHandler).startEntity(eref.getNodeName());
} else {
// warning("Can not output entity to a pure SAX ContentHandler");
}
}
break;
default:
}
}
use of org.xml.sax.Locator in project geode by apache.
the class AbstractXmlParserJUnitTest method testSetDocumentLocator.
/**
* Test method for {@link AbstractXmlParser#setDocumentLocator(Locator)}.
*/
@Test
public void testSetDocumentLocator() {
final MockXmlParser mockXmlParser = new MockXmlParser();
final Locator mockLocator = new Locator() {
@Override
public String getSystemId() {
return null;
}
@Override
public String getPublicId() {
return null;
}
@Override
public int getLineNumber() {
return 0;
}
@Override
public int getColumnNumber() {
return 0;
}
};
mockXmlParser.setDocumentLocator(mockLocator);
assertSame(mockLocator, mockXmlParser.documentLocator);
}
Aggregations