Example usage for org.w3c.dom Node getAttributes

List of usage examples for org.w3c.dom Node getAttributes

Introduction

In this page you can find the example usage for org.w3c.dom Node getAttributes.

Prototype

public NamedNodeMap getAttributes();

Source Link

Document

A NamedNodeMap containing the attributes of this node (if it is an Element) or null otherwise.

Usage

From source file:Main.java

public static <T> T loadBean(Node node, Class<T> beanClass)
        throws IntrospectionException, InstantiationException, IllegalAccessException, IllegalArgumentException,
        DOMException, InvocationTargetException {
    T store = beanClass.newInstance();/*from w  w  w . ja v a  2  s  .com*/

    Map<String, PropertyDescriptor> properties = new HashMap<String, PropertyDescriptor>();
    BeanInfo beanInfo = Introspector.getBeanInfo(beanClass);
    for (PropertyDescriptor property : beanInfo.getPropertyDescriptors()) {
        properties.put(property.getName(), property);
    }

    NamedNodeMap attributes = node.getAttributes();
    for (int i = 0; i < attributes.getLength(); i++) {
        Node attribute = attributes.item(i);
        PropertyDescriptor property = properties.get(attribute.getNodeName());
        if (property != null && property.getPropertyType().equals(String.class)
                && property.getWriteMethod() != null) {
            property.getWriteMethod().invoke(store, attribute.getNodeValue());
        }
    }

    NodeList childNodes = node.getChildNodes();
    for (int i = 0; i < childNodes.getLength(); i++) {
        Node child = childNodes.item(i);
        PropertyDescriptor property = properties.get(child.getNodeName());
        if (property != null && property.getPropertyType().equals(String.class)
                && property.getWriteMethod() != null) {
            property.getWriteMethod().invoke(store, child.getTextContent());
        }
    }

    return store;
}

From source file:com.evolveum.midpoint.test.util.TestUtil.java

public static String getNodeOid(Node node) {
    Node oidNode = null;// w  w w  . ja  v  a 2  s.  co  m
    if ((null == node.getAttributes())
            || (null == (oidNode = node.getAttributes()
                    .getNamedItem(SchemaConstants.C_OID_ATTRIBUTE.getLocalPart())))
            || (StringUtils.isEmpty(oidNode.getNodeValue()))) {
        return null;
    }
    String oid = oidNode.getNodeValue();
    return oid;
}

From source file:Main.java

/** Transform xml element and children into a string
 *
 * @param nd Node root of elements to transform
 * @return String representation of xml//ww w .  j  a  v  a2s  .  co m
 */
public static String elementToString(Node nd, boolean add_newlines) {
    //short type = n.getNodeType();

    if (Node.CDATA_SECTION_NODE == nd.getNodeType()) {
        return "<![CDATA[" + nd.getNodeValue() + "]]&gt;";
    }

    // return if simple element type
    final String name = nd.getNodeName();
    if (name.startsWith("#")) {
        if (name.equals("#text"))
            return nd.getNodeValue();
        return "";
    }

    // output name
    String ret = "<" + name;

    // output attributes
    NamedNodeMap attrs = nd.getAttributes();
    if (attrs != null) {
        for (int idx = 0; idx < attrs.getLength(); idx++) {
            Node attr = attrs.item(idx);
            ret += " " + attr.getNodeName() + "=\"" + attr.getNodeValue() + "\"";
        }
    }

    final String text = nd.getTextContent();
    final NodeList child_ndls = nd.getChildNodes();
    String all_child_str = "";

    for (int idx = 0; idx < child_ndls.getLength(); idx++) {
        final String child_str = elementToString(child_ndls.item(idx), add_newlines);
        if ((child_str != null) && (child_str.length() > 0)) {
            all_child_str += child_str;
        }
    }
    if (all_child_str.length() > 0) {
        // output children
        ret += ">" + (add_newlines ? "\n" : " ");
        ret += all_child_str;
        ret += "</" + name + ">";
    } else if ((text != null) && (text.length() > 0)) {
        // output text
        ret += text;
        ret += "</" + name + ">";
    } else {
        // output nothing
        ret += "/>" + (add_newlines ? "\n" : " ");
    }

    return ret;
}

From source file:Main.java

public static void assertEquivalent(Node node, Node node2) {
    if (node == null) {
        throw new IllegalArgumentException("the first node to be compared is null");
    }/* w w  w  . ja  v  a 2 s.  c om*/

    if (node2 == null) {
        throw new IllegalArgumentException("the second node to be compared is null");
    }

    if (!node.getNodeName().equals(node2.getNodeName())) {
        throw new IllegalArgumentException("nodes have different node names");
    }

    int attrCount = 0;
    NamedNodeMap attrs = node.getAttributes();
    if (attrs != null) {
        attrCount = attrs.getLength();
    }

    int attrCount2 = 0;
    NamedNodeMap attrs2 = node2.getAttributes();
    if (attrs2 != null) {
        attrCount2 = attrs2.getLength();
    }

    if (attrCount != attrCount2) {
        throw new IllegalArgumentException("nodes hava a different number of attributes");
    }

    outer: for (int i = 0; i < attrCount; i++) {
        Node n = attrs.item(i);
        String name = n.getNodeName();
        String value = n.getNodeValue();

        for (int j = 0; j < attrCount; j++) {
            Node n2 = attrs2.item(j);
            String name2 = n2.getNodeName();
            String value2 = n2.getNodeValue();

            if (name.equals(name2) && value.equals(value2)) {
                continue outer;
            }
        }
        throw new IllegalArgumentException("attribute " + name + "=" + value + " doesn't match");
    }

    boolean hasChildren = node.hasChildNodes();

    if (hasChildren != node2.hasChildNodes()) {
        throw new IllegalArgumentException("one node has children and the other doesn't");
    }

    if (hasChildren) {
        NodeList nl = node.getChildNodes();
        NodeList nl2 = node2.getChildNodes();

        short[] toFilter = new short[] { Node.TEXT_NODE, Node.ATTRIBUTE_NODE, Node.COMMENT_NODE };
        List nodes = filter(nl, toFilter);
        List nodes2 = filter(nl2, toFilter);

        int length = nodes.size();

        if (length != nodes2.size()) {
            throw new IllegalArgumentException("nodes hava a different number of children");
        }

        for (int i = 0; i < length; i++) {
            Node n = (Node) nodes.get(i);
            Node n2 = (Node) nodes2.get(i);
            assertEquivalent(n, n2);
        }
    }
}

From source file:Main.java

private static Node convertFromNamespaceForm(final Node node) {
    if (node instanceof Element) {
        final Document document = node.getOwnerDocument();
        final Element newElement = document.createElementNS(null, node.getLocalName());
        final NodeList children = node.getChildNodes();

        for (int i = 0, n = children.getLength(); i < n; i++) {
            final Node oldChildNode = children.item(i);
            final Node newChildNode = convertFromNamespaceForm(oldChildNode);

            newElement.appendChild(newChildNode);
        }//  w w w .  ja va 2  s .c o m

        final NamedNodeMap attributes = node.getAttributes();

        for (int i = 0, n = attributes.getLength(); i < n; i++) {
            final Attr attr = (Attr) attributes.item(i);
            final String attrQualifiedName = attr.getNodeName();
            final String attrLocalName = attr.getLocalName();

            if (!attrQualifiedName.equals(XMLNS) && !attrQualifiedName.startsWith(XMLNS_COLON)
                    && !attrLocalName.equals(XSI_SCHEMA_LOCATION_ATTR)) {
                newElement.setAttributeNS(null, attrLocalName, attr.getValue());
            }
        }

        return newElement;
    } else {
        return node.cloneNode(true);
    }
}

From source file:com.eucalyptus.imaging.manifest.DownloadManifestFactory.java

/**
 * Generates download manifest based on bundle manifest and puts in into
 * system owned bucket/*from   ww w .  j a  v  a 2  s.c  om*/
 * 
 * @param baseManifest
 *          the base manifest
 * @param keyToUse
 *          public key that used for encryption
 * @param manifestName
 *          name for generated manifest file
 * @param expirationHours
 *          expiration policy in hours for pre-signed URLs
 * @param urlForNc
 *          indicates if urs are constructed for NC use
 * @return pre-signed URL that can be used to download generated manifest
 * @throws DownloadManifestException
 */
public static String generateDownloadManifest(final ImageManifestFile baseManifest, final PublicKey keyToUse,
        final String manifestName, int expirationHours, boolean urlForNc) throws DownloadManifestException {
    EucaS3Client s3Client = null;
    try {
        try {
            s3Client = s3ClientsPool.borrowObject();
        } catch (Exception ex) {
            throw new DownloadManifestException("Can't borrow s3Client from the pool");
        }
        // prepare to do pre-signed urls
        if (!urlForNc)
            s3Client.refreshEndpoint(true);
        else
            s3Client.refreshEndpoint();

        Date expiration = new Date();
        long msec = expiration.getTime() + 1000 * 60 * 60 * expirationHours;
        expiration.setTime(msec);

        // check if download-manifest already exists
        if (objectExist(s3Client, DOWNLOAD_MANIFEST_BUCKET_NAME, DOWNLOAD_MANIFEST_PREFIX + manifestName)) {
            LOG.debug("Manifest '" + (DOWNLOAD_MANIFEST_PREFIX + manifestName)
                    + "' is already created and has not expired. Skipping creation");
            URL s = s3Client.generatePresignedUrl(DOWNLOAD_MANIFEST_BUCKET_NAME,
                    DOWNLOAD_MANIFEST_PREFIX + manifestName, expiration, HttpMethod.GET);
            return String.format("%s://imaging@%s%s?%s", s.getProtocol(), s.getAuthority(), s.getPath(),
                    s.getQuery());
        } else {
            LOG.debug("Manifest '" + (DOWNLOAD_MANIFEST_PREFIX + manifestName) + "' does not exist");
        }

        UrlValidator urlValidator = new UrlValidator();

        final String manifest = baseManifest.getManifest();
        if (manifest == null) {
            throw new DownloadManifestException("Can't generate download manifest from null base manifest");
        }
        final Document inputSource;
        final XPath xpath;
        Function<String, String> xpathHelper;
        DocumentBuilder builder = XMLParser.getDocBuilder();
        inputSource = builder.parse(new ByteArrayInputStream(manifest.getBytes()));
        if (!"manifest".equals(inputSource.getDocumentElement().getNodeName())) {
            LOG.error("Expected image manifest. Got " + nodeToString(inputSource, false));
            throw new InvalidBaseManifestException("Base manifest does not have manifest element");
        }

        StringBuilder signatureSrc = new StringBuilder();
        Document manifestDoc = builder.newDocument();
        Element root = (Element) manifestDoc.createElement("manifest");
        manifestDoc.appendChild(root);
        Element el = manifestDoc.createElement("version");
        el.appendChild(manifestDoc.createTextNode("2014-01-14"));
        signatureSrc.append(nodeToString(el, false));
        root.appendChild(el);
        el = manifestDoc.createElement("file-format");
        el.appendChild(manifestDoc.createTextNode(baseManifest.getManifestType().getFileType().toString()));
        root.appendChild(el);
        signatureSrc.append(nodeToString(el, false));

        xpath = XPathFactory.newInstance().newXPath();
        xpathHelper = new Function<String, String>() {
            @Override
            public String apply(String input) {
                try {
                    return (String) xpath.evaluate(input, inputSource, XPathConstants.STRING);
                } catch (XPathExpressionException ex) {
                    return null;
                }
            }
        };

        // extract keys
        // TODO: move this?
        if (baseManifest.getManifestType().getFileType() == FileType.BUNDLE) {
            String encryptedKey = xpathHelper.apply("/manifest/image/ec2_encrypted_key");
            String encryptedIV = xpathHelper.apply("/manifest/image/ec2_encrypted_iv");
            String size = xpathHelper.apply("/manifest/image/size");
            EncryptedKey encryptKey = reEncryptKey(new EncryptedKey(encryptedKey, encryptedIV), keyToUse);
            el = manifestDoc.createElement("bundle");
            Element key = manifestDoc.createElement("encrypted-key");
            key.appendChild(manifestDoc.createTextNode(encryptKey.getKey()));
            Element iv = manifestDoc.createElement("encrypted-iv");
            iv.appendChild(manifestDoc.createTextNode(encryptKey.getIV()));
            el.appendChild(key);
            el.appendChild(iv);
            Element sizeEl = manifestDoc.createElement("unbundled-size");
            sizeEl.appendChild(manifestDoc.createTextNode(size));
            el.appendChild(sizeEl);
            root.appendChild(el);
            signatureSrc.append(nodeToString(el, false));
        }

        el = manifestDoc.createElement("image");
        String bundleSize = xpathHelper.apply(baseManifest.getManifestType().getSizePath());
        if (bundleSize == null) {
            throw new InvalidBaseManifestException("Base manifest does not have size element");
        }
        Element size = manifestDoc.createElement("size");
        size.appendChild(manifestDoc.createTextNode(bundleSize));
        el.appendChild(size);

        Element partsEl = manifestDoc.createElement("parts");
        el.appendChild(partsEl);
        // parts
        NodeList parts = (NodeList) xpath.evaluate(baseManifest.getManifestType().getPartsPath(), inputSource,
                XPathConstants.NODESET);
        if (parts == null) {
            throw new InvalidBaseManifestException("Base manifest does not have parts");
        }

        for (int i = 0; i < parts.getLength(); i++) {
            Node part = parts.item(i);
            String partIndex = part.getAttributes().getNamedItem("index").getNodeValue();
            String partKey = ((Node) xpath.evaluate(baseManifest.getManifestType().getPartUrlElement(), part,
                    XPathConstants.NODE)).getTextContent();
            String partDownloadUrl = partKey;
            if (baseManifest.getManifestType().signPartUrl()) {
                GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(
                        baseManifest.getBaseBucket(), partKey, HttpMethod.GET);
                generatePresignedUrlRequest.setExpiration(expiration);
                URL s = s3Client.generatePresignedUrl(generatePresignedUrlRequest);
                partDownloadUrl = s.toString();
            } else {
                // validate url per EUCA-9144
                if (!urlValidator.isEucalyptusUrl(partDownloadUrl))
                    throw new DownloadManifestException(
                            "Some parts in the manifest are not stored in the OS. Its location is outside Eucalyptus:"
                                    + partDownloadUrl);
            }
            Node digestNode = null;
            if (baseManifest.getManifestType().getDigestElement() != null)
                digestNode = ((Node) xpath.evaluate(baseManifest.getManifestType().getDigestElement(), part,
                        XPathConstants.NODE));
            Element aPart = manifestDoc.createElement("part");
            Element getUrl = manifestDoc.createElement("get-url");
            getUrl.appendChild(manifestDoc.createTextNode(partDownloadUrl));
            aPart.setAttribute("index", partIndex);
            aPart.appendChild(getUrl);
            if (digestNode != null) {
                NamedNodeMap nm = digestNode.getAttributes();
                if (nm == null)
                    throw new DownloadManifestException(
                            "Some parts in manifest don't have digest's verification algorithm");
                Element digest = manifestDoc.createElement("digest");
                digest.setAttribute("algorithm", nm.getNamedItem("algorithm").getTextContent());
                digest.appendChild(manifestDoc.createTextNode(digestNode.getTextContent()));
                aPart.appendChild(digest);
            }
            partsEl.appendChild(aPart);
        }
        root.appendChild(el);
        signatureSrc.append(nodeToString(el, false));
        String signatureData = signatureSrc.toString();
        Element signature = manifestDoc.createElement("signature");
        signature.setAttribute("algorithm", "RSA-SHA256");
        signature.appendChild(manifestDoc
                .createTextNode(Signatures.SHA256withRSA.trySign(Eucalyptus.class, signatureData.getBytes())));
        root.appendChild(signature);
        String downloadManifest = nodeToString(manifestDoc, true);
        // TODO: move this ?
        createManifestsBucketIfNeeded(s3Client);
        putManifestData(s3Client, DOWNLOAD_MANIFEST_BUCKET_NAME, DOWNLOAD_MANIFEST_PREFIX + manifestName,
                downloadManifest, expiration);
        // generate pre-sign url for download manifest
        URL s = s3Client.generatePresignedUrl(DOWNLOAD_MANIFEST_BUCKET_NAME,
                DOWNLOAD_MANIFEST_PREFIX + manifestName, expiration, HttpMethod.GET);
        return String.format("%s://imaging@%s%s?%s", s.getProtocol(), s.getAuthority(), s.getPath(),
                s.getQuery());
    } catch (Exception ex) {
        LOG.error("Got an error", ex);
        throw new DownloadManifestException("Can't generate download manifest");
    } finally {
        if (s3Client != null)
            try {
                s3ClientsPool.returnObject(s3Client);
            } catch (Exception e) {
                // sad, but let's not break instances run
                LOG.warn("Could not return s3Client to the pool");
            }
    }
}

From source file:de.codesourcery.spring.contextrewrite.XMLRewrite.java

private static Rule wrap(InsertAttributeRule r) {
    return new Rule(r.xpath(), r.id()) {
        @Override/*from  w  w w  .ja  v  a 2 s .  co m*/
        public void apply(Document document, Node matchedNode) throws Exception {
            final Attr attribute = document.createAttribute(r.name());
            attribute.setValue(r.value());
            matchedNode.getAttributes().setNamedItem(attribute);
        }

        @Override
        public String toString() {
            return "INSERT ATTRIBUTE: " + r.xpath() + " with " + r.name() + "=" + r.value();
        }
    };
}

From source file:Main.java

private static void prettyPrintLoop(Node node, StringBuilder string, String indentation) {
    if (node == null) {
        return;// ww w.ja  v a 2  s.  c o m
    }

    int type = node.getNodeType();
    switch (type) {
    case Node.DOCUMENT_NODE:
        string.append("\n");
        prettyPrintLoop(node.getChildNodes(), string, indentation + "\t");
        break;

    case Node.ELEMENT_NODE:
        string.append(indentation);
        string.append("<");
        string.append(node.getNodeName());

        Attr[] attributes;
        if (node.getAttributes() != null) {
            int length = node.getAttributes().getLength();
            attributes = new Attr[length];
            for (int loopIndex = 0; loopIndex < length; loopIndex++) {
                attributes[loopIndex] = (Attr) node.getAttributes().item(loopIndex);
            }
        } else {
            attributes = new Attr[0];
        }

        for (Attr attribute : attributes) {
            string.append(" ");
            string.append(attribute.getNodeName());
            string.append("=\"");
            string.append(attribute.getNodeValue());
            string.append("\"");
        }

        string.append(">\n");

        prettyPrintLoop(node.getChildNodes(), string, indentation + "\t");

        string.append(indentation);
        string.append("</");
        string.append(node.getNodeName());
        string.append(">\n");

        break;

    case Node.TEXT_NODE:
        string.append(indentation);
        string.append(node.getNodeValue().trim());
        string.append("\n");
        break;

    case Node.PROCESSING_INSTRUCTION_NODE:
        string.append(indentation);
        string.append("<?");
        string.append(node.getNodeName());
        String text = node.getNodeValue();
        if (text != null && text.length() > 0) {
            string.append(text);
        }
        string.append("?>\n");
        break;

    case Node.CDATA_SECTION_NODE:
        string.append(indentation);
        string.append("<![CDATA[");
        string.append(node.getNodeValue());
        string.append("]]>");
        break;
    }
}

From source file:com.puppycrawl.tools.checkstyle.XDocsPagesTest.java

private static void validateUsageExample(String fileName, String sectionName, Node subSection) {
    final String text = subSection.getTextContent().replace("Checkstyle Style", "").replace("Google Style", "")
            .replace("Sun Style", "").trim();

    Assert.assertTrue(/*w  w  w  .  j a  va 2s .  c om*/
            fileName + " section '" + sectionName + "' has unknown text in 'Example of Usage': " + text,
            text.isEmpty());

    for (Node node : findChildElementsByTag(subSection, "a")) {
        final String url = node.getAttributes().getNamedItem("href").getTextContent();
        final String linkText = node.getTextContent().trim();
        String expectedUrl = null;

        if ("Checkstyle Style".equals(linkText)) {
            expectedUrl = "https://github.com/search?q=" + "path%3Aconfig+filename%3Acheckstyle_checks.xml+"
                    + "repo%3Acheckstyle%2Fcheckstyle+" + sectionName;
        } else if ("Google Style".equals(linkText)) {
            expectedUrl = "https://github.com/search?q="
                    + "path%3Asrc%2Fmain%2Fresources+filename%3Agoogle_checks.xml+"
                    + "repo%3Acheckstyle%2Fcheckstyle+" + sectionName;
        } else if ("Sun Style".equals(linkText)) {
            expectedUrl = "https://github.com/search?q="
                    + "path%3Asrc%2Fmain%2Fresources+filename%3Asun_checks.xml+"
                    + "repo%3Acheckstyle%2Fcheckstyle+" + sectionName;
        }

        Assert.assertEquals(fileName + " section '" + sectionName + "' should have matching url", expectedUrl,
                url);
    }
}

From source file:Main.java

public static String domNode2String(Node node, boolean escapeStrings) {
    String ret = "";
    switch (node.getNodeType()) {

    case Node.DOCUMENT_NODE:
        // recurse on each child
        NodeList nodes = node.getChildNodes();
        if (nodes != null) {
            for (int i = 0; i < nodes.getLength(); i++) {
                ret += domNode2String(nodes.item(i), escapeStrings);
            }//  w  w  w  . j  av  a2 s .  com
        }
        break;

    case Node.ELEMENT_NODE:
        String name = node.getNodeName();
        ret += "<" + name;
        NamedNodeMap attributes = node.getAttributes();
        for (int i = 0; i < attributes.getLength(); i++) {
            Node current = attributes.item(i);
            ret += " " + current.getNodeName() + "=\""
                    + ((escapeStrings) ? escapeStringForXML(current.getNodeValue()) : current.getNodeValue())
                    + "\"";
        }
        ret += ">";

        // recurse on each child
        NodeList children = node.getChildNodes();
        if (children != null) {
            for (int i = 0; i < children.getLength(); i++) {
                ret += domNode2String(children.item(i), escapeStrings);
            }
        }

        ret += "</" + name + ">";
        break;

    case Node.TEXT_NODE:
        ret += (escapeStrings) ? escapeStringForXML(node.getNodeValue()) : node.getNodeValue();
        break;
    case Node.COMMENT_NODE:
        ret += "<!--" + node.getNodeValue() + "-->";
        break;
    }
    return ret;
}