/** {@inheritDoc} */
  @Override
  public void startDocument() throws SAXException {
    LOG.debug("Starting XML parsing");

    // XmlToken
    XmlToken token = new XmlToken();
    token.setLine(locator.getLineNumber());
    token.setColumn(locator.getColumnNumber());
    token.setType(XmlTokenTypes.DOCUMENT);
    token.setText(file.getName());

    // Node
    root = new DetailAST();
    root.initialize(token);

    currentNode = root;

    // Path = package
    token = new XmlToken();
    token.setLine(locator.getLineNumber());
    token.setColumn(locator.getColumnNumber());
    token.setType(XmlTokenTypes.PATH);
    token.setText(file.getParent());
    DetailAST path = new DetailAST();
    path.initialize(token);
    root.addChild(path);
    DetailAST pathIdent = new DetailAST();
    token = new XmlToken();
    token.setLine(locator.getLineNumber());
    token.setColumn(locator.getColumnNumber());
    token.setType(XmlTokenTypes.IDENT);
    token.setText(file.getParent());
    pathIdent.initialize(token);
    path.addChild(pathIdent);

    // Fake child to match Java grammar structure
    pathIdent = new DetailAST();
    pathIdent.initialize(token);
    path.addChild(pathIdent);

    // Name = Type
    token = new XmlToken();
    token.setLine(locator.getLineNumber());
    token.setColumn(locator.getColumnNumber());
    token.setType(XmlTokenTypes.IDENT);
    token.setText(file.getName());
    DetailAST name = new DetailAST();
    name.initialize(token);
    root.addChild(name);
    DetailAST nameIdent = new DetailAST();
    token = new XmlToken();
    token.setLine(locator.getLineNumber());
    token.setColumn(locator.getColumnNumber());
    token.setType(XmlTokenTypes.IDENT);
    token.setText(file.getName());
    nameIdent.initialize(token);
    name.addChild(nameIdent);
  }
    private SAXLocation(Locator locator) {

      lineNumber = locator.getLineNumber();
      columnNumber = locator.getColumnNumber();
      publicId = locator.getPublicId();
      systemId = locator.getSystemId();
    }
Exemple #3
0
 public static String toString(final Locator loc) {
   return loc.getSystemId()
       + ", line "
       + loc.getLineNumber()
       + ", column "
       + loc.getColumnNumber();
 }
 /**
  * Copy constructor.
  *
  * <p>Create a persistent copy of the current state of a locator.
  * When the original locator changes, this copy will still keep
  * the original values (and it can be used outside the scope of
  * DocumentHandler methods).</p>
  *
  * @param locator The locator to copy.
  */
 public SerializableLocatorImpl (org.xml.sax.Locator locator)
 {
     setPublicId(locator.getPublicId());
     setSystemId(locator.getSystemId());
     setLineNumber(locator.getLineNumber());
     setColumnNumber(locator.getColumnNumber());
 }
 /**
  * Constructor SAXSourceLocator
  *
  * @param locator Source locator
  */
 public SAXSourceLocator(Locator locator) {
   m_locator = locator;
   this.setColumnNumber(locator.getColumnNumber());
   this.setLineNumber(locator.getLineNumber());
   this.setPublicId(locator.getPublicId());
   this.setSystemId(locator.getSystemId());
 }
  public void setDocumentLocator(Locator loc) {
    locator = loc;

    ParseLocationListener pll = rdfParser.getParseLocationListener();
    if (pll != null && loc != null) {
      pll.parseLocationUpdate(loc.getLineNumber(), loc.getColumnNumber());
    }
  }
 @Override
 public FileSourceLocator getSourceLocator() {
   if (super.getSourceLocator() == null && locator != null) {
     super.setSourceLocator(
         new PsiXmlLocator(locator.getLineNumber(), locator.getColumnNumber(), getId()));
   }
   return super.getSourceLocator();
 }
 private void addLocatorLocation() {
   if (locator != null) {
     String systemId = locator.getSystemId();
     log4j.debug(systemId);
     if (uri == systemId || (uri != null && uri.equals(systemId))) {
       owner.addLocatorLocation(locator.getLineNumber(), locator.getColumnNumber());
     }
   }
 }
Exemple #9
0
 public LocatedMessage(Locator locator, String key, String format, Object... arguments) {
   this(
       locator.getSystemId(),
       locator.getLineNumber(),
       locator.getColumnNumber(),
       null,
       key,
       format,
       arguments);
 }
  /** {@inheritDoc} */
  public void processingInstruction(String target, String data) throws SAXException {
    LOG.debug("Processing instruction : " + target);
    LOG.debug("  Args : " + data);

    // XmlToken
    XmlToken token = new XmlToken();
    token.setLine(locator.getLineNumber());
    token.setColumn(locator.getColumnNumber());
    token.setText(target);
    token.setType(XmlTokenTypes.PROCESSING_INSTRUCTION);

    // Node
    DetailAST child = new DetailAST();
    child.initialize(token);
    child.setText(token.getText());

    // Target
    token = new XmlToken();
    token.setLine(locator.getLineNumber());
    token.setColumn(locator.getColumnNumber());
    token.setText(target);
    token.setType(XmlTokenTypes.PROCESSING_TARGET);

    DetailAST targetAST = new DetailAST();
    targetAST.initialize(token);
    targetAST.setText(token.getText());
    child.addChild(targetAST);

    // Data
    token = new XmlToken();
    token.setLine(locator.getLineNumber());
    token.setColumn(locator.getColumnNumber());
    token.setText(data);
    token.setType(XmlTokenTypes.PROCESSING_DATA);

    DetailAST dataAST = new DetailAST();
    dataAST.initialize(token);
    dataAST.setText(token.getText());
    child.addChild(dataAST);

    // Parent
    currentNode.addChild(child);
  }
  /** {@inheritDoc} */
  public void startPrefixMapping(String prefix, String URI) throws SAXException {
    LOG.debug("Prefix mapping : " + URI + ", chosen prefix : " + prefix);

    // XmlToken
    XmlToken token = new XmlToken();
    token.setLine(locator.getLineNumber());
    token.setColumn(locator.getColumnNumber());
    token.setText(prefix);
    token.setType(XmlTokenTypes.PREFIX_MAPPING);

    // Node
    DetailAST child = new DetailAST();
    child.initialize(token);

    // Prefix
    token = new XmlToken();
    token.setLine(locator.getLineNumber());
    token.setColumn(locator.getColumnNumber());
    token.setText(prefix);
    token.setType(XmlTokenTypes.IDENT);

    DetailAST prefixAST = new DetailAST();
    prefixAST.initialize(token);
    prefixAST.setText(token.getText());

    child.addChild(prefixAST);

    // URI
    token = new XmlToken();
    token.setLine(locator.getLineNumber());
    token.setColumn(locator.getColumnNumber());
    token.setText(URI);
    token.setType(XmlTokenTypes.STRING_LITERAL);

    DetailAST uri = new DetailAST();
    uri.initialize(token);

    child.addChild(uri);

    // Parent
    currentNode.addChild(child);
  }
 private void checkNumber(Attributes attrs) throws SAXException {
   if (StringTools.isEmpty(attrs.getValue("no"))) {
     throw new SAXException(
         "References cannot be empty: "
             + "\n Line: "
             + pLocator.getLineNumber()
             + ", column: "
             + pLocator.getColumnNumber()
             + ".");
   } else if (Integer.parseInt(attrs.getValue("no")) < 1) {
     throw new SAXException(
         "References must be larger than 0: "
             + attrs.getValue("no")
             + "\n Line: "
             + pLocator.getLineNumber()
             + ", column: "
             + pLocator.getColumnNumber()
             + ".");
   }
 }
 private final void throwException(String message) throws SAXException {
   if (documentLocator != null) {
     message =
         "At line "
             + documentLocator.getLineNumber()
             + ", column "
             + documentLocator.getColumnNumber()
             + ": "
             + message;
   }
   throw new SAXException(message);
 }
 /**
  * Computes a string containing the current parse location or an empty string if there is no
  * locator.
  *
  * @return the location as debug-text.
  */
 private String getLocatorString() {
   final Locator locator = getLocator();
   if (locator == null) {
     return "";
   }
   final StringBuffer message = new StringBuffer(100);
   message.append(" [Location: Line=");
   message.append(locator.getLineNumber());
   message.append(" Column=");
   message.append(locator.getColumnNumber());
   message.append("] ");
   return message.toString();
 }
 private void checkRefNumber(int refNumber) throws SAXException {
   if (refNumber > elementList.size()) {
     throw new SAXException(
         "Only backward references in match elements are possible, tried to specify token "
             + refNumber
             + "\n"
             + "Line: "
             + pLocator.getLineNumber()
             + ", column: "
             + pLocator.getColumnNumber()
             + ".");
   }
 }
 @Override
 public void startElement(
     final String uri, final String localName, final String qName, final Attributes attributes)
     throws SAXException {
   addTextNode();
   final Element e = doc.createElementNS(uri, qName);
   for (int i = 0; i < attributes.getLength(); i++) {
     e.setAttributeNS(attributes.getURI(i), attributes.getQName(i), attributes.getValue(i));
   }
   e.setUserData(
       KEY_LOCATION, new NodeLocation(locator.getLineNumber(), locator.getColumnNumber()), null);
   elementStack.push(e);
 }
Exemple #17
0
  /**
   * Called by the SAX parser when an error occurs. Used by this class to report the current
   * position in the file.
   *
   * @param e The exception that occurred.
   * @throws SAXException if the error reporting throws an exception.
   */
  @Override
  public void error(SAXParseException e) throws SAXException {
    LOG.severe(
        "Unable to parse xml file.  publicId=("
            + documentLocator.getPublicId()
            + "), systemId=("
            + documentLocator.getSystemId()
            + "), lineNumber="
            + documentLocator.getLineNumber()
            + ", columnNumber="
            + documentLocator.getColumnNumber()
            + ".");

    super.error(e);
  }
Exemple #18
0
    public void startElement(String ur, String localName, String qName, Attributes attributes) {
      currentQName = qName;

      if (qName.indexOf("BinData") == -1) {
        xmlBuffer.append("<");
        xmlBuffer.append(qName);
        for (int i = 0; i < attributes.getLength(); i++) {
          String key = XMLTools.escapeXML(attributes.getQName(i));
          String value = XMLTools.escapeXML(attributes.getValue(i));
          if (key.equals("BigEndian")) {
            String endian = value.toLowerCase();
            if (!endian.equals("true") && !endian.equals("false")) {
              // hack for files that specify 't' or 'f' instead of
              // 'true' or 'false'
              if (endian.startsWith("t")) endian = "true";
              else if (endian.startsWith("f")) endian = "false";
            }
            value = endian;
          }
          xmlBuffer.append(" ");
          xmlBuffer.append(key);
          xmlBuffer.append("=\"");
          xmlBuffer.append(value);
          xmlBuffer.append("\"");
        }
        xmlBuffer.append(">");
      } else {
        binData.add(new BinData(locator.getLineNumber(), locator.getColumnNumber()));
        String compress = attributes.getValue("Compression");
        compression.add(compress == null ? "" : compress);

        xmlBuffer.append("<");
        xmlBuffer.append(qName);
        for (int i = 0; i < attributes.getLength(); i++) {
          String key = XMLTools.escapeXML(attributes.getQName(i));
          String value = XMLTools.escapeXML(attributes.getValue(i));
          if (key.equals("Length")) value = "0";
          xmlBuffer.append(" ");
          xmlBuffer.append(key);
          xmlBuffer.append("=\"");
          xmlBuffer.append(value);
          xmlBuffer.append("\"");
        }
        xmlBuffer.append(">");
      }
    }
  /** {@inheritDoc} */
  public void skippedEntity(String text) throws SAXException {

    // XmlToken
    XmlToken token = new XmlToken();
    token.setLine(locator.getLineNumber());
    token.setColumn(locator.getColumnNumber());
    token.setText(text);
    token.setType(XmlTokenTypes.SKIPPED_ENTITY);

    // Node
    DetailAST child = new DetailAST();
    child.initialize(token);
    child.setText(token.getText());

    // Parent
    currentNode.addChild(child);
  }
  /** {@inheritDoc} */
  public void ignorableWhitespace(char[] ch, int start, int end) throws SAXException {

    String value = new String(ch, start, end);

    LOG.debug("ignorable whitespace : ..." + value + "...");

    // XmlToken
    XmlToken token = new XmlToken();
    token.setLine(locator.getLineNumber());
    token.setColumn(locator.getColumnNumber() + start);
    token.setText(value);
    token.setType(XmlTokenTypes.WHITE_SPACE);

    // Node
    DetailAST child = new DetailAST();
    child.initialize(token);
    child.setText(token.getText());

    // Parent
    currentNode.addChild(child);
  }
  /** {@inheritDoc} */
  public void characters(char[] ch, int start, int end) throws SAXException {

    String value = new String(ch, start, end);

    LOG.debug("#PCDATA : " + value);

    // XmlToken
    XmlToken token = new XmlToken();
    token.setLine(locator.getLineNumber());
    token.setColumn(locator.getColumnNumber() + start);
    token.setText(value);
    token.setType(XmlTokenTypes.PCDATA);

    // Node
    DetailAST child = new DetailAST();
    child.initialize(token);
    child.setText(token.getText());

    // Parent
    currentNode.addChild(child);
  }
  protected XMLValidationError nextError(SAXParseException e, boolean isFatal) {
    String errorMessage = e.getMessage();

    int lineNumber = locator.getLineNumber();
    int columnNumber = locator.getColumnNumber();

    log(
        this,
        (isFatal ? "FATAL " : "Non-Fatal")
            + "Error on line "
            + lineNumber
            + ", column "
            + columnNumber
            + ": "
            + errorMessage);

    XMLValidationError validationError = new XMLValidationError();
    validationError.setLineNumber(lineNumber);
    validationError.setColumnNumber(columnNumber);
    validationError.setErrorMessage(errorMessage);
    return validationError;
  }
  public void startElement(String uri, String localname, String qName, Attributes attributes)
      throws SAXException {

    namespaceSupport.startElement();

    // Handle location data
    if (locationData == null && locator != null && mustOutputFirstElement) {
      final String systemId = locator.getSystemId();
      if (systemId != null) {
        locationData =
            new LocationData(systemId, locator.getLineNumber(), locator.getColumnNumber());
      }
    }

    // Check for XForms or extension namespaces
    final boolean isXForms = XFormsConstants.XFORMS_NAMESPACE_URI.equals(uri);
    final boolean isXXForms = XFormsConstants.XXFORMS_NAMESPACE_URI.equals(uri);
    final boolean isEXForms = XFormsConstants.EXFORMS_NAMESPACE_URI.equals(uri);
    final boolean isXBL = XFormsConstants.XBL_NAMESPACE_URI.equals(uri);
    final boolean isXHTML = XMLConstants.XHTML_NAMESPACE_URI.equals(uri);

    // TODO: how else can we handle components?
    // NOTE: Here we have an issue identifying which elements must have content preserved. For
    // example, an element
    // to which an XBL binding is applied should be preserved, because XBL template processing take
    // place during
    // static state analysis. In XFormsDocumentAnnotatorContentHandler, we detect XBL bindings.
    // Should we do the
    // same here again? It is wasteful to do it twice. Possibly, XFDACH could pass this information
    // here since
    // it already does all the work to detect content preservation. E.g. custom attribute.

    //        final boolean isXFormsOrExtension = isXForms || isXXForms || isEXForms || isXBL;
    final boolean isXFormsOrExtension = !isXHTML && !"".equals(uri); // see NOTE above
    final boolean isExtension =
        isXFormsOrExtension && !isXForms && !isXXForms && !isEXForms && !isXBL; // see NOTE above

    // Handle xml:base
    if (!inXFormsOrExtension) {
      final String xmlBaseAttribute = attributes.getValue(XMLConstants.XML_URI, "base");
      if (xmlBaseAttribute == null) {
        xmlBaseStack.push(xmlBaseStack.peek());
      } else {
        try {
          final URI currentXMLBaseURI = xmlBaseStack.peek();
          xmlBaseStack.push(
              currentXMLBaseURI
                  .resolve(new URI(xmlBaseAttribute))
                  .normalize()); // normalize to remove "..", etc.
        } catch (URISyntaxException e) {
          throw new ValidationException(
              "Error creating URI from: '"
                  + xmlBaseStack.peek()
                  + "' and '"
                  + xmlBaseAttribute
                  + "'.",
              e,
              new LocationData(locator));
        }
      }
    }

    // Handle properties of the form @xxforms:* when outside of models or controls
    if (!inXFormsOrExtension && !isXFormsOrExtension) {
      final int attributesCount = attributes.getLength();
      for (int i = 0; i < attributesCount; i++) {
        final String attributeURI = attributes.getURI(i);
        if (XFormsConstants.XXFORMS_NAMESPACE_URI.equals(attributeURI)) {
          // Found xxforms:* attribute
          final String attributeLocalName = attributes.getLocalName(i);
          // Only take the first occurrence into account, and make sure the property is supported
          if (properties.get(attributeLocalName) == null
              && XFormsProperties.getPropertyDefinition(attributeLocalName) != null) {
            properties.put(attributeLocalName, attributes.getValue(i));
          }
        }
      }
    }

    if (level > 0 || !ignoreRootElement) {

      // Start extracting model or controls
      if (!inXFormsOrExtension && isXFormsOrExtension) {

        inXFormsOrExtension = true;
        xformsLevel = level;

        outputFirstElementIfNeeded();

        // Add xml:base on element
        attributes =
            XMLUtils.addOrReplaceAttribute(
                attributes, XMLConstants.XML_URI, "xml", "base", getCurrentBaseURI());

        sendStartPrefixMappings();
      }

      // Check for preserved content
      if (inXFormsOrExtension && !inPreserve) {
        // TODO: Just warn?
        if (isXXForms) {
          // Check that we are getting a valid xxforms:* element
          if (XFormsConstants.ALLOWED_XXFORMS_ELEMENTS.get(localname) == null
              && !XFormsActions.isActionName(XFormsConstants.XXFORMS_NAMESPACE_URI, localname))
            throw new ValidationException(
                "Invalid extension element in XForms document: " + qName,
                new LocationData(locator));
        } else if (isEXForms) {
          // Check that we are getting a valid exforms:* element
          if (XFormsConstants.ALLOWED_EXFORMS_ELEMENTS.get(localname) == null)
            throw new ValidationException(
                "Invalid eXForms element in XForms document: " + qName, new LocationData(locator));
        } else if (isXBL) {
          // Check that we are getting a valid xbl:* element
          if (XFormsConstants.ALLOWED_XBL_ELEMENTS.get(localname) == null)
            throw new ValidationException(
                "Invalid XBL element in XForms document: " + qName, new LocationData(locator));
        }

        // Preserve as is the content of labels, etc., instances, and schemas
        if ((XFormsConstants.LABEL_HINT_HELP_ALERT_ELEMENT.get(localname)
                        != null // labels, etc. may contain XHTML
                    || "instance".equals(localname))
                && isXForms // XForms instances
            || "schema".equals(localname) && XMLConstants.XSD_URI.equals(uri) // XML schemas
            || "xbl".equals(localname)
                && isXBL // preserve everything under xbl:xbl so that templates may be processed by
                         // static state
            || isExtension) {
          inPreserve = true;
          preserveLevel = level;
        }
      }

      // We are within preserved content or we output regular XForms content
      if (inXFormsOrExtension && (inPreserve || isXFormsOrExtension)) {
        super.startElement(uri, localname, qName, attributes);
      }
    } else {
      // Just open the root element
      outputFirstElementIfNeeded();
      sendStartPrefixMappings();
      super.startElement(uri, localname, qName, attributes);
    }

    level++;
  }
Exemple #24
0
 public int getColumnNumber() {
   return locator.getColumnNumber();
 }
 /** Save current location */
 public void saveLocation() {
   // Save current location
   line = locator.getLineNumber();
   column = locator.getColumnNumber();
 }
  /**
   * Start processing given node
   *
   * @param node Node to process
   * @throws org.xml.sax.SAXException
   */
  protected void startNode(Node node) throws org.xml.sax.SAXException {

    //   TODO: <REVIEW>
    //    A Serializer implements ContentHandler, but not NodeConsumer
    //    so drop this reference to NodeConsumer which would otherwise
    //    pull in all sorts of things
    //    if (m_contentHandler instanceof NodeConsumer)
    //    {
    //      ((NodeConsumer) m_contentHandler).setOriginatingNode(node);
    //    }
    //    TODO: </REVIEW>

    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();
        // System.out.println("TreeWalker#startNode: "+node.getNodeName());

        // Make sure the namespace node of
        // 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:")) {
            // Use "" instead of null, as Xerces likes "" for the
            // name of the default namespace.  Fix attributed
            // to "Steven Murray" <*****@*****.**>.
            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:
        {
          // String data = ((Text) node).getData();

          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:
    }
  }
  /** {@inheritDoc} */
  public void startElement(
      String nameSpaceURI, String localName, String rawName, Attributes attributs)
      throws SAXException {
    LOG.debug("Opening element : " + localName);

    int col = locator.getColumnNumber();

    // XmlToken
    XmlToken token = new XmlToken();
    token.setLine(locator.getLineNumber());
    token.setColumn(locator.getColumnNumber());
    token.setText(rawName);
    token.setType(XmlTokenTypes.ELEMENT);

    // Node
    DetailAST child = new DetailAST();
    child.initialize(token);

    // Parent
    currentNode.addChild(child);

    // Ident
    DetailAST ident = new DetailAST();
    token = new XmlToken();
    token.setLine(locator.getLineNumber());
    col++;
    token.setColumn(col);
    token.setText(localName);
    token.setType(XmlTokenTypes.IDENT);
    ident.initialize(token);
    child.addChild(ident);

    // Attributes
    LOG.debug("  Attributes : ");
    DetailAST attrs = new DetailAST();
    token = new XmlToken();
    token.setLine(locator.getLineNumber());
    col += rawName.length() + 1;
    token.setColumn(col);
    token.setText(rawName);
    token.setType(XmlTokenTypes.ATTRIBUTES);
    attrs.initialize(token);
    child.addChild(attrs);

    for (int index = 0; index < attributs.getLength(); index++) {

      // Attribut
      DetailAST attr = new DetailAST();
      token = new XmlToken();
      token.setLine(locator.getLineNumber());
      token.setColumn(index);
      token.setText(rawName);
      token.setType(XmlTokenTypes.ATTRIBUTE);
      attr.initialize(token);
      attrs.addChild(attr);
      LOG.debug("     - " + attributs.getLocalName(index) + " = " + attributs.getValue(index));

      // Ident
      ident = new DetailAST();
      token = new XmlToken();
      token.setLine(locator.getLineNumber());
      token.setColumn(index);
      token.setText(attributs.getLocalName(index));
      token.setType(XmlTokenTypes.IDENT);
      ident.initialize(token);
      attr.addChild(ident);

      // Value
      DetailAST value = new DetailAST();
      token = new XmlToken();
      token.setLine(locator.getLineNumber());
      token.setColumn(index + attributs.getLocalName(index).length() + 1);
      token.setText(attributs.getValue(index));
      token.setType(XmlTokenTypes.STRING_LITERAL);
      value.initialize(token);
      attr.addChild(value);

      // Go forward
      col += attributs.getLocalName(index).length() + attributs.getValue(index).length() + 2;
    }

    // This node is now he current node
    currentNode = child;
  }
 /**
  * Return the column number where the current document event ends.
  *
  * <p><strong>Warning:</strong> The return value from the method is intended only as an
  * approximation for the sake of error reporting; it is not intended to provide sufficient
  * information to edit the character content of the original XML document.
  *
  * <p>The return value is an approximation of the column number in the document entity or external
  * parsed entity where the markup triggering the event appears.
  *
  * @return The column number, or -1 if none is available.
  * @see #getLineNumber
  */
 public int getColumnNumber() {
   return (null == m_locator) ? super.getColumnNumber() : m_locator.getColumnNumber();
 }
Exemple #29
0
 public PresetParsingException rememberLocation(Locator locator) {
   if (locator == null) return this;
   this.columnNumber = locator.getColumnNumber();
   this.lineNumber = locator.getLineNumber();
   return this;
 }
  /**
   * 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;

        // Set properties from the attributes, but don't throw
        // an error if there is an attribute defined that is not
        // allowed on a stylesheet.
        try {
          stylesheetProcessor.setPropertiesFromAttributes(
              handler, "stylesheet", stylesheetAttrs, stylesheet);
        } catch (Exception e) {
          // This is pretty ugly, but it will have to do for now.
          // This is just trying to append some text specifying that
          // this error came from a missing or invalid XSLT namespace
          // declaration.
          // If someone comes up with a better solution, please feel
          // free to contribute it. -mm

          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) {
        handler.error(
            XSLTErrorResources.ER_FAILED_CREATING_ELEMLITRSLT,
            null,
            ie); // "Failed creating ElemLiteralResult instance!", ie);
      } catch (IllegalAccessException iae) {
        handler.error(
            XSLTErrorResources.ER_FAILED_CREATING_ELEMLITRSLT,
            null,
            iae); // "Failed creating ElemLiteralResult instance!", 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);
    }
  }