use of org.xml.sax.Locator 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 org.xml.sax.Locator in project j2objc by google.
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 j2objc by google.
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 (m_contentHandler instanceof NodeConsumer) {
((NodeConsumer) m_contentHandler).setOriginatingNode(node);
}
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:
NamedNodeMap atts = ((Element) node).getAttributes();
int nAttrs = atts.getLength();
for (int i = 0; i < nAttrs; i++) {
Node attr = atts.item(i);
String attrName = attr.getNodeName();
// System.out.println("TreeWalker#startNode: attr["+i+"] = "+attrName+", "+attr.getNodeValue());
if (attrName.equals("xmlns") || attrName.startsWith("xmlns:")) {
// System.out.println("TreeWalker#startNode: attr["+i+"] = "+attrName+", "+attr.getNodeValue());
int index;
// Use "" instead of null, as Xerces likes "" for the
// name of the default namespace. Fix attributed
// to "Steven Murray" <smurray@ebt.com>.
String prefix = (index = attrName.indexOf(":")) < 0 ? "" : attrName.substring(index + 1);
this.m_contentHandler.startPrefixMapping(prefix, attr.getNodeValue());
}
}
// System.out.println("m_dh.getNamespaceOfNode(node): "+m_dh.getNamespaceOfNode(node));
// System.out.println("m_dh.getLocalNameOfNode(node): "+m_dh.getLocalNameOfNode(node));
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 intellij-community by JetBrains.
the class RngXmlAttributeDescriptor method mergeWith.
public RngXmlAttributeDescriptor mergeWith(RngXmlAttributeDescriptor d) {
final QName name = d.myName.equals(UNKNOWN) ? myName : d.myName;
final HashMap<String, String> values = new HashMap<>(myValues);
values.putAll(d.myValues);
final THashSet<Locator> locations = new THashSet<>(myDeclarations, HASHING_STRATEGY);
locations.addAll(d.myDeclarations);
return new RngXmlAttributeDescriptor(myElementDescriptor, name, values, myOptional || d.myOptional, locations.toArray(new Locator[locations.size()]));
}
use of org.xml.sax.Locator in project camel by apache.
the class XmlLineNumberParser method parseXml.
/**
* Parses the XML.
*
* @param is the XML content as an input stream
* @param xmlTransformer the XML transformer
* @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 namespaces 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, XmlTextTransformer xmlTransformer, String rootNames, final String forceNamespace) throws Exception {
ObjectHelper.notNull(is, "is");
final XmlTextTransformer transformer = xmlTransformer == null ? new NoopTransformer() : xmlTransformer;
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(transformer.transform(attributes.getQName(i)), transformer.transform(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 {
char[] chars = new char[length];
System.arraycopy(ch, start, chars, 0, length);
String s = new String(chars);
s = transformer.transform(s);
textBuffer.append(s);
}
@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;
}
Aggregations