コード例 #1
0
  public void testWrite() throws Exception {
    Car car = new Car();
    car.numberOfDoors = 2;
    car.milesPerGallon = 30;
    car.model = "Grand Am";
    car.manufacturer = "Pontiac";
    car.topSpeed = 220;

    Document carDocument = marshaller.objectToXML(car);
    Element root =
        (Element) carDocument.getElementsByTagNameNS("mynamespaceuri", "vehicle").item(0);
    Attr elem = root.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "type");
    String carType = elem.getNodeValue();
    assertTrue(
        "The type field was written incorrectly for the subclass",
        carType.equals("prefix:car-type"));

    Vehicle vehicle = new Vehicle();
    vehicle.model = "Blah Blah";
    vehicle.manufacturer = "Some Place";
    vehicle.topSpeed = 10000;

    Document vehicleDocument = marshaller.objectToXML(vehicle);
    root = (Element) vehicleDocument.getElementsByTagNameNS("mynamespaceuri", "vehicle").item(0);
    elem = root.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "type");
    String vehicleType = elem.getNodeValue();
    assertTrue(
        "The type field was written incorrectly for the superclass",
        vehicleType.equals("prefix:vehicle-type"));
  }
コード例 #2
0
  @Override
  public void visitElement(@NonNull XmlContext context, @NonNull Element element) {
    int declaredRowCount = getInt(element, ATTR_ROW_COUNT, -1);
    int declaredColumnCount = getInt(element, ATTR_COLUMN_COUNT, -1);

    if (declaredColumnCount != -1 || declaredRowCount != -1) {
      for (Element child : LintUtils.getChildren(element)) {
        if (declaredColumnCount != -1) {
          int column = getInt(child, ATTR_LAYOUT_COLUMN, -1);
          if (column >= declaredColumnCount) {
            Attr node = child.getAttributeNodeNS(ANDROID_URI, ATTR_LAYOUT_COLUMN);
            context.report(
                ISSUE,
                node,
                context.getLocation(node),
                String.format(
                    "Column attribute (%1$d) exceeds declared grid column count (%2$d)",
                    column, declaredColumnCount));
          }
        }
        if (declaredRowCount != -1) {
          int row = getInt(child, ATTR_LAYOUT_ROW, -1);
          if (row > declaredRowCount) {
            Attr node = child.getAttributeNodeNS(ANDROID_URI, ATTR_LAYOUT_ROW);
            context.report(
                ISSUE,
                node,
                context.getLocation(node),
                String.format(
                    "Row attribute (%1$d) exceeds declared grid row count (%2$d)",
                    row, declaredRowCount));
          }
        }
      }
    }

    if (element.getTagName().equals(FQCN_GRID_LAYOUT_V7)) {
      // Make sure that we're not using android: namespace attributes where we should
      // be using app namespace attributes!
      ensureAppNamespace(context, element, ATTR_COLUMN_COUNT);
      ensureAppNamespace(context, element, ATTR_ORIENTATION);
      ensureAppNamespace(context, element, ATTR_ROW_COUNT);
      ensureAppNamespace(context, element, ATTR_USE_DEFAULT_MARGINS);
      ensureAppNamespace(context, element, "alignmentMode");
      ensureAppNamespace(context, element, "columnOrderPreserved");
      ensureAppNamespace(context, element, "rowOrderPreserved");

      for (Element child : LintUtils.getChildren(element)) {
        ensureAppNamespace(context, child, ATTR_LAYOUT_COLUMN);
        ensureAppNamespace(context, child, ATTR_LAYOUT_COLUMN_SPAN);
        ensureAppNamespace(context, child, ATTR_LAYOUT_GRAVITY);
        ensureAppNamespace(context, child, ATTR_LAYOUT_ROW);
        ensureAppNamespace(context, child, ATTR_LAYOUT_ROW_SPAN);
      }
    }
  }
コード例 #3
0
  private void addLayoutReplacements(
      @NonNull List<TextEdit> edits,
      @NonNull Element element,
      @NonNull IStructuredDocument document) {
    String tag = element.getTagName();
    if (tag.equals(mOldFqcn)) {
      int start = RefactoringUtil.getTagNameRangeStart(element, document);
      if (start != -1) {
        int end = start + mOldFqcn.length();
        edits.add(new ReplaceEdit(start, end - start, mNewFqcn));
      }
    } else if (tag.equals(VIEW_TAG)) {
      Attr classNode = element.getAttributeNode(ATTR_CLASS);
      if (classNode != null && classNode.getValue().equals(mOldFqcn)) {
        int start = RefactoringUtil.getAttributeValueRangeStart(classNode, document);
        if (start != -1) {
          int end = start + mOldFqcn.length();
          edits.add(new ReplaceEdit(start, end - start, mNewFqcn));
        }
      }
    } else if (tag.equals(VIEW_FRAGMENT)) {
      Attr classNode = element.getAttributeNode(ATTR_CLASS);
      if (classNode == null) {
        classNode = element.getAttributeNodeNS(ANDROID_URI, ATTR_NAME);
      }
      if (classNode != null && classNode.getValue().equals(mOldFqcn)) {
        int start = RefactoringUtil.getAttributeValueRangeStart(classNode, document);
        if (start != -1) {
          int end = start + mOldFqcn.length();
          edits.add(new ReplaceEdit(start, end - start, mNewFqcn));
        }
      }
    } else if (element.hasAttributeNS(TOOLS_URI, ATTR_CONTEXT)) {
      Attr classNode = element.getAttributeNodeNS(TOOLS_URI, ATTR_CONTEXT);
      if (classNode != null && classNode.getValue().equals(mOldFqcn)) {
        int start = RefactoringUtil.getAttributeValueRangeStart(classNode, document);
        if (start != -1) {
          int end = start + mOldFqcn.length();
          edits.add(new ReplaceEdit(start, end - start, mNewFqcn));
        }
      }
    }

    NodeList children = element.getChildNodes();
    for (int i = 0, n = children.getLength(); i < n; i++) {
      Node child = children.item(i);
      if (child.getNodeType() == Node.ELEMENT_NODE) {
        addLayoutReplacements(edits, (Element) child, document);
      }
    }
  }
コード例 #4
0
 /**
  * Crée l'élément DOM correspondant à l'affichage, si nécessaire en créant l'élément DOM parent.
  */
 private void creerNoeud(final MyCompoundEdit cedit) {
   if (attribut) {
     Element elparent = (Element) affParent.getNoeud();
     if (elparent == null) {
       affParent.creerNoeud(cedit);
       elparent = (Element) affParent.getNoeud();
     }
     final String nom = cfg.nomAttribut(refNoeud);
     final String espace = cfg.espaceAttribut(refNoeud);
     elparent.setAttributeNS(espace, nom, "");
     noeud = elparent.getAttributeNodeNS(espace, nom);
     cedit.addEdit(new FormUndoableEdit(FormUndoableEdit.TypeEdition.AJOUTER, this));
   } else {
     noeud = JaxeElement.nouvelElementDOM(doc, refNoeud);
     Element elparent = (Element) affParent.getNoeud();
     if (elparent == null) {
       affParent.creerNoeud(cedit);
       elparent = (Element) affParent.getNoeud();
       elparent.appendChild(noeud.getOwnerDocument().createTextNode("\n"));
     }
     final Element suivant = affParent.trouverSuivant(refNoeud);
     final Node textnode = noeud.getOwnerDocument().createTextNode("\n");
     if (suivant == null) {
       elparent.appendChild(noeud);
       elparent.appendChild(textnode);
     } else {
       elparent.insertBefore(noeud, suivant);
       elparent.insertBefore(textnode, suivant);
     }
     cedit.addEdit(new FormUndoableEdit(FormUndoableEdit.TypeEdition.AJOUTER, this));
   }
   affParent.lireEnfants();
   doc.textPane.miseAJourArbre();
 }
コード例 #5
0
  /**
   * @param containingHtmlElement the name of the HTML element containing el. If the HTML element is
   *     contained inside a template construct then this name may differ from el's immediate parent.
   */
  private void inspectElement(JobEnvelope source, Element el, ElKey containingHtmlElement) {
    ElKey elKey = ElKey.forElement(el);

    // Recurse early so that ihtml:dynamic elements have been parsed before we
    // process the attributes element list.
    for (Node child : Nodes.childrenOf(el)) {
      inspect(source, child, elKey);
    }

    // For each attribute allowed on this element type, ensure that
    // (1) If it is not specified, and its default value is not allowed, then
    //     it is added with a known safe value.
    // (2) Its value is rewritten as appropriate.
    // We don't have to worry about disallowed attributes since those will
    // not be present in scriptsPerNode.  The TemplateSanitizer should have
    // stripped those out.  The TemplateSanitizer should also have stripped out
    // disallowed elements.
    if (!htmlSchema.isElementAllowed(elKey)) {
      return;
    }

    HTML.Element elInfo = htmlSchema.lookupElement(elKey);
    List<HTML.Attribute> attrs = elInfo.getAttributes();
    if (attrs != null) {
      for (HTML.Attribute a : attrs) {
        AttribKey attrKey = a.getKey();
        if (!htmlSchema.isAttributeAllowed(attrKey)) {
          continue;
        }
        Attr attr = null;
        String aUri = attrKey.ns.uri;
        String aName = attrKey.localName;
        Attr unsafe = el.getAttributeNodeNS(aUri, aName);
        if (unsafe != null && a.getValueCriterion().accept(unsafe.getValue())) {
          attr = unsafe;
        } else if ((a.getDefaultValue() != null
                && !a.getValueCriterion().accept(a.getDefaultValue()))
            || !a.isOptional()) {
          attr = el.getOwnerDocument().createAttributeNS(aUri, aName);
          String safeValue;
          if (a.getType() == HTML.Attribute.Type.URI) {
            safeValue = "" + Nodes.getFilePositionFor(el).source().getUri();
          } else {
            safeValue = a.getSafeValue();
          }
          if (safeValue == null) {
            mq.addMessage(
                IhtmlMessageType.MISSING_ATTRIB, Nodes.getFilePositionFor(el), elKey, attrKey);
            continue;
          }
          attr.setNodeValue(safeValue);
          el.setAttributeNodeNS(attr);
        }
        if (attr != null) {
          inspectHtmlAttribute(source, attr, a);
        }
      }
    }
    scriptsPerNode.put(el, null);
  }
コード例 #6
0
ファイル: KeyInfo.java プロジェクト: ronshapiro/j86
  /**
   * Constructor KeyInfo
   *
   * @param element
   * @param baseURI
   * @throws XMLSecurityException
   */
  public KeyInfo(Element element, String baseURI) throws XMLSecurityException {
    super(element, baseURI);

    Attr attr = element.getAttributeNodeNS(null, "Id");
    if (attr != null) {
      element.setIdAttributeNode(attr, true);
    }
  }
コード例 #7
0
ファイル: XMLUtils.java プロジェクト: lisuxuan1993/jdk7
  /**
   * This method spreads all namespace attributes in a DOM document to their children. This is
   * needed because the XML Signature XPath transform must evaluate the XPath against all nodes in
   * the input, even against XPath namespace nodes. Through a bug in XalanJ2, the namespace nodes
   * are not fully visible in the Xalan XPath model, so we have to do this by hand in DOM spaces so
   * that the nodes become visible in XPath space.
   *
   * @param doc
   * @see <A HREF="http://nagoya.apache.org/bugzilla/show_bug.cgi?id=2650">Namespace axis resolution
   *     is not XPath compliant </A>
   */
  public static void circumventBug2650(Document doc) {

    Element documentElement = doc.getDocumentElement();

    // if the document element has no xmlns definition, we add xmlns=""
    Attr xmlnsAttr = documentElement.getAttributeNodeNS(Constants.NamespaceSpecNS, "xmlns");

    if (xmlnsAttr == null) {
      documentElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns", "");
    }

    XMLUtils.circumventBug2650internal(doc);
  }
コード例 #8
0
 @Test
 public void testSampleAssertion() throws Exception {
   Element issuedAssertion = this.readDocument("/saml.xml").getDocumentElement();
   String assertionId = issuedAssertion.getAttributeNodeNS(null, "ID").getNodeValue();
   SecurityToken token = new SecurityToken(assertionId, issuedAssertion, null);
   SecurityAssertionImpl assertion = new SecurityAssertionImpl(token);
   assertNotNull(assertion.getSecurityToken());
   assertEquals(token, assertion.getSecurityToken());
   assertEquals(ISSUER, assertion.getIssuer());
   assertEquals(PRINCIPAL, assertion.getPrincipal().getName());
   assertEquals(PRINCIPAL, assertion.getPrincipal().toString());
   assertEquals(NUM_ATTRIBUTES, assertion.getAttributeStatements().size());
   assertEquals(NUM_NAUTH, assertion.getAuthnStatements().size());
   // we don't currently parse these
   //        assertEquals(NUM_AUTHZ, assertion.getAuthzDecisionStatements().size());
   assertNotNull(assertion.toString());
 }
コード例 #9
0
  public void marshal(Node parent, String dsPrefix, DOMCryptoContext context)
      throws MarshalException {
    if (log.isLoggable(Level.FINE)) {
      log.log(Level.FINE, "Marshalling Reference");
    }
    Document ownerDoc = DOMUtils.getOwnerDocument(parent);

    refElem = DOMUtils.createElement(ownerDoc, "Reference", XMLSignature.XMLNS, dsPrefix);

    // set attributes
    DOMUtils.setAttributeID(refElem, "Id", id);
    DOMUtils.setAttribute(refElem, "URI", uri);
    DOMUtils.setAttribute(refElem, "Type", type);

    // create and append Transforms element
    if (!transforms.isEmpty() || !appliedTransforms.isEmpty()) {
      Element transformsElem =
          DOMUtils.createElement(ownerDoc, "Transforms", XMLSignature.XMLNS, dsPrefix);
      refElem.appendChild(transformsElem);
      for (int i = 0, size = appliedTransforms.size(); i < size; i++) {
        DOMStructure transform = (DOMStructure) appliedTransforms.get(i);
        transform.marshal(transformsElem, dsPrefix, context);
      }
      for (int i = 0, size = transforms.size(); i < size; i++) {
        DOMStructure transform = (DOMStructure) transforms.get(i);
        transform.marshal(transformsElem, dsPrefix, context);
      }
    }

    // create and append DigestMethod element
    ((DOMDigestMethod) digestMethod).marshal(refElem, dsPrefix, context);

    // create and append DigestValue element
    if (log.isLoggable(Level.FINE)) {
      log.log(Level.FINE, "Adding digestValueElem");
    }
    Element digestValueElem =
        DOMUtils.createElement(ownerDoc, "DigestValue", XMLSignature.XMLNS, dsPrefix);
    if (digestValue != null) {
      digestValueElem.appendChild(ownerDoc.createTextNode(Base64.encode(digestValue)));
    }
    refElem.appendChild(digestValueElem);

    parent.appendChild(refElem);
    here = refElem.getAttributeNodeNS(null, "URI");
  }
コード例 #10
0
  @Test
  public void abuseWeaknessWithNamespaceIdTest() throws Exception {

    SoapTestDocument soap = new SoapTestDocument();
    Document doc = soap.getDocument();

    Element signed = soap.getDummyPayloadBody();
    String id = soap.getDummyPayloadBodyWsuId();

    Element payload = (Element) signed.cloneNode(true);

    soap.getHeader().appendChild(payload);

    String xpath = "/soapenv:Envelope//*[@wsu:Id='" + id + "']";
    log.info("Using XPath: " + xpath);
    AbsoluteLocationPath abs = new AbsoluteLocationPath(xpath);
    Step step = abs.getRelativeLocationPaths().get(2);

    XPathAttributeWeaknessPostProcess aw = new XPathAttributeWeaknessPostProcess(step);

    assertEquals(3, aw.getNumberOfPossibilities());

    Attr sa, pa;

    aw.abuseWeakness(0, new SignedElement(signed, null), new PayloadElement(payload, null));
    log.info("abuseWeakness(0, signed, payload)\n" + domToString(doc, true));
    sa = signed.getAttributeNodeNS(URI_NS_WSU, "Id");
    pa = payload.getAttributeNodeNS(URI_NS_WSU, "Id");
    assertNotNull(sa);
    assertNotNull(pa);
    assertEquals(sa.getTextContent(), id);
    assertFalse(pa.getTextContent().isEmpty());
    assertFalse(pa.getTextContent().equals(id));
    assertFalse(sa.getTextContent().equals(pa.getTextContent()));

    aw.abuseWeakness(2, new SignedElement(signed, null), new PayloadElement(payload, null));
    log.info("abuseWeakness(2, signed, payload)\n" + domToString(doc, true));
    sa = signed.getAttributeNodeNS(URI_NS_WSU, "Id");
    pa = payload.getAttributeNodeNS(URI_NS_WSU, "Id");
    assertNotNull(sa);
    assertNotNull(pa);
    assertEquals(sa.getTextContent(), id);
    assertFalse(pa.getTextContent().isEmpty());
    assertEquals(sa.getTextContent(), pa.getTextContent());

    aw.abuseWeakness(1, new SignedElement(signed, null), new PayloadElement(payload, null));
    log.info("abuseWeakness(1, signed, payload)\n" + domToString(doc, true));
    sa = signed.getAttributeNodeNS(URI_NS_WSU, "Id");
    pa = payload.getAttributeNodeNS(URI_NS_WSU, "Id");
    assertNotNull(sa);
    assertNull(pa);
    assertEquals(sa.getTextContent(), id);
  }
コード例 #11
0
 private static void secureLoadElement(Element element) throws RSSManagerException {
   Attr secureAttr =
       element.getAttributeNodeNS(
           RSSManagerConstants.SecureValueProperties.SECURE_VAULT_NS,
           RSSManagerConstants.SecureValueProperties.SECRET_ALIAS_ATTRIBUTE_NAME_WITH_NAMESPACE);
   if (secureAttr != null) {
     element.setTextContent(RSSManagerUtil.loadFromSecureVault(secureAttr.getValue()));
     element.removeAttributeNode(secureAttr);
   }
   NodeList childNodes = element.getChildNodes();
   int count = childNodes.getLength();
   Node tmpNode;
   for (int i = 0; i < count; i++) {
     tmpNode = childNodes.item(i);
     if (tmpNode instanceof Element) {
       secureLoadElement((Element) tmpNode);
     }
   }
 }
コード例 #12
0
  /**
   * Creates a <code>DOMReference</code> from an element.
   *
   * @param refElem a Reference element
   */
  public DOMReference(Element refElem, XMLCryptoContext context) throws MarshalException {
    // unmarshal Transforms, if specified
    Element nextSibling = DOMUtils.getFirstChildElement(refElem);
    List transforms = new ArrayList(5);
    if (nextSibling.getLocalName().equals("Transforms")) {
      Element transformElem = DOMUtils.getFirstChildElement(nextSibling);
      while (transformElem != null) {
        transforms.add(new DOMTransform(transformElem, context));
        transformElem = DOMUtils.getNextSiblingElement(transformElem);
      }
      nextSibling = DOMUtils.getNextSiblingElement(nextSibling);
    }

    // unmarshal DigestMethod
    Element dmElem = nextSibling;
    this.digestMethod = DOMDigestMethod.unmarshal(dmElem);

    // unmarshal DigestValue
    try {
      Element dvElem = DOMUtils.getNextSiblingElement(dmElem);
      this.digestValue = Base64.decode(dvElem);
    } catch (Base64DecodingException bde) {
      throw new MarshalException(bde);
    }

    // unmarshal attributes
    this.uri = DOMUtils.getAttributeValue(refElem, "URI");
    this.id = DOMUtils.getAttributeValue(refElem, "Id");

    this.type = DOMUtils.getAttributeValue(refElem, "Type");
    this.here = refElem.getAttributeNodeNS(null, "URI");
    this.refElem = refElem;

    if (transforms.isEmpty()) {
      this.transforms = Collections.EMPTY_LIST;
    } else {
      this.transforms = Collections.unmodifiableList(transforms);
    }
    this.appliedTransforms = Collections.EMPTY_LIST;
    this.allTransforms = transforms;
    this.appliedTransformData = null;
  }
コード例 #13
0
  /**
   * Creates an <code>XMLObject</code> from an element.
   *
   * @param objElem an Object element
   * @throws MarshalException if there is an error when unmarshalling
   */
  public DOMXMLObject(Element objElem, XMLCryptoContext context, Provider provider)
      throws MarshalException {
    // unmarshal attributes
    this.encoding = DOMUtils.getAttributeValue(objElem, "Encoding");

    Attr attr = objElem.getAttributeNodeNS(null, "Id");
    if (attr != null) {
      this.id = attr.getValue();
      objElem.setIdAttributeNode(attr, true);
    } else {
      this.id = null;
    }
    this.mimeType = DOMUtils.getAttributeValue(objElem, "MimeType");

    NodeList nodes = objElem.getChildNodes();
    int length = nodes.getLength();
    List content = new ArrayList(length);
    for (int i = 0; i < length; i++) {
      Node child = nodes.item(i);
      if (child.getNodeType() == Node.ELEMENT_NODE) {
        Element childElem = (Element) child;
        String tag = childElem.getLocalName();
        if (tag.equals("Manifest")) {
          content.add(new DOMManifest(childElem, context, provider));
          continue;
        } else if (tag.equals("SignatureProperties")) {
          content.add(new DOMSignatureProperties(childElem));
          continue;
        } else if (tag.equals("X509Data")) {
          content.add(new DOMX509Data(childElem));
          continue;
        }
        // @@@FIXME: check for other dsig structures
      }
      content.add(new javax.xml.crypto.dom.DOMStructure(child));
    }
    if (content.isEmpty()) {
      this.content = Collections.EMPTY_LIST;
    } else {
      this.content = Collections.unmodifiableList(content);
    }
  }
コード例 #14
0
  private static void ensureAppNamespace(XmlContext context, Element element, String name) {
    Attr attribute = element.getAttributeNodeNS(ANDROID_URI, name);
    if (attribute != null) {
      String prefix = getNamespacePrefix(element.getOwnerDocument(), AUTO_URI);
      boolean haveNamespace = prefix != null;
      if (!haveNamespace) {
        prefix = "app";
      }

      StringBuilder sb = new StringBuilder();
      sb.append("Wrong namespace; with v7 `GridLayout` you should use ")
          .append(prefix)
          .append(":")
          .append(name);
      if (!haveNamespace) {
        sb.append(" (and add `xmlns:app=\"").append(AUTO_URI).append("\"` to your root element.)");
      }
      String message = sb.toString();

      context.report(ISSUE, attribute, context.getLocation(attribute), message);
    }
  }
コード例 #15
0
  /**
   * Returns the Attr[]s to be outputted for the given element. <br>
   * IMPORTANT: This method expects to work on a modified DOM tree, i.e. a DOM which has been
   * prepared using {@link
   * com.sun.org.apache.xml.internal.security.utils.XMLUtils#circumventBug2650(
   * org.w3c.dom.Document)}.
   *
   * @param E
   * @param ns
   * @return the Attr[]s to be outputted
   * @throws CanonicalizationException
   */
  Iterator handleAttributes(Element E, NameSpaceSymbTable ns) throws CanonicalizationException {
    // result will contain the attrs which have to be outputted
    xmlattrStack.push(ns.getLevel());
    boolean isRealVisible = isVisibleDO(E, ns.getLevel()) == 1;
    NamedNodeMap attrs = null;
    int attrsLength = 0;
    if (E.hasAttributes()) {
      attrs = E.getAttributes();
      attrsLength = attrs.getLength();
    }

    SortedSet result = this.result;
    result.clear();

    for (int i = 0; i < attrsLength; i++) {
      Attr N = (Attr) attrs.item(i);
      String NUri = N.getNamespaceURI();

      if (XMLNS_URI != NUri) {
        // A non namespace definition node.
        if (XML_LANG_URI == NUri) {
          xmlattrStack.addXmlnsAttr(N);
        } else if (isRealVisible) {
          // The node is visible add the attribute to the list of output attributes.
          result.add(N);
        }
        // keep working
        continue;
      }

      String NName = N.getLocalName();
      String NValue = N.getValue();
      if ("xml".equals(NName) && XML_LANG_URI.equals(NValue)) {
        /* except omit namespace node with local name xml, which defines
         * the xml prefix, if its string value is http://www.w3.org/XML/1998/namespace.
         */
        continue;
      }
      // add the prefix binding to the ns symb table.
      // ns.addInclusiveMapping(NName,NValue,N,isRealVisible);
      if (isVisible(N)) {
        if (!isRealVisible && ns.removeMappingIfRender(NName)) {
          continue;
        }
        // The xpath select this node output it if needed.
        // Node n=ns.addMappingAndRenderXNodeSet(NName,NValue,N,isRealVisible);
        Node n = ns.addMappingAndRender(NName, NValue, N);
        if (n != null) {
          result.add(n);
          if (C14nHelper.namespaceIsRelative(N)) {
            Object exArgs[] = {E.getTagName(), NName, N.getNodeValue()};
            throw new CanonicalizationException("c14n.Canonicalizer.RelativeNamespace", exArgs);
          }
        }
      } else {
        if (isRealVisible && NName != XMLNS) {
          ns.removeMapping(NName);
        } else {
          ns.addMapping(NName, NValue, N);
        }
      }
    }
    if (isRealVisible) {
      // The element is visible, handle the xmlns definition
      Attr xmlns = E.getAttributeNodeNS(XMLNS_URI, XMLNS);
      Node n = null;
      if (xmlns == null) {
        // No xmlns def just get the already defined.
        n = ns.getMapping(XMLNS);
      } else if (!isVisible(xmlns)) {
        // There is a definition but the xmlns is not selected by the xpath.
        // then xmlns=""
        n = ns.addMappingAndRender(XMLNS, "", nullNode);
      }
      // output the xmlns def if needed.
      if (n != null) {
        result.add(n);
      }
      // Float all xml:* attributes of the unselected parent elements to this one.
      // addXmlAttributes(E,result);
      xmlattrStack.getXmlnsAttr(result);
      ns.getUnrenderedNodes(result);
    }

    return result.iterator();
  }
コード例 #16
0
ファイル: DOMUtils.java プロジェクト: OzkanCiftci/jdk7u-jdk
 /**
  * Returns the attribute value for the attribute with the specified name. Returns null if there is
  * no such attribute, or the empty string if the attribute value is empty.
  *
  * <p>This works around a limitation of the DOM <code>Element.getAttributeNode</code> method,
  * which does not distinguish between an unspecified attribute and an attribute with a value of ""
  * (it returns "" for both cases).
  *
  * @param elem the element containing the attribute
  * @param name the name of the attribute
  * @return the attribute value (may be null if unspecified)
  */
 public static String getAttributeValue(Element elem, String name) {
   Attr attr = elem.getAttributeNodeNS(null, name);
   return (attr == null) ? null : attr.getValue();
 }
コード例 #17
0
  /**
   * Returns the Attr[]s to be output for the given element. <br>
   * IMPORTANT: This method expects to work on a modified DOM tree, i.e. a DOM which has been
   * prepared using {@link org.apache.xml.security.utils.XMLUtils#circumventBug2650(
   * org.w3c.dom.Document)}.
   *
   * @param element
   * @param ns
   * @return the Attr[]s to be output
   * @throws CanonicalizationException
   */
  @Override
  protected Iterator<Attr> handleAttributes(Element element, NameSpaceSymbTable ns)
      throws CanonicalizationException {
    // result will contain the attrs which have to be output
    xmlattrStack.push(ns.getLevel());
    boolean isRealVisible = isVisibleDO(element, ns.getLevel()) == 1;
    final SortedSet<Attr> result = this.result;
    result.clear();

    if (element.hasAttributes()) {
      NamedNodeMap attrs = element.getAttributes();
      int attrsLength = attrs.getLength();

      for (int i = 0; i < attrsLength; i++) {
        Attr attribute = (Attr) attrs.item(i);
        String NUri = attribute.getNamespaceURI();
        String NName = attribute.getLocalName();
        String NValue = attribute.getValue();

        if (!XMLNS_URI.equals(NUri)) {
          // A non namespace definition node.
          if (XML_LANG_URI.equals(NUri)) {
            if (NName.equals("id")) {
              if (isRealVisible) {
                // treat xml:id like any other attribute
                // (emit it, but don't inherit it)
                result.add(attribute);
              }
            } else {
              xmlattrStack.addXmlnsAttr(attribute);
            }
          } else if (isRealVisible) {
            // The node is visible add the attribute to the list of output attributes.
            result.add(attribute);
          }
        } else if (!XML.equals(NName) || !XML_LANG_URI.equals(NValue)) {
          /* except omit namespace node with local name xml, which defines
           * the xml prefix, if its string value is
           * http://www.w3.org/XML/1998/namespace.
           */
          // add the prefix binding to the ns symb table.
          if (isVisible(attribute)) {
            if (isRealVisible || !ns.removeMappingIfRender(NName)) {
              // The xpath select this node output it if needed.
              Node n = ns.addMappingAndRender(NName, NValue, attribute);
              if (n != null) {
                result.add((Attr) n);
                if (C14nHelper.namespaceIsRelative(attribute)) {
                  Object exArgs[] = {element.getTagName(), NName, attribute.getNodeValue()};
                  throw new CanonicalizationException(
                      "c14n.Canonicalizer.RelativeNamespace", exArgs);
                }
              }
            }
          } else {
            if (isRealVisible && !XMLNS.equals(NName)) {
              ns.removeMapping(NName);
            } else {
              ns.addMapping(NName, NValue, attribute);
            }
          }
        }
      }
    }

    if (isRealVisible) {
      // The element is visible, handle the xmlns definition
      Attr xmlns = element.getAttributeNodeNS(XMLNS_URI, XMLNS);
      Node n = null;
      if (xmlns == null) {
        // No xmlns def just get the already defined.
        n = ns.getMapping(XMLNS);
      } else if (!isVisible(xmlns)) {
        // There is a definition but the xmlns is not selected by the xpath.
        // then xmlns=""
        n = ns.addMappingAndRender(XMLNS, "", nullNode);
      }
      // output the xmlns def if needed.
      if (n != null) {
        result.add((Attr) n);
      }
      // Float all xml:* attributes of the unselected parent elements to this one.
      xmlattrStack.getXmlnsAttr(result);
      ns.getUnrenderedNodes(result);
    }

    return result.iterator();
  }
コード例 #18
0
 @Kroll.method
 public AttrProxy getAttributeNodeNS(String namespaceURI, String localName) throws DOMException {
   return getProxy(element.getAttributeNodeNS(namespaceURI, localName));
 }
コード例 #19
0
  public TestReport runImpl() throws Exception {
    Handler h = new Handler();
    TestReport report = null;

    // cdata-sections == false
    Document doc = newSVGDoc();
    DOMConfiguration conf = ((AbstractDocument) doc).getDomConfig();
    conf.setParameter("cdata-sections", Boolean.FALSE);
    Element e = doc.getDocumentElement();
    e.appendChild(doc.createTextNode("abc"));
    e.appendChild(doc.createCDATASection("def"));
    e.appendChild(doc.createTextNode("ghi"));
    ((AbstractDocument) doc).normalizeDocument();
    if (!(e.getFirstChild().getNodeType() == Node.TEXT_NODE
        && e.getFirstChild().getNodeValue().equals("abcdefghi")
        && e.getFirstChild() == e.getLastChild())) {
      if (report == null) {
        report = reportError("Document.normalizeDocument test failed");
      }
      report.addDescriptionEntry("DOMConfiguration parameter", "cdata-sections == false");
    }

    // comments == false
    doc = newSVGDoc();
    conf = ((AbstractDocument) doc).getDomConfig();
    conf.setParameter("comments", Boolean.FALSE);
    e = doc.getDocumentElement();
    e.appendChild(doc.createTextNode("abc"));
    e.appendChild(doc.createComment("def"));
    e.appendChild(doc.createTextNode("ghi"));
    ((AbstractDocument) doc).normalizeDocument();
    if (!(e.getFirstChild().getNodeType() == Node.TEXT_NODE
        && e.getFirstChild().getNodeValue().equals("abcghi")
        && e.getFirstChild() == e.getLastChild())) {
      if (report == null) {
        report = reportError("Document.normalizeDocument test failed");
      }
      report.addDescriptionEntry("DOMConfiguration parameter", "comments == false");
    }

    // element-content-whitespace == false
    doc = newSVGDoc();
    conf = ((AbstractDocument) doc).getDomConfig();
    conf.setParameter("element-content-whitespace", Boolean.FALSE);
    e = doc.getDocumentElement();
    e.appendChild(doc.createTextNode("    "));
    e.appendChild(doc.createElementNS(SVG_NAMESPACE_URI, "g"));
    e.appendChild(doc.createTextNode("    "));
    ((AbstractDocument) doc).normalizeDocument();
    if (!(e.getFirstChild().getNodeType() == Node.ELEMENT_NODE
        && e.getFirstChild().getNodeName().equals("g")
        && e.getFirstChild() == e.getLastChild())) {
      if (report == null) {
        report = reportError("Document.normalizeDocument test failed");
      }
      report.addDescriptionEntry(
          "DOMConfiguration parameter", "element-content-whitespace == false");
    }

    // split-cdata-sections == true
    doc = newSVGDoc();
    conf = ((AbstractDocument) doc).getDomConfig();
    conf.setParameter("split-cdata-sections", Boolean.TRUE);
    conf.setParameter("error-handler", h);
    e = doc.getDocumentElement();
    e.appendChild(doc.createCDATASection("before ]]> after"));
    ((AbstractDocument) doc).normalizeDocument();
    if (!(e.getFirstChild().getNodeType() == Node.CDATA_SECTION_NODE
        && e.getFirstChild().getNodeValue().equals("before ]]")
        && e.getFirstChild().getNextSibling().getNodeType() == Node.CDATA_SECTION_NODE
        && e.getFirstChild().getNextSibling().getNodeValue().equals("> after")
        && e.getFirstChild().getNextSibling() == e.getLastChild()
        && h.get("cdata-sections-splitted") == 1)) {
      if (report == null) {
        report = reportError("Document.normalizeDocument test failed");
      }
      report.addDescriptionEntry("DOMConfiguration parameter", "split-cdata-sections == true");
    }

    // well-formed
    doc = newSVGDoc();
    ((AbstractDocument) doc).setStrictErrorChecking(false);
    conf = ((AbstractDocument) doc).getDomConfig();
    conf.setParameter("error-handler", h);
    e = doc.getDocumentElement();
    e.appendChild(doc.createComment("before -- after"));
    e.appendChild(doc.createComment("ends in a dash -"));
    e.setAttribute("*", "blah");
    e.appendChild(doc.createProcessingInstruction("abc", "def?>"));
    ((AbstractDocument) doc).normalizeDocument();
    if (!(h.get("wf-invalid-character-in-node-name") == 1 && h.get("wf-invalid-character") == 3)) {
      if (report == null) {
        report = reportError("Document.normalizeDocument test failed");
      }
      report.addDescriptionEntry("DOMConfiguration parameter", "well-formed == true");
    }

    // namespaces
    doc = newDoc();
    e = doc.createElementNS(null, "root");
    doc.appendChild(e);
    Element e2 = doc.createElementNS(null, "parent");
    e.appendChild(e2);
    e2.setAttributeNS(XMLNS_NAMESPACE_URI, "xmlns:ns", "http://www.example.org/ns1");
    e2.setAttributeNS(XMLNS_NAMESPACE_URI, "xmlns:bar", "http://www.example.org/ns2");
    Element e3 = doc.createElementNS("http://www.example.org/ns1", "ns:child1");
    e2.appendChild(e3);
    e3.setAttributeNS(XMLNS_NAMESPACE_URI, "xmlns:ns", "http://www.example.org/ns2");
    e3 = doc.createElementNS("http://www.example.org/ns2", "ns:child2");
    e2.appendChild(e3);
    ((AbstractDocument) doc).normalizeDocument();
    Attr a = e3.getAttributeNodeNS(XMLNS_NAMESPACE_URI, "ns");
    if (!(a != null
        && a.getNodeName().equals("xmlns:ns")
        && a.getNodeValue().equals("http://www.example.org/ns2"))) {
      if (report == null) {
        report = reportError("Document.normalizeDocument test failed");
      }
      report.addDescriptionEntry("DOMConfiguration parameter", "namespaces == true, test 1");
    }

    doc = newDoc();
    e = doc.createElementNS(null, "root");
    doc.appendChild(e);
    e2 = doc.createElementNS("http://www.example.org/ns1", "ns:child1");
    e.appendChild(e2);
    e2.setAttributeNS(XMLNS_NAMESPACE_URI, "xmlns:ns", "http://www.example.org/ns1");
    e3 = doc.createElementNS("http://www.example.org/ns1", "ns:child2");
    e2.appendChild(e3);
    e2 =
        (Element)
            ((AbstractDocument) doc).renameNode(e2, "http://www.example.org/ns2", "ns:child1");
    ((AbstractDocument) doc).normalizeDocument();
    a = e2.getAttributeNodeNS(XMLNS_NAMESPACE_URI, "ns");
    Attr a2 = e3.getAttributeNodeNS(XMLNS_NAMESPACE_URI, "ns");
    if (!(a != null
        && a.getNodeName().equals("xmlns:ns")
        && a.getNodeValue().equals("http://www.example.org/ns2")
        && a2 != null
        && a2.getNodeName().equals("xmlns:ns")
        && a2.getNodeValue().equals("http://www.example.org/ns1"))) {
      if (report == null) {
        report = reportError("Document.normalizeDocument test failed");
      }
      report.addDescriptionEntry("DOMConfiguration parameter", "namespaces == true, test 2");
    }

    doc = newDoc();
    e = doc.createElementNS(null, "root");
    doc.appendChild(e);
    e2 = doc.createElementNS("http://www.example.org/ns1", "child1");
    e.appendChild(e2);
    e2.setAttributeNS("http://www.example.org/ns2", "blah", "hi");
    ((AbstractDocument) doc).normalizeDocument();
    a = e2.getAttributeNodeNS(XMLNS_NAMESPACE_URI, "xmlns");
    a2 = e2.getAttributeNodeNS(XMLNS_NAMESPACE_URI, "NS1");
    if (!(a != null
        && a.getNodeValue().equals("http://www.example.org/ns1")
        && a2 != null
        && a2.getNodeValue().equals("http://www.example.org/ns2"))) {
      if (report == null) {
        report = reportError("Document.normalizeDocument test failed");
      }
      report.addDescriptionEntry("DOMConfiguration parameter", "namespaces == true, test 3");
    }

    // namespace-declarations == false
    doc = newDoc();
    e = doc.createElementNS(null, "ex:root");
    e.setAttributeNS(XMLNS_NAMESPACE_URI, "xmlns:ex", "http://www.example.org/ns1");
    conf = ((AbstractDocument) doc).getDomConfig();
    conf.setParameter("namespace-declarations", Boolean.FALSE);
    doc.appendChild(e);
    ((AbstractDocument) doc).normalizeDocument();
    if (!(e.getAttributeNodeNS(XMLNS_NAMESPACE_URI, "ex") == null)) {
      if (report == null) {
        report = reportError("Document.normalizeDocument test failed");
      }
      report.addDescriptionEntry("DOMConfiguration parameter", "namespace-declarations == false");
    }

    if (report == null) {
      return reportSuccess();
    }
    return report;
  }