/** Find name spaces declaration in atrributes and move them to separate collection. */
  @Override
  protected final void newFrame(ElementFrame<Node, Node> frame) {
    Node element = getCurrentNode();
    frame.uris = new ArrayList<String>();
    frame.prefixes = new ArrayList<String>();
    frame.attributes = new ArrayList<Object>();

    if (context == null) {
      context = new W3CNamespaceContext();
    }
    if (element instanceof Element) {
      context.setElement((Element) element);
    }

    NamedNodeMap nodes = element.getAttributes();

    String ePrefix = element.getPrefix();
    if (ePrefix == null) {
      ePrefix = "";
    }

    if (nodes != null) {
      for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        String prefix = node.getPrefix();
        String localName = node.getLocalName();
        String value = node.getNodeValue();
        String name = node.getNodeName();

        if (prefix == null) {
          prefix = "";
        }

        if (name != null && "xmlns".equals(name)) {
          frame.uris.add(value);
          frame.prefixes.add("");
        } else if (prefix.length() > 0 && "xmlns".equals(prefix)) {
          frame.uris.add(value);
          frame.prefixes.add(localName);
        } else if (name.startsWith("xmlns:")) {
          prefix = name.substring(6);
          frame.uris.add(value);
          frame.prefixes.add(prefix);
        } else {
          frame.attributes.add(node);
        }
      }
    }
  }
Example #2
0
    public int getIndex(String qName) {
      String pre = null;
      String local = null;

      if (qName.lastIndexOf(':') != -1) {
        String[] split = qName.split(":");
        pre = split[0];
        local = split[1];
      } else {
        pre = "";
        local = qName;
      }

      for (int i = 0; i < atts.getLength(); i++) {
        Node att = (Node) atts.item(i);

        if (att.getLocalName().equals(local)) {
          String apre = att.getPrefix();

          if (apre == null) {
            apre = "";
          }

          if (pre.equals(apre)) {
            return i;
          }
        }
      }

      return -1;
    }
Example #3
0
 private Namespace getNodeNamespace() {
   String uri = dom.getNamespaceURI();
   String prefix = dom.getPrefix();
   if (uri == null) uri = "";
   if (prefix == null) prefix = "";
   return Namespace.create(prefix, uri);
 }
Example #4
0
  /**
   * Runs an XPath expression on this node.
   *
   * @param env
   * @param expression
   * @return array of results
   * @throws XPathExpressionException
   */
  public Value xpath(Env env, String expression) {
    try {
      XPath xpath = XPathFactory.newInstance().newXPath();

      InputSource is = new InputSource(asXML(env).toInputStream());
      NodeList nodes = (NodeList) xpath.evaluate(expression, is, XPathConstants.NODESET);

      int nodeLength = nodes.getLength();

      if (nodeLength == 0) return NullValue.NULL;

      // There are matching nodes
      ArrayValue result = new ArrayValueImpl();
      for (int i = 0; i < nodeLength; i++) {
        Node node = nodes.item(i);

        boolean isPrefix = node.getPrefix() != null;

        SimpleXMLElement xml =
            buildNode(env, _cls, null, nodes.item(i), node.getNamespaceURI(), isPrefix);

        result.put(wrapJava(env, _cls, xml));
      }

      return result;
    } catch (XPathExpressionException e) {
      env.warning(e);
      log.log(Level.FINE, e.getMessage());

      return NullValue.NULL;
    }
  }
Example #5
0
  /**
   * Retrieves the prefix associated with a namespace URI in the given context node.
   *
   * @param namespaceURI the namespace whose prefix is required
   * @param contextNode the node where to search for namespace declarations
   * @return the prefix associated with the namespace URI; the empty string indicates the default
   *     namespace, while <code>null</code> indicates no association
   */
  public static String getPrefix(String namespaceURI, Node contextNode) {
    switch (contextNode.getNodeType()) {
      case Node.ATTRIBUTE_NODE:
        contextNode = ((Attr) contextNode).getOwnerElement();
        break;
      case Node.ELEMENT_NODE:
        break;
      default:
        contextNode = contextNode.getParentNode();
    }

    while (contextNode != null && contextNode.getNodeType() == Node.ELEMENT_NODE) {
      Element contextElem = (Element) contextNode;
      NamedNodeMap attributes = contextElem.getAttributes();

      for (int i = 0, n = attributes.getLength(); i < n; i++) {
        Node attr = attributes.item(i);
        if (namespaceURI.equals(attr.getNodeValue())) {
          String prefix = attr.getPrefix();
          if ("xmlns".equals(prefix)) {
            return attr.getLocalName();
          } else if (prefix == null && "xmlns".equals(attr.getLocalName())) {
            return "";
          }
        }
      }
      contextNode = contextNode.getParentNode();
    }
    return null;
  }
  /**
   * Returns the CMDocument that corresponds to the DOM Node. or null if no CMDocument is
   * appropriate for the DOM Node.
   */
  public CMDocument getCorrespondingCMDocument(Node node) {
    CMDocument jcmdoc = null;
    if (node instanceof IDOMNode) {
      IDOMModel model = ((IDOMNode) node).getModel();
      String modelPath = model.getBaseLocation();
      if (modelPath != null && !IModelManager.UNMANAGED_MODEL.equals(modelPath)) {
        float version =
            DeploymentDescriptorPropertyCache.getInstance().getJSPVersion(new Path(modelPath));
        jcmdoc = JSPCMDocumentFactory.getCMDocument(version);
      }
    }
    if (jcmdoc == null) {
      jcmdoc = JSPCMDocumentFactory.getCMDocument();
    }

    CMDocument result = null;
    try {
      if (node.getNodeType() == Node.ELEMENT_NODE) {
        String elementName = node.getNodeName();

        // test to see if this node belongs to JSP's CMDocument (case
        // sensitive)
        CMElementDeclaration dec =
            (CMElementDeclaration) jcmdoc.getElements().getNamedItem(elementName);
        if (dec != null) {
          result = jcmdoc;
        }
      }

      String prefix = node.getPrefix();

      if (result == null && prefix != null && prefix.length() > 0 && node instanceof IDOMNode) {
        // check position dependent
        IDOMNode xmlNode = (IDOMNode) node;
        TLDCMDocumentManager tldmgr =
            TaglibController.getTLDCMDocumentManager(xmlNode.getStructuredDocument());
        if (tldmgr != null) {
          List documents = tldmgr.getCMDocumentTrackers(node.getPrefix(), xmlNode.getStartOffset());
          // there shouldn't be more than one cmdocument returned
          if (documents != null && documents.size() > 0) result = (CMDocument) documents.get(0);
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return result;
  }
Example #7
0
  // <foo><!--comment-->bar</foo> will put the text as a tail of the comment
  // this isn't very nice. Do we have getText too, that gets all text of foo?
  private MeiElement makeMeiElement(Node element) {
    // TODO: CDATA
    // Comments get a name #comment
    String nshref = element.getNamespaceURI();
    String nsprefix = element.getPrefix();
    MeiNamespace elns = new MeiNamespace(nshref, nsprefix);
    MeiElement e = new MeiElement(elns, element.getNodeName());
    if (element.getNodeType() == Node.COMMENT_NODE) {
      e.setValue(element.getNodeValue());
    }

    NamedNodeMap attributes = element.getAttributes();
    if (attributes != null) {
      for (int i = 0; i < attributes.getLength(); i++) {
        Node item = attributes.item(i);
        if (XML_ID_ATTRIBUTE.equals(item.getNodeName())) {
          e.setId(item.getNodeValue());
        } else {
          String attrns = item.getNamespaceURI();
          String attrpre = item.getPrefix();
          MeiNamespace atns = new MeiNamespace(attrns, attrpre);
          MeiAttribute a = new MeiAttribute(atns, item.getNodeName(), item.getNodeValue());
          e.addAttribute(a);
        }
      }
    }

    NodeList childNodes = element.getChildNodes();
    MeiElement lastElement = null;
    for (int i = 0; i < childNodes.getLength(); i++) {
      Node item = childNodes.item(i);
      if (item.getNodeType() == Node.TEXT_NODE) {
        if (lastElement == null) {
          e.setValue(item.getNodeValue());
        } else {
          lastElement.setTail(item.getNodeValue());
        }
      } else {
        MeiElement child = makeMeiElement(item);
        e.addChild(child);
        lastElement = child;
      }
    }
    return e;
  }
  @Override
  public Comparisons provideComparisons(NodeAndXpath<Node> control, NodeAndXpath<Node> test) {
    Node controlNode = control.getNode();
    Node testNode = test.getNode();

    Comparisons comparisons = new Comparisons();

    comparisons.add(
        Comparison.ofType(ComparisonType.NAMESPACE_URI)
            .between(control, controlNode.getNamespaceURI())
            .and(test, testNode.getNamespaceURI()));

    comparisons.add(
        Comparison.ofType(ComparisonType.NAMESPACE_PREFIX)
            .between(control, controlNode.getPrefix())
            .and(test, testNode.getPrefix()));

    return comparisons;
  }
  // --------------------------------------------------------------------------
  protected String getNodeNameNS(Node p_node) {
    String l_prefix = null;

    l_prefix = p_node.getPrefix();
    // System.out.println("PREFIX: " + l_prefix);
    if ((l_prefix == null) || (l_prefix.isEmpty())) {
      return p_node.getNodeName();
    }
    return p_node.getLocalName();
  }
Example #10
0
 final void setLocalName(String localName) {
   if (dom instanceof ProcessingInstruction) {
     setProcessingInstructionName(localName);
   } else {
     String prefix = dom.getPrefix();
     if (prefix == null) prefix = "";
     this.dom =
         dom.getOwnerDocument()
             .renameNode(dom, dom.getNamespaceURI(), QName.qualify(prefix, localName));
   }
 }
  private String getSAMLNSPrefix(Document samlResponseDocument) {
    Node assertionElement =
        samlResponseDocument
            .getDocumentElement()
            .getElementsByTagNameNS(
                JBossSAMLURIConstants.ASSERTION_NSURI.get(), JBossSAMLConstants.ASSERTION.get())
            .item(0);

    if (assertionElement == null) {
      throwResponseDocumentOrAssertionNotFound();
    }

    return assertionElement.getPrefix();
  }
  public String getSAMLNSPrefix(Document samlResponseDocument) {
    Node assertionElement =
        samlResponseDocument
            .getDocumentElement()
            .getElementsByTagNameNS(
                JBossSAMLURIConstants.ASSERTION_NSURI.get(), JBossSAMLConstants.ASSERTION.get())
            .item(0);

    if (assertionElement == null) {
      throw new IllegalStateException("Unable to find assertion in saml response document");
    }

    return assertionElement.getPrefix();
  }
Example #13
0
 private void resolveNamespaceIfNecessary(ThreadContext context, Node node, String default_href) {
   if (node == null) return;
   String nodePrefix = node.getPrefix();
   if (nodePrefix == null) { // default namespace
     node.getOwnerDocument().renameNode(node, default_href, node.getNodeName());
   } else {
     XmlNamespace xmlNamespace = nsCache.get(nodePrefix);
     String href = (String) xmlNamespace.href(context).toJava(String.class);
     node.getOwnerDocument().renameNode(node, href, node.getNodeName());
   }
   resolveNamespaceIfNecessary(context, node.getNextSibling(), default_href);
   NodeList children = node.getChildNodes();
   for (int i = 0; i < children.getLength(); i++) {
     resolveNamespaceIfNecessary(context, children.item(i), default_href);
   }
 }
Example #14
0
  public static Map<String, String> toMapExcept(NamedNodeMap attrs, String... exclusions) {
    Map<String, String> args = new HashMap<String, String>();
    outer:
    for (int j = 0; j < attrs.getLength(); j++) {
      Node attr = attrs.item(j);

      // automatically exclude things in the xml namespace, ie: xml:base
      if (XML_RESERVED_PREFIX.equals(attr.getPrefix())) continue outer;

      String attrName = attr.getNodeName();
      for (String ex : exclusions) if (ex.equals(attrName)) continue outer;
      String val = attr.getNodeValue();
      args.put(attrName, val);
    }
    return args;
  }
Example #15
0
  public String getNamespacePrefix(String uri) {

    NamespaceContextIterator eachNamespace = getNamespaceContextNodes();
    while (eachNamespace.hasNext()) {
      org.w3c.dom.Attr namespaceDecl = eachNamespace.nextNamespaceAttr();
      if (namespaceDecl.getNodeValue().equals(uri)) {
        String candidatePrefix = namespaceDecl.getLocalName();
        if ("xmlns".equals(candidatePrefix)) return "";
        else return candidatePrefix;
      }
    }

    // Find if any of the ancestors' name has this uri
    org.w3c.dom.Node currentAncestor = this;
    while (currentAncestor != null && !(currentAncestor instanceof Document)) {

      if (uri.equals(currentAncestor.getNamespaceURI())) return currentAncestor.getPrefix();
      currentAncestor = currentAncestor.getParentNode();
    }

    return null;
  }
Example #16
0
  protected void processNonSchemaAttributes(XSDConcreteComponent component, Node node)
      throws RepositoryException {
    if (component == null) {
      return;
    }
    Element element = component.getElement();
    if (element == null) {
      return;
    }

    NamedNodeMap attributes = element.getAttributes();
    if (attributes == null) {
      return;
    }

    for (int i = 0, len = attributes.getLength(); i != len; ++i) {
      org.w3c.dom.Node attribute = attributes.item(i);
      if (attribute.getNodeType() != org.w3c.dom.Node.ATTRIBUTE_NODE) {
        continue;
      }
      String namespaceUri = attribute.getNamespaceURI();
      if (!XsdLexicon.Namespace.URI.equals(namespaceUri)) {
        // Record any attribute that is not in the XSD namespace ...
        String localName = attribute.getLocalName();
        String value = attribute.getNodeValue();
        if (value == null) continue;
        if (namespaceUri != null) {
          NamespaceRegistry namespaceRegistry =
              node.getSession().getWorkspace().getNamespaceRegistry();
          String prefix = registerNamespace(namespaceRegistry, namespaceUri, attribute.getPrefix());
          String propertyName = prefix + ":" + localName;
          node.setProperty(propertyName, value);
        } else {
          node.setProperty(localName, value);
        }
      }
    }
  }
Example #17
0
 private void write(Writer writer, NSStack nsstack, Node node, int depth) throws IOException {
   nsstack = new NSStack(nsstack);
   if (node.getPrefix() != null) {
     String nsuri = nsstack.getNamespace(node.getPrefix());
     if (nsuri == null) {
       nsstack.addNamespace(node.getPrefix(), node.getNamespaceURI());
     }
   }
   writer.write(pad(depth));
   writer.write("<" + node.getNodeName());
   NamedNodeMap attrs = node.getAttributes();
   if (attrs != null) {
     writer.write(" ");
     //            writer.write("\n");
     for (int i = 0; i < attrs.getLength(); i++) {
       Attr attr = (Attr) attrs.item(i);
       if (attr.getPrefix() != null) {
         String nsuri = nsstack.getNamespace(attr.getPrefix());
         if (nsuri == null) {
           nsstack.addNamespace(attr.getPrefix(), attr.getNamespaceURI());
         }
       } else if (attr.getNodeName().startsWith("xmlns:")) {
         String prefix = attr.getNodeName().substring(6);
         String nsuri = attr.getNodeValue();
         nsstack.addNamespace(prefix, nsuri);
       }
       String value = attr.getValue();
       //                writer.write(pad(depth+1));
       writer.write(attr.getName() + "='" + value + "'");
       if (i < attrs.getLength()) writer.write(" ");
       //                writer.write("\n");
       if (value != null && value.indexOf(":") > -1 && value.indexOf("://") == -1) {
         String prefix = value.substring(0, value.indexOf(":"));
         String nsuri = nsstack.getNamespace(prefix);
         if (nsuri == null) {
           System.err.println("WARNING: Use of undeclared namespace prefix : " + prefix);
         }
       }
     }
     //            writer.write(pad(depth));
   }
   Map<String, String> namespaces = nsstack.getNamespaces();
   if (namespaces != null) {
     Iterator<String> nsit = namespaces.keySet().iterator();
     while (nsit.hasNext()) {
       String prefix = nsit.next();
       String nsuri = namespaces.get(prefix);
       Attr attr = (Attr) node.getAttributes().getNamedItem("xmlns:" + prefix);
       if (attr == null) {
         //                    writer.write(pad(depth+1));
         writer.write("xmlns:" + prefix + "='" + nsuri + "'");
         //                    writer.write("\n");
       }
     }
     //            writer.write(pad(depth));
   }
   writer.write(">");
   NodeList children = node.getChildNodes();
   if (children.getLength() == 1 && children.item(0).getNodeType() == Node.TEXT_NODE) {
     Node text = children.item(0);
     writer.write(text.getNodeValue());
   } else if (children.getLength() > 0) {
     writer.write("\n");
     for (int i = 0; i < children.getLength(); i++) {
       write(writer, nsstack, children.item(i), depth + 1);
     }
     writer.write(pad(depth));
   }
   writer.write("</" + node.getNodeName() + ">\n");
 }
Example #18
0
 void doApply(
     Stylesheet stylesheet,
     QName mode,
     Node context,
     int pos,
     int len,
     Node parent,
     Node nextSibling)
     throws TransformerException {
   Node result = null;
   Document doc = (parent instanceof Document) ? (Document) parent : parent.getOwnerDocument();
   short nodeType = source.getNodeType();
   if (nodeType == Node.ATTRIBUTE_NODE && parent.getFirstChild() != null) {
     // Ignore attributes added after child elements
   } else {
     // Namespace aliasing
     if (nodeType == Node.ELEMENT_NODE) {
       String prefix = source.getPrefix();
       if (prefix == null) prefix = "#default";
       String resultPrefix = (String) stylesheet.namespaceAliases.get(prefix);
       if (resultPrefix != null) {
         if ("#default".equals(resultPrefix)) resultPrefix = null;
         String uri = source.lookupNamespaceURI(resultPrefix);
         String name = source.getNodeName();
         // Create a new element node in the result document
         result = doc.createElementNS(uri, name);
         // copy attributes
         NamedNodeMap srcAttrs = source.getAttributes();
         NamedNodeMap dstAttrs = result.getAttributes();
         int l = srcAttrs.getLength();
         for (int i = 0; i < l; i++) {
           Node attr = srcAttrs.item(i);
           if (!Stylesheet.XSL_NS.equals(attr.getNamespaceURI())) {
             attr = attr.cloneNode(true);
             attr = doc.adoptNode(attr);
             dstAttrs.setNamedItemNS(attr);
           }
         }
       }
     }
     if (result == null) {
       // Create result node
       result = source.cloneNode(false);
       // Remove any XSL attributes
       NamedNodeMap attrs = result.getAttributes();
       if (attrs != null) {
         int l = attrs.getLength();
         for (int i = 0; i < l; i++) {
           Node attr = attrs.item(i);
           if (Stylesheet.XSL_NS.equals(attr.getNamespaceURI())) {
             attrs.removeNamedItem(attr.getNodeName());
             i--;
             l--;
           }
         }
       }
       Node result2 = doc.adoptNode(result);
       if (result2 == null) {
         String msg =
             "Error adopting node to result tree: "
                 + result
                 + " ("
                 + result.getClass().getName()
                 + ")";
         DOMSourceLocator l = new DOMSourceLocator(context);
         throw new TransformerException(msg, l);
       }
       result = result2;
     }
     if (nextSibling != null) parent.insertBefore(result, nextSibling);
     else parent.appendChild(result);
     if (nodeType == Node.ELEMENT_NODE)
       stylesheet.addNamespaceNodes(source, result, doc, elementExcludeResultPrefixes);
     // children
     if (children != null) children.apply(stylesheet, mode, context, pos, len, result, null);
   }
   // next sibling
   if (next != null) next.apply(stylesheet, mode, context, pos, len, parent, nextSibling);
 }
 void serialize(Node node, ContentHandler ch, LexicalHandler lh) throws SAXException {
   attrs = node.getAttributes();
   Node children;
   Node next = node.getNextSibling();
   switch (node.getNodeType()) {
     case Node.ELEMENT_NODE:
       String uri = node.getNamespaceURI();
       String prefix = node.getPrefix();
       boolean defined = isDefined(prefix, uri);
       if (!defined) {
         define(prefix, uri);
         ch.startPrefixMapping(prefix, uri);
       }
       String localName = node.getLocalName();
       String qName = node.getNodeName();
       ch.startElement(uri, localName, qName, this);
       children = node.getFirstChild();
       if (children != null) {
         serialize(children, ch, lh);
       }
       ch.endElement(uri, localName, qName);
       if (!defined) {
         ch.endPrefixMapping(prefix);
         undefine(prefix, uri);
       }
       break;
     case Node.TEXT_NODE:
       char[] chars = node.getNodeValue().toCharArray();
       ch.characters(chars, 0, chars.length);
       break;
     case Node.CDATA_SECTION_NODE:
       char[] cdata = node.getNodeValue().toCharArray();
       if (lh != null) {
         lh.startCDATA();
         ch.characters(cdata, 0, cdata.length);
         lh.endCDATA();
       } else {
         ch.characters(cdata, 0, cdata.length);
       }
       break;
     case Node.COMMENT_NODE:
       if (lh != null) {
         char[] comment = node.getNodeValue().toCharArray();
         lh.comment(comment, 0, comment.length);
       }
       break;
     case Node.DOCUMENT_NODE:
     case Node.DOCUMENT_FRAGMENT_NODE:
       ch.startDocument();
       children = node.getFirstChild();
       if (children != null) {
         serialize(children, ch, lh);
       }
       ch.endDocument();
       break;
     case Node.DOCUMENT_TYPE_NODE:
       if (lh != null) {
         DocumentType doctype = (DocumentType) node;
         String publicId = doctype.getPublicId();
         String systemId = doctype.getSystemId();
         lh.startDTD(node.getNodeName(), publicId, systemId);
         NamedNodeMap entities = doctype.getEntities();
         int len = entities.getLength();
         for (int i = 0; i < len; i++) {
           Node entity = entities.item(i);
           String entityName = entity.getNodeName();
           lh.startEntity(entityName);
           lh.endEntity(entityName);
         }
         lh.endDTD();
       }
       break;
     case Node.PROCESSING_INSTRUCTION_NODE:
       ch.processingInstruction(node.getNodeName(), node.getNodeValue());
       break;
     case Node.ENTITY_REFERENCE_NODE:
       ch.skippedEntity(node.getNodeName());
       break;
   }
   attrs = null;
   if (next != null) {
     serialize(next, ch, lh);
   }
 }
  /**
   * DOM Level 3: Check a node to determine if it contains unbound namespace prefixes.
   *
   * @param node The node to check for unbound namespace prefices
   */
  protected void checkUnboundNamespacePrefixedNode(Node node) throws IOException {

    if (fNamespaces) {

      if (DEBUG) {
        System.out.println(
            "==>serializeNode(" + node.getNodeName() + ") [Entity Reference - Namespaces on]");
        System.out.println("==>Declared Prefix Count: " + fNSBinder.getDeclaredPrefixCount());
        System.out.println("==>Node Name: " + node.getNodeName());
        System.out.println("==>First Child Node Name: " + node.getFirstChild().getNodeName());
        System.out.println("==>First Child Node Prefix: " + node.getFirstChild().getPrefix());
        System.out.println(
            "==>First Child Node NamespaceURI: " + node.getFirstChild().getNamespaceURI());
      }

      Node child, next;
      for (child = node.getFirstChild(); child != null; child = next) {
        next = child.getNextSibling();
        if (DEBUG) {
          System.out.println("==>serializeNode(" + child.getNodeName() + ") [Child Node]");
          System.out.println("==>serializeNode(" + child.getPrefix() + ") [Child Node Prefix]");
        }

        // If a NamespaceURI is not declared for the current
        // node's prefix, raise a fatal error.
        String prefix = child.getPrefix();
        prefix =
            (prefix == null || prefix.length() == 0)
                ? XMLSymbols.EMPTY_STRING
                : fSymbolTable.addSymbol(prefix);
        if (fNSBinder.getURI(prefix) == null && prefix != null) {
          fatalError(
              "The replacement text of the entity node '"
                  + node.getNodeName()
                  + "' contains an element node '"
                  + child.getNodeName()
                  + "' with an undeclared prefix '"
                  + prefix
                  + "'.");
        }

        if (child.getNodeType() == Node.ELEMENT_NODE) {

          NamedNodeMap attrs = child.getAttributes();

          for (int i = 0; i < attrs.getLength(); i++) {

            String attrPrefix = attrs.item(i).getPrefix();
            attrPrefix =
                (attrPrefix == null || attrPrefix.length() == 0)
                    ? XMLSymbols.EMPTY_STRING
                    : fSymbolTable.addSymbol(attrPrefix);
            if (fNSBinder.getURI(attrPrefix) == null && attrPrefix != null) {
              fatalError(
                  "The replacement text of the entity node '"
                      + node.getNodeName()
                      + "' contains an element node '"
                      + child.getNodeName()
                      + "' with an attribute '"
                      + attrs.item(i).getNodeName()
                      + "' an undeclared prefix '"
                      + attrPrefix
                      + "'.");
            }
          }
        }

        if (child.hasChildNodes()) {
          checkUnboundNamespacePrefixedNode(child);
        }
      }
    }
  }
 protected String getUnprefixedNodeName(Node node) {
   return node.getPrefix() != null
       ? node.getNodeName().substring(node.getPrefix().length() + 1)
       : node.getNodeName();
 }
  /** @see org.w3c.dom.Node#getLocalName() */
  public String getLocalName() {

    // For namespace node, the local name is the same as the prefix
    return m_attributeNode.getPrefix();
  }
 /** @see org.w3c.dom.Node#getPrefix() */
 public String getPrefix() {
   return m_attributeNode.getPrefix();
 }
Example #24
0
 private void printNode(Node node) {
   System.out.println("NamespaceURI: " + node.getNamespaceURI());
   System.out.println("LocalName: " + node.getLocalName());
   System.out.println("Prefix: " + node.getPrefix());
   System.out.println("NodeName: " + node.getNodeName());
 }
Example #25
0
 final QName getQname() {
   String uri = (dom.getNamespaceURI()) == null ? "" : dom.getNamespaceURI();
   String prefix = (dom.getPrefix() == null) ? "" : dom.getPrefix();
   return QName.create(uri, dom.getLocalName(), prefix);
 }
  protected static String nodeToString(Node node, Set<String> parentPrefixes, String namespaceURI)
      throws Exception {
    StringBuilder b = new StringBuilder();

    if (node == null) {
      return "";
    }

    if (node instanceof Element) {
      Element element = (Element) node;
      b.append("<");
      b.append(element.getNodeName());

      Map<String, String> thisLevelPrefixes = new HashMap<>();
      if (element.getPrefix() != null && !parentPrefixes.contains(element.getPrefix())) {
        thisLevelPrefixes.put(element.getPrefix(), element.getNamespaceURI());
      }

      if (element.hasAttributes()) {
        NamedNodeMap map = element.getAttributes();
        for (int i = 0; i < map.getLength(); i++) {
          Node attr = map.item(i);
          if (attr.getNodeName().startsWith("xmlns")) continue;
          if (attr.getPrefix() != null && !parentPrefixes.contains(attr.getPrefix())) {
            thisLevelPrefixes.put(attr.getPrefix(), element.getNamespaceURI());
          }
          b.append(" ");
          b.append(attr.getNodeName());
          b.append("=\"");
          b.append(attr.getNodeValue());
          b.append("\"");
        }
      }

      if (namespaceURI != null
          && !thisLevelPrefixes.containsValue(namespaceURI)
          && !namespaceURI.equals(element.getParentNode().getNamespaceURI())) {
        b.append(" xmlns=\"").append(namespaceURI).append("\"");
      }

      for (Map.Entry<String, String> entry : thisLevelPrefixes.entrySet()) {
        b.append(" xmlns:")
            .append(entry.getKey())
            .append("=\"")
            .append(entry.getValue())
            .append("\"");
        parentPrefixes.add(entry.getKey());
      }

      NodeList children = element.getChildNodes();
      boolean hasOnlyAttributes = true;
      for (int i = 0; i < children.getLength(); i++) {
        Node child = children.item(i);
        if (child.getNodeType() != Node.ATTRIBUTE_NODE) {
          hasOnlyAttributes = false;
          break;
        }
      }
      if (!hasOnlyAttributes) {
        b.append(">");
        for (int i = 0; i < children.getLength(); i++) {
          b.append(
              nodeToString(children.item(i), parentPrefixes, children.item(i).getNamespaceURI()));
        }
        b.append("</");
        b.append(element.getNodeName());
        b.append(">");
      } else {
        b.append("/>");
      }

      for (String thisLevelPrefix : thisLevelPrefixes.keySet()) {
        parentPrefixes.remove(thisLevelPrefix);
      }

    } else if (node.getNodeValue() != null) {
      b.append(encodeText(node.getNodeValue(), node instanceof Attr));
    }

    return b.toString();
  }
Example #27
0
 Namespace getNamespaceDeclaration() {
   if (dom.getPrefix() == null) return getNamespaceDeclaration("");
   return getNamespaceDeclaration(dom.getPrefix());
 }
Example #28
0
  /**
   * returns a property from a XMl Node
   *
   * @param node
   * @param key
   * @param caseSensitive
   * @return Object matching key
   * @throws SAXException
   */
  public static Object getProperty(Node node, Collection.Key k, boolean caseSensitive)
      throws SAXException {
    // String lcKey=StringUtil.toLowerCase(key);
    if (k.getLowerString().startsWith("xml")) {
      // Comment
      if (k.equals(XMLCOMMENT)) {
        StringBuffer sb = new StringBuffer();
        NodeList list = node.getChildNodes();
        int len = list.getLength();
        for (int i = 0; i < len; i++) {
          Node n = list.item(i);
          if (n instanceof Comment) {
            sb.append(((Comment) n).getData());
          }
        }
        return sb.toString();
      }
      // NS URI
      if (k.equals(XMLNSURI)) {
        undefinedInRoot(k, node);
        return param(node.getNamespaceURI(), "");
      }
      // Prefix
      if (k.equals(XMLNSPREFIX)) {
        undefinedInRoot(k, node);
        return param(node.getPrefix(), "");
      }
      // Root
      else if (k.equals(XMLROOT)) {
        Element re = getRootElement(node, caseSensitive);
        if (re == null)
          throw new SAXException(
              "Attribute [" + k.getString() + "] not found in XML, XML is empty");
        return param(re, "");
      }
      // Parent
      else if (k.equals(XMLPARENT)) {

        Node parent = getParentNode(node, caseSensitive);
        if (parent == null) {
          if (node.getNodeType() == Node.DOCUMENT_NODE)
            throw new SAXException(
                "Attribute ["
                    + k.getString()
                    + "] not found in XML, there is no parent element, you are already at the root element");
          throw new SAXException(
              "Attribute [" + k.getString() + "] not found in XML, there is no parent element");
        }
        return parent;
      }
      // Name
      else if (k.equals(XMLNAME)) {
        return node.getNodeName();
      }
      // Value
      else if (k.equals(XMLVALUE)) {
        return StringUtil.toStringEmptyIfNull(node.getNodeValue());
      }
      // type
      else if (k.equals(XMLTYPE)) {
        return getTypeAsString(node, true);
      }
      // Attributes
      else if (k.equals(XMLATTRIBUTES)) {
        NamedNodeMap attr = node.getAttributes();

        if (attr == null) throw undefined(k, node);
        return new XMLAttributes(node.getOwnerDocument(), attr, caseSensitive);
      }
      // Text
      else if (k.equals(XMLTEXT)) {
        undefinedInRoot(k, node);
        StringBuffer sb = new StringBuffer();
        NodeList list = node.getChildNodes();
        int len = list.getLength();
        for (int i = 0; i < len; i++) {
          Node n = list.item(i);
          if (n instanceof Text || n instanceof CDATASection) {
            sb.append(((CharacterData) n).getData());
          }
        }
        return sb.toString();
      } else if (k.equals(XMLCDATA)) {
        undefinedInRoot(k, node);
        StringBuffer sb = new StringBuffer();
        NodeList list = node.getChildNodes();
        int len = list.getLength();
        for (int i = 0; i < len; i++) {
          Node n = list.item(i);
          if (n instanceof Text || n instanceof CDATASection) {
            sb.append(((CharacterData) n).getData());
          }
        }
        return sb.toString();
      }
      // children
      else if (k.equals(XMLCHILDREN)) {
        return new XMLNodeList(node, caseSensitive);
      }
    }

    if (node instanceof Document) {
      node = ((Document) node).getDocumentElement();
      if (node == null)
        throw new SAXException("Attribute [" + k.getString() + "] not found in XML, XML is empty");

      // if((!caseSensitive && node.getNodeName().equalsIgnoreCase(k.getString())) || (caseSensitive
      // && node.getNodeName().equals(k.getString()))) {
      if (nameEqual(node, k.getString(), caseSensitive)) {
        return XMLStructFactory.newInstance(node, caseSensitive);
      }
    } else if (node.getNodeType() == Node.ELEMENT_NODE && Decision.isInteger(k)) {
      int index = Caster.toIntValue(k, 0);
      int count = 0;
      Node parent = node.getParentNode();
      String nodeName = node.getNodeName();
      Element[] children = XMLUtil.getChildElementsAsArray(parent);

      for (int i = 0; i < children.length; i++) {
        if (XMLUtil.nameEqual(children[i], nodeName, caseSensitive)) count++;

        if (count == index) return XMLCaster.toXMLStruct(children[i], caseSensitive);
      }
      String detail;
      if (count == 0) detail = "there are no Elements with this name";
      else if (count == 1) detail = "there is only 1 Element with this name";
      else detail = "there are only " + count + " Elements with this name";
      throw new SAXException(
          "invalid index ["
              + k.getString()
              + "] for Element with name ["
              + node.getNodeName()
              + "], "
              + detail);
    } else {
      List<Node> children =
          XMLUtil.getChildNodesAsList(node, Node.ELEMENT_NODE, caseSensitive, null);
      int len = children.size();
      Array array = null; // new ArrayImpl();
      Element el;
      XMLStruct sct = null, first = null;
      for (int i = 0; i < len; i++) {
        el = (Element) children.get(i); // XMLCaster.toXMLStruct(getChildNode(index),caseSensitive);
        if (XMLUtil.nameEqual(el, k.getString(), caseSensitive)) {
          sct = XMLCaster.toXMLStruct(el, caseSensitive);

          if (array != null) {
            array.appendEL(sct);
          } else if (first != null) {
            array = new ArrayImpl();
            array.appendEL(first);
            array.appendEL(sct);
          } else {
            first = sct;
          }
        }
      }

      if (array != null) {
        try {
          return new XMLMultiElementStruct(array, false);
        } catch (PageException e) {
        }
      }
      if (first != null) return first;
    }
    throw new SAXException("Attribute [" + k.getString() + "] not found");
  }