org.w3c.dom.Attr Java Examples

The following examples show how to use org.w3c.dom.Attr. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Internalizer.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Declares a new prefix on the given element and associates it
 * with the specified namespace URI.
 * <p>
 * Note that this method doesn't use the default namespace
 * even if it can.
 */
private String allocatePrefix( Element e, String nsUri ) {
    // look for existing namespaces.
    NamedNodeMap atts = e.getAttributes();
    for( int i=0; i<atts.getLength(); i++ ) {
        Attr a = (Attr)atts.item(i);
        if( Const.XMLNS_URI.equals(a.getNamespaceURI()) ) {
            if( a.getName().indexOf(':')==-1 )  continue;

            if( a.getValue().equals(nsUri) )
                return a.getLocalName();    // found one
        }
    }

    // none found. allocate new.
    while(true) {
        String prefix = "p"+(int)(Math.random()*1000000)+'_';
        if(e.getAttributeNodeNS(Const.XMLNS_URI,prefix)!=null)
            continue;   // this prefix is already allocated.

        e.setAttributeNS(Const.XMLNS_URI,"xmlns:"+prefix,nsUri);
        return prefix;
    }
}
 
Example #2
Source File: XmlNode.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
private void addNamespaces(Namespaces rv, Element element) {
    if (element == null) throw new RuntimeException("element must not be null");
    String myDefaultNamespace = toUri(element.lookupNamespaceURI(null));
    String parentDefaultNamespace = "";
    if (element.getParentNode() != null) {
        parentDefaultNamespace = toUri(element.getParentNode().lookupNamespaceURI(null));
    }
    if (!myDefaultNamespace.equals(parentDefaultNamespace) || !(element.getParentNode() instanceof Element) ) {
        rv.declare(Namespace.create("", myDefaultNamespace));
    }
    NamedNodeMap attributes = element.getAttributes();
    for (int i=0; i<attributes.getLength(); i++) {
        Attr attr = (Attr)attributes.item(i);
        if (attr.getPrefix() != null && attr.getPrefix().equals("xmlns")) {
            rv.declare(Namespace.create(attr.getLocalName(), attr.getValue()));
        }
    }
}
 
Example #3
Source File: ContactPersonUnmarshaller.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException {
    ContactPerson person = (ContactPerson) samlObject;

    if (attribute.getLocalName().equals(ContactPerson.CONTACT_TYPE_ATTRIB_NAME)) {
        if (ContactPersonTypeEnumeration.TECHNICAL.toString().equals(attribute.getValue())) {
            person.setType(ContactPersonTypeEnumeration.TECHNICAL);
        } else if (ContactPersonTypeEnumeration.SUPPORT.toString().equals(attribute.getValue())) {
            person.setType(ContactPersonTypeEnumeration.SUPPORT);
        } else if (ContactPersonTypeEnumeration.ADMINISTRATIVE.toString().equals(attribute.getValue())) {
            person.setType(ContactPersonTypeEnumeration.ADMINISTRATIVE);
        } else if (ContactPersonTypeEnumeration.BILLING.toString().equals(attribute.getValue())) {
            person.setType(ContactPersonTypeEnumeration.BILLING);
        } else if (ContactPersonTypeEnumeration.OTHER.toString().equals(attribute.getValue())) {
            person.setType(ContactPersonTypeEnumeration.OTHER);
        } else {
            super.processAttribute(samlObject, attribute);
        }
    } else {
        QName attribQName = XMLHelper.getNodeQName(attribute);
        if (attribute.isId()) {
            person.getUnknownAttributes().registerID(attribQName);
        }
        person.getUnknownAttributes().put(attribQName, attribute.getValue());
    }
}
 
Example #4
Source File: EntitiesDescriptorUnmarshaller.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException {
    EntitiesDescriptor entitiesDescriptor = (EntitiesDescriptor) samlObject;

    if (attribute.getLocalName().equals(EntitiesDescriptor.ID_ATTRIB_NAME)) {
        entitiesDescriptor.setID(attribute.getValue());
        attribute.getOwnerElement().setIdAttributeNode(attribute, true);
    } else if (attribute.getLocalName().equals(TimeBoundSAMLObject.VALID_UNTIL_ATTRIB_NAME)
            && !DatatypeHelper.isEmpty(attribute.getValue())) {
        entitiesDescriptor.setValidUntil(new DateTime(attribute.getValue(), ISOChronology.getInstanceUTC()));
    } else if (attribute.getLocalName().equals(CacheableSAMLObject.CACHE_DURATION_ATTRIB_NAME)) {
        entitiesDescriptor.setCacheDuration(new Long(XMLHelper.durationToLong(attribute.getValue())));
    } else if (attribute.getLocalName().equals(EntitiesDescriptor.NAME_ATTRIB_NAME)) {
        entitiesDescriptor.setName(attribute.getValue());
    } else {
        super.processAttribute(samlObject, attribute);
    }
}
 
Example #5
Source File: SignatureAlgorithm.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Constructor SignatureAlgorithm
 *
 * @param element
 * @param baseURI
 * @param secureValidation
 * @throws XMLSecurityException
 */
public SignatureAlgorithm(
    Element element, String baseURI, boolean secureValidation
) throws XMLSecurityException {
    super(element, baseURI);
    algorithmURI = this.getURI();

    Attr attr = element.getAttributeNodeNS(null, "Id");
    if (attr != null) {
        element.setIdAttributeNode(attr, true);
    }

    if (secureValidation && (XMLSignature.ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5.equals(algorithmURI)
        || XMLSignature.ALGO_ID_SIGNATURE_NOT_RECOMMENDED_RSA_MD5.equals(algorithmURI))) {
        Object exArgs[] = { algorithmURI };

        throw new XMLSecurityException("signature.signatureAlgorithm", exArgs);
    }

    signatureAlgorithm = getSignatureAlgorithmSpi(algorithmURI);
    signatureAlgorithm.engineGetContextFromElement(this.constructionElement);
}
 
Example #6
Source File: LayoutIdFormat.java    From lewis with Apache License 2.0 6 votes vote down vote up
@Override
public void visitAttribute(@NonNull XmlContext context, @NonNull Attr attribute) {
    String value = attribute.getValue();

    if (!value.isEmpty()) {

        // Make sure this is really one of the android: attributes
        if (!ANDROID_URI.equals(attribute.getNamespaceURI())) {
            return;
        }

        value = value.substring(5); // ignore "@+id/"

        if (!idCorrectFormat(value)) {
            context.report(ISSUE, attribute, context.getLocation(attribute),
                    String.format("The id \"%1$s\", should be written using lowerCamelCase.", value));
        }

    }
}
 
Example #7
Source File: SignatureProperties.java    From JDKSourceCode1.8 with MIT License 6 votes vote down vote up
/**
 * Constructs {@link SignatureProperties} from {@link Element}
 * @param element <code>SignatureProperties</code> element
 * @param BaseURI the URI of the resource where the XML instance was stored
 * @throws XMLSecurityException
 */
public SignatureProperties(Element element, String BaseURI) throws XMLSecurityException {
    super(element, BaseURI);

    Attr attr = element.getAttributeNodeNS(null, "Id");
    if (attr != null) {
        element.setIdAttributeNode(attr, true);
    }

    int length = getLength();
    for (int i = 0; i < length; i++) {
        Element propertyElem =
            XMLUtils.selectDsNode(this.constructionElement, Constants._TAG_SIGNATUREPROPERTY, i);
        Attr propertyAttr = propertyElem.getAttributeNodeNS(null, "Id");
        if (propertyAttr != null) {
            propertyElem.setIdAttributeNode(propertyAttr, true);
        }
    }
}
 
Example #8
Source File: C14nHelper.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
/**
 * This method throws an exception if the Attribute value contains
 * a relative URI.
 *
 * @param attr
 * @throws CanonicalizationException
 */
public static void assertNotRelativeNS(Attr attr) throws CanonicalizationException {
    if (attr == null) {
        return;
    }

    String nodeAttrName = attr.getNodeName();
    boolean definesDefaultNS = nodeAttrName.equals("xmlns");
    boolean definesNonDefaultNS = nodeAttrName.startsWith("xmlns:");

    if ((definesDefaultNS || definesNonDefaultNS) && namespaceIsRelative(attr)) {
        String parentName = attr.getOwnerElement().getTagName();
        String attrValue = attr.getValue();
        Object exArgs[] = { parentName, nodeAttrName, attrValue };

        throw new CanonicalizationException(
            "c14n.Canonicalizer.RelativeNamespace", exArgs
        );
    }
}
 
Example #9
Source File: AuthorizationDecisionStatementUnmarshaller.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException {

    AuthorizationDecisionStatement authorizationDecisionStatement;
    authorizationDecisionStatement = (AuthorizationDecisionStatement) samlObject;

    if (AuthorizationDecisionStatement.DECISION_ATTRIB_NAME.equals(attribute.getLocalName())) {
        String value = attribute.getValue();
        if (value.equals(DecisionTypeEnumeration.PERMIT.toString())) {
            authorizationDecisionStatement.setDecision(DecisionTypeEnumeration.PERMIT);
        } else if (value.equals(DecisionTypeEnumeration.DENY.toString())) {
            authorizationDecisionStatement.setDecision(DecisionTypeEnumeration.DENY);
        } else if (value.equals(DecisionTypeEnumeration.INDETERMINATE.toString())) {
            authorizationDecisionStatement.setDecision(DecisionTypeEnumeration.INDETERMINATE);
        } else {
            log.error("Unknown value for DecisionType '" + value + "'");
            throw new UnmarshallingException("Unknown value for DecisionType '" + value + "'");
        }
    } else if (AuthorizationDecisionStatement.RESOURCE_ATTRIB_NAME.equals(attribute.getLocalName())) {
        authorizationDecisionStatement.setResource(attribute.getValue());
    } else {
        super.processAttribute(samlObject, attribute);
    }
}
 
Example #10
Source File: XMLUtils.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * This method returns the first non-null owner document of the Nodes in this Set.
 * This method is necessary because it <I>always</I> returns a
 * {@link Document}. {@link Node#getOwnerDocument} returns <CODE>null</CODE>
 * if the {@link Node} is a {@link Document}.
 *
 * @param xpathNodeSet
 * @return the owner document
 */
public static Document getOwnerDocument(Set<Node> xpathNodeSet) {
    NullPointerException npe = null;
    for (Node node : xpathNodeSet) {
        int nodeType = node.getNodeType();
        if (nodeType == Node.DOCUMENT_NODE) {
            return (Document) node;
        }
        try {
            if (nodeType == Node.ATTRIBUTE_NODE) {
                return ((Attr)node).getOwnerElement().getOwnerDocument();
            }
            return node.getOwnerDocument();
        } catch (NullPointerException e) {
            npe = e;
        }
    }

    throw new NullPointerException(I18n.translate("endorsed.jdk1.4.0")
                                   + " Original message was \""
                                   + (npe == null ? "" : npe.getMessage()) + "\"");
}
 
Example #11
Source File: SetAttributeNode.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public static void test2() {
    String name = "attr";
    String oldValue = "old value";
    String newValue = "new value";
    Attr retAttr;

    IIOMetadataNode parent = new IIOMetadataNode("parent");
    MyAttrNode attrNode1 = new MyAttrNode(name, oldValue);
    MyAttrNode attrNode2 = new MyAttrNode(name, newValue);

    retAttr = parent.setAttributeNode(attrNode1);
    retAttr = parent.setAttributeNode(attrNode2);

    String actName = retAttr.getNodeName();
    String actValue = retAttr.getValue();

    if (!actName.equals(name) || !actValue.equals(oldValue)) {
        throw new RuntimeException("Test 2 failed: Invalid attribute " +
                                   "returned: " +
                                   "(name: " + actName +
                                   ", value: " + actValue + ")");
    }
}
 
Example #12
Source File: NameSpaceSymbTable.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Gets the attribute node that defines the binding for the prefix.
 * @param prefix the prefix to obtain the attribute.
 * @return null if there is no need to render the prefix. Otherwise the node of
 * definition.
 **/
public Attr getMapping(String prefix) {
    NameSpaceSymbEntry entry = symb.get(prefix);
    if (entry == null) {
        //There is no definition for the prefix(a bug?).
        return null;
    }
    if (entry.rendered) {
        //No need to render an entry already rendered.
        return null;
    }
    // Mark this entry as render.
    entry = (NameSpaceSymbEntry) entry.clone();
    needsClone();
    symb.put(prefix, entry);
    entry.rendered = true;
    entry.lastrendered = entry.uri;
    // Return the node for outputing.
    return entry.n;
}
 
Example #13
Source File: XmlUtil.java    From windup with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Converts the given {@link Node} to a {@link String}.
 */
public static String nodeToString(Node node)
{
    StringWriter sw = new StringWriter();
    if (node instanceof Attr)
    {
        Attr attr = (Attr) node;
        return attr.getValue();
    }
    try
    {
        Transformer t = TransformerFactory.newInstance().newTransformer();
        t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        t.setOutputProperty(OutputKeys.INDENT, "no");
        t.transform(new DOMSource(node), new StreamResult(sw));
    }
    catch (TransformerException te)
    {
        LOG.warning("Transformer Exception: " + te.getMessage());
    }
    return sw.toString();
}
 
Example #14
Source File: ElementImpl.java    From j2objc with Apache License 2.0 6 votes vote down vote up
public Attr setAttributeNode(Attr newAttr) throws DOMException {
    AttrImpl newAttrImpl = (AttrImpl) newAttr;

    if (newAttrImpl.document != this.document) {
        throw new DOMException(DOMException.WRONG_DOCUMENT_ERR, null);
    }

    if (newAttrImpl.getOwnerElement() != null) {
        throw new DOMException(DOMException.INUSE_ATTRIBUTE_ERR, null);
    }

    AttrImpl oldAttrImpl = null;

    int i = indexOfAttribute(newAttr.getName());
    if (i != -1) {
        oldAttrImpl = attributes.get(i);
        attributes.remove(i);
    }

    attributes.add(newAttrImpl);
    newAttrImpl.ownerElement = this;

    return oldAttrImpl;
}
 
Example #15
Source File: AbstractDOMParser.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
protected Attr createAttrNode (QName attrQName) {
    Attr attr = null;

    if (fNamespaceAware) {
        if (fDocumentImpl != null) {
            // if we are using xerces DOM implementation, call our
            // own constructor to reuse the strings we have here.
            attr = fDocumentImpl.createAttributeNS (attrQName.uri,
            attrQName.rawname,
            attrQName.localpart);
        }
        else {
            attr = fDocument.createAttributeNS (attrQName.uri,
            attrQName.rawname);
        }
    }
    else {
        attr = fDocument.createAttribute (attrQName.rawname);
    }

    return attr;
}
 
Example #16
Source File: XmlCombiner.java    From Flashtool with GNU General Public License v3.0 6 votes vote down vote up
private static CombineChildren getCombineChildren(@Nullable Element element) {
	CombineChildren combine = null;
	if (element == null) {
		return null;
	}
	Attr combineAttribute = element.getAttributeNode(CombineChildren.ATTRIBUTE_NAME);
	if (combineAttribute != null) {
		try {
			combine = CombineChildren.valueOf(combineAttribute.getValue().toUpperCase());
		} catch (IllegalArgumentException e) {
			throw new RuntimeException("The attribute 'combine' of element '"
					+ element.getTagName() + "' has invalid value '"
					+ combineAttribute.getValue(), e);
		}
	}
	return combine;
}
 
Example #17
Source File: XmlUrlRewriteRulesExporter.java    From knox with Apache License 2.0 6 votes vote down vote up
private Element createElement( Document document, String name, Object bean )
    throws IntrospectionException, InvocationTargetException, NoSuchMethodException, IllegalAccessException {
  Element element = document.createElement( name );
  BeanInfo beanInfo = Introspector.getBeanInfo( bean.getClass(), Object.class );
  for( PropertyDescriptor propInfo: beanInfo.getPropertyDescriptors() ) {
    String propName = propInfo.getName();
    if( propInfo.getReadMethod() != null && String.class.isAssignableFrom( propInfo.getPropertyType() ) ) {
      String propValue = BeanUtils.getProperty( bean, propName );
      if( propValue != null && !propValue.isEmpty() ) {
        // Doing it the hard way to avoid having the &'s in the query string escaped at &amp;
        Attr attr = document.createAttribute( propName );
        attr.setValue( propValue );
        element.setAttributeNode( attr );
        //element.setAttribute( propName, propValue );
      }
    }
  }
  return element;
}
 
Example #18
Source File: CanonicalizerBase.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Adds to ns the definitions from the parent elements of el
 * @param el
 * @param ns
 */
protected final void getParentNameSpaces(Element el, NameSpaceSymbTable ns)  {
    Node n1 = el.getParentNode();
    if (n1 == null || Node.ELEMENT_NODE != n1.getNodeType()) {
        return;
    }
    //Obtain all the parents of the element
    List<Element> parents = new ArrayList<Element>();
    Node parent = n1;
    while (parent != null && Node.ELEMENT_NODE == parent.getNodeType()) {
        parents.add((Element)parent);
        parent = parent.getParentNode();
    }
    //Visit them in reverse order.
    ListIterator<Element> it = parents.listIterator(parents.size());
    while (it.hasPrevious()) {
        Element ele = it.previous();
        handleParent(ele, ns);
    }
    parents.clear();
    Attr nsprefix;
    if (((nsprefix = ns.getMappingWithoutRendered(XMLNS)) != null)
            && "".equals(nsprefix.getValue())) {
        ns.addMappingAndRender(
                XMLNS, "", getNullNode(nsprefix.getOwnerDocument()));
    }
}
 
Example #19
Source File: DOMNormalizer.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
final String normalizeAttributeValue(String value, Attr attr) {
    if (!attr.getSpecified()){
        // specified attributes should already have a normalized form
        // since those were added by validator
        return value;
    }
    int end = value.length();
    // ensure capacity
    if (fNormalizedValue.ch.length < end) {
        fNormalizedValue.ch = new char[end];
    }
    fNormalizedValue.length = 0;
    boolean normalized = false;
    for (int i = 0; i < end; i++) {
        char c = value.charAt(i);
        if (c==0x0009 || c==0x000A) {
           fNormalizedValue.ch[fNormalizedValue.length++] = ' ';
           normalized = true;
        }
        else if(c==0x000D){
           normalized = true;
           fNormalizedValue.ch[fNormalizedValue.length++] = ' ';
           int next = i+1;
           if (next < end && value.charAt(next)==0x000A) i=next; // skip following xA
        }
        else {
            fNormalizedValue.ch[fNormalizedValue.length++] = c;
        }
    }
    if (normalized){
       value = fNormalizedValue.toString();
       attr.setValue(value);
    }
    return value;
}
 
Example #20
Source File: C14nHelper.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * This method throws a CanonicalizationException if the supplied Element
 * contains any relative namespaces.
 *
 * @param ctxNode
 * @throws CanonicalizationException
 * @see C14nHelper#assertNotRelativeNS(Attr)
 */
public static void checkForRelativeNamespace(Element ctxNode)
    throws CanonicalizationException {
    if (ctxNode != null) {
        NamedNodeMap attributes = ctxNode.getAttributes();

        for (int i = 0; i < attributes.getLength(); i++) {
            C14nHelper.assertNotRelativeNS((Attr) attributes.item(i));
        }
    } else {
        throw new CanonicalizationException("Called checkForRelativeNamespace() on null");
    }
}
 
Example #21
Source File: XSDocumentInfo.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Initialize namespace support by collecting all of the namespace
 * declarations in the root's ancestors. This is necessary to
 * support schemas fragments, i.e. schemas embedded in other
 * documents. See,
 *
 * https://jaxp.dev.java.net/issues/show_bug.cgi?id=43
 *
 * Requires the DOM to be created with namespace support enabled.
 */
private void initNamespaceSupport(Element schemaRoot) {
    fNamespaceSupport = new SchemaNamespaceSupport();
    fNamespaceSupport.reset();

    Node parent = schemaRoot.getParentNode();
    while (parent != null && parent.getNodeType() == Node.ELEMENT_NODE
            && !parent.getNodeName().equals("DOCUMENT_NODE"))
    {
        Element eparent = (Element) parent;
        NamedNodeMap map = eparent.getAttributes();
        int length = (map != null) ? map.getLength() : 0;
        for (int i = 0; i < length; i++) {
            Attr attr = (Attr) map.item(i);
            String uri = attr.getNamespaceURI();

            // Check if attribute is an ns decl -- requires ns support
            if (uri != null && uri.equals("http://www.w3.org/2000/xmlns/")) {
                String prefix = attr.getLocalName().intern();
                if (prefix == "xmlns") prefix = "";
                // Declare prefix if not set -- moving upwards
                if (fNamespaceSupport.getURI(prefix) == null) {
                    fNamespaceSupport.declarePrefix(prefix,
                            attr.getValue().intern());
                }
            }
        }
        parent = parent.getParentNode();
    }
}
 
Example #22
Source File: MapLayout.java    From MeteoInfo with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void addLayoutGraphicElement(Document doc, Element parent, LayoutGraphic aLayoutGraphic) {
    Element layoutGraphic = doc.createElement("LayoutGraphic");
    Attr elementType = doc.createAttribute("ElementType");
    Attr isTitle = doc.createAttribute("IsTitle");
    Attr left = doc.createAttribute("Left");
    Attr top = doc.createAttribute("Top");
    Attr width = doc.createAttribute("Width");
    Attr height = doc.createAttribute("Height");

    elementType.setValue(aLayoutGraphic.getElementType().toString());
    isTitle.setValue(String.valueOf(aLayoutGraphic.isTitle()));
    left.setValue(String.valueOf(aLayoutGraphic.getLeft()));
    top.setValue(String.valueOf(aLayoutGraphic.getTop()));
    width.setValue(String.valueOf(aLayoutGraphic.getWidth()));
    height.setValue(String.valueOf(aLayoutGraphic.getHeight()));

    layoutGraphic.setAttributeNode(elementType);
    layoutGraphic.setAttributeNode(isTitle);
    layoutGraphic.setAttributeNode(left);
    layoutGraphic.setAttributeNode(top);
    layoutGraphic.setAttributeNode(width);
    layoutGraphic.setAttributeNode(height);

    //Add graphic
    Graphic aGraphic = aLayoutGraphic.getGraphic();
    aGraphic.exportToXML(doc, layoutGraphic);

    //Append in parent
    parent.appendChild(layoutGraphic);
}
 
Example #23
Source File: RenewingUnmarshaller.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException {
    Renewing renewing = (Renewing) xmlObject;
    
    if (attribute.getLocalName().equals(Renewing.ALLOW_ATTRIB_NAME)) {
        renewing.setAllow(XSBooleanValue.valueOf(attribute.getValue()));
    } else if (attribute.getLocalName().equals(Renewing.OK_ATTRIB_NAME)) {
        renewing.setOK(XSBooleanValue.valueOf(attribute.getValue()));
    } else {
        super.processAttribute(xmlObject, attribute);
    }
}
 
Example #24
Source File: DOMNamespaceContext.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
private void addNamespaces(Node element) {
    if (element.getParentNode() != null) {
        addNamespaces(element.getParentNode());
    }
    if (element instanceof Element) {
        Element el = (Element)element;
        NamedNodeMap map = el.getAttributes();
        for (int x = 0; x < map.getLength(); x++) {
            Attr attr = (Attr)map.item(x);
            if ("xmlns".equals(attr.getPrefix())) {
                namespaceMap.put(attr.getLocalName(), attr.getValue());
            }
        }
    }
}
 
Example #25
Source File: ElementImpl.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
/**
* Add a new name/value pair, or replace the value of the existing
* attribute having that name.
*
* Note: this method supports only the simplest kind of Attribute,
* one whose value is a string contained in a single Text node.
* If you want to assert a more complex value (which XML permits,
* though HTML doesn't), see setAttributeNode().
*
* The attribute is created with specified=true, meaning it's an
* explicit value rather than inherited from the DTD as a default.
* Again, setAttributeNode can be used to achieve other results.
*
* @throws DOMException(INVALID_NAME_ERR) if the name is not acceptable.
* (Attribute factory will do that test for us.)
*
* @throws DOMException(NO_MODIFICATION_ALLOWED_ERR) if the node is
* readonly.
*/
   public void setAttribute(String name, String value) {

           if (ownerDocument.errorChecking && isReadOnly()) {
                   String msg =
                           DOMMessageFormatter.formatMessage(
                                   DOMMessageFormatter.DOM_DOMAIN,
                                   "NO_MODIFICATION_ALLOWED_ERR",
                                   null);
                   throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR, msg);
           }

           if (needsSyncData()) {
                   synchronizeData();
           }

           Attr newAttr = getAttributeNode(name);
           if (newAttr == null) {
                   newAttr = getOwnerDocument().createAttribute(name);

                   if (attributes == null) {
                           attributes = new AttributeMap(this, null);
                   }

                   newAttr.setNodeValue(value);
                   attributes.setNamedItem(newAttr);
           }
           else {
                   newAttr.setNodeValue(value);
           }

   }
 
Example #26
Source File: KeyInfoReferenceResolver.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Resolve the KeyInfoReference Element's URI attribute into a KeyInfo instance.
 *
 * @param element
 * @param baseURI
 * @param storage
 * @return the KeyInfo which is referred to by this KeyInfoReference, or null if can not be resolved
 * @throws XMLSecurityException
 */
private KeyInfo resolveReferentKeyInfo(Element element, String baseURI, StorageResolver storage) throws XMLSecurityException {
    KeyInfoReference reference = new KeyInfoReference(element, baseURI);
    Attr uriAttr = reference.getURIAttr();

    XMLSignatureInput resource = resolveInput(uriAttr, baseURI, secureValidation);

    Element referentElement = null;
    try {
        referentElement = obtainReferenceElement(resource);
    } catch (Exception e) {
        if (log.isLoggable(java.util.logging.Level.FINE)) {
            log.log(java.util.logging.Level.FINE, "XMLSecurityException", e);
        }
        return null;
    }

    if (referentElement == null) {
        log.log(java.util.logging.Level.FINE, "De-reference of KeyInfoReference URI returned null: " + uriAttr.getValue());
        return null;
    }

    validateReference(referentElement);

    KeyInfo referent = new KeyInfo(referentElement, baseURI);
    referent.addStorageResolver(storage);
    return referent;
}
 
Example #27
Source File: ElementImpl.java    From jdk1.8-source-analysis with Apache License 2.0 5 votes vote down vote up
public Attr getAttributeNodeNS(String namespaceURI, String localName) {
    for (int i=0; i<attrs.length; i++) {
        if (attrs[i].getName().equals(localName) && nsEquals(attrs[i].getNamespaceURI(), namespaceURI)) {
            return attrs[i];
        }
    }
    return null;
}
 
Example #28
Source File: NamedNodeMapTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testSetNamedItemNS() throws Exception {
    final String nsURI = "urn:BooksAreUs.org:BookInfo";
    Document document = createDOMWithNS("NamedNodeMap01.xml");
    NodeList nodeList = document.getElementsByTagName("body");
    nodeList = nodeList.item(0).getChildNodes();
    Node n = nodeList.item(3);

    NamedNodeMap namedNodeMap = n.getAttributes();

    // creating an Attribute using createAttributeNS
    // method having the same namespaceURI
    // and the same qualified name as the existing one in the xml file
    Attr attr = document.createAttributeNS(nsURI, "b:style");
    // setting to a new Value
    attr.setValue("newValue");
    Node replacedAttr = namedNodeMap.setNamedItemNS(attr); // return the replaced attr
    assertEquals(replacedAttr.getNodeValue(), "font-family");
    Node updatedAttr = namedNodeMap.getNamedItemNS(nsURI, "style");
    assertEquals(updatedAttr.getNodeValue(), "newValue");


    // creating a non existing attribute node
    attr = document.createAttributeNS(nsURI, "b:newNode");
    attr.setValue("newValue");

    assertNull(namedNodeMap.setNamedItemNS(attr)); // return null

    // checking if the node could be accessed
    // using the getNamedItemNS method
    Node newAttr = namedNodeMap.getNamedItemNS(nsURI, "newNode");
    assertEquals(newAttr.getNodeValue(), "newValue");
}
 
Example #29
Source File: SignatureConfirmationUnmarshaller.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException {
    SignatureConfirmation sc = (SignatureConfirmation) xmlObject;
    
    QName attrName =
        XMLHelper.constructQName(attribute.getNamespaceURI(), attribute.getLocalName(), attribute.getPrefix());
    if (SignatureConfirmation.WSU_ID_ATTR_NAME.equals(attrName)) {
        sc.setWSUId(attribute.getValue());
        attribute.getOwnerElement().setIdAttributeNode(attribute, true);
    } else if (SignatureConfirmation.VALUE_ATTRIB_NAME.equals(attribute.getLocalName())) {
        sc.setValue(attribute.getValue());
    } else {
        super.processAttribute(xmlObject, attribute);
    }
}
 
Example #30
Source File: AttrList.java    From fastods with GNU General Public License v3.0 5 votes vote down vote up
/**
 * @param attributes the attributes
 * @return the attr list
 */
static AttrList create(final NamedNodeMap attributes) {
    final int l = attributes.getLength();
    final List<Attr> as = new ArrayList<Attr>(l);
    for (int i = 0; i < l; i++) {
        as.add((Attr) attributes.item(i));
    }
    return new AttrList(as);
}