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:com.photon.phresco.framework.commons.QualityUtil.java

private static void appendCollectionProp(Document document, Node elementProp, String contextType,
        String contextPostData) { // collection append in prop
    String argumentValue = null;/* ww w . ja v a 2 s . c  o  m*/
    if (contextType.equals(FrameworkConstants.POST)) {
        argumentValue = contextPostData;
    }
    Node collectionProp = document.createElement("collectionProp");
    NamedNodeMap attributes = collectionProp.getAttributes();
    attributes.setNamedItem(createAttribute(document, "name", "Arguments.arguments"));

    Node subElementProp = document.createElement("elementProp");
    NamedNodeMap subElementAttributes = subElementProp.getAttributes();
    subElementAttributes.setNamedItem(createAttribute(document, "name", ""));
    subElementAttributes.setNamedItem(createAttribute(document, "elementType", "HTTPArgument"));
    collectionProp.appendChild(subElementProp);
    appendTypeProp(document, subElementProp, "boolProp", "HTTPArgument.always_encode", "false");
    appendTypeProp(document, subElementProp, "stringProp", "Argument.value", argumentValue);
    appendTypeProp(document, subElementProp, "stringProp", "Argument.metadata", "=");
    appendTypeProp(document, subElementProp, "boolProp", "HTTPArgument.use_equals", "true");

    elementProp.setTextContent(null);
    elementProp.appendChild(collectionProp);
}

From source file:moskitt4me.repositoryClient.core.util.RepositoryClientUtil.java

public static void setInitialLocationType(RepositoryLocation location) {

    FTPClient client = RepositoryClientUtil.connect(location, false);

    if (client != null) {

        String tempDir = "";

        try {//w w w  .ja  v a  2s  .c  om
            String eclipseInstallationDirectory = Platform.getInstallLocation().getURL().getPath();
            tempDir = RepositoryClientUtil.createFolder(eclipseInstallationDirectory + "tmp", 0);

            FTPFile[] files = client.listFiles();

            if (files.length > 0) {
                String fileName = files[0].getName();
                String destination = tempDir + "/" + fileName;
                FileOutputStream fos = new FileOutputStream(destination);
                client.retrieveFile(fileName, fos);
                fos.close();

                extractZipFile(tempDir, fileName);

                Document doc = getDocument(tempDir + "/rasset.xml");
                if (doc != null) {
                    Node ntype = doc.getElementsByTagName("type").item(0);
                    String type = ntype.getAttributes().getNamedItem("value").getNodeValue();
                    if (type != null) {
                        if (isTechnicalFragment(type)) {
                            location.setType("Technical");
                        } else {
                            location.setType("Conceptual");
                        }
                    }
                }
            } else {
                location.setType("Empty");
            }
        } catch (Exception e) {

        } finally {
            RepositoryClientUtil.disconnect(client);
            if (location.getType().equals("")) {
                location.setType("Empty");
            }
            if (!tempDir.equals("")) {
                RepositoryClientUtil.removeFolder(new File(tempDir));
            }
        }
    }
}

From source file:Main.java

/**
 * Copies the source tree into the specified place in a destination
 * tree. The source node and its children are appended as children
 * of the destination node./*from w w w .  j  ava  2  s .  c  o m*/
 * <p>
 * <em>Note:</em> This is an iterative implementation.
 */
public static void copyInto(Node src, Node dest) throws DOMException {

    // get node factory
    Document factory = dest.getOwnerDocument();
    boolean domimpl = factory instanceof DocumentImpl;

    // placement variables
    Node start = src;
    Node parent = src;
    Node place = src;

    // traverse source tree
    while (place != null) {

        // copy this node
        Node node = null;
        int type = place.getNodeType();
        switch (type) {
        case Node.CDATA_SECTION_NODE: {
            node = factory.createCDATASection(place.getNodeValue());
            break;
        }
        case Node.COMMENT_NODE: {
            node = factory.createComment(place.getNodeValue());
            break;
        }
        case Node.ELEMENT_NODE: {
            Element element = factory.createElement(place.getNodeName());
            node = element;
            NamedNodeMap attrs = place.getAttributes();
            int attrCount = attrs.getLength();
            for (int i = 0; i < attrCount; i++) {
                Attr attr = (Attr) attrs.item(i);
                String attrName = attr.getNodeName();
                String attrValue = attr.getNodeValue();
                element.setAttribute(attrName, attrValue);
                if (domimpl && !attr.getSpecified()) {
                    ((AttrImpl) element.getAttributeNode(attrName)).setSpecified(false);
                }
            }
            break;
        }
        case Node.ENTITY_REFERENCE_NODE: {
            node = factory.createEntityReference(place.getNodeName());
            break;
        }
        case Node.PROCESSING_INSTRUCTION_NODE: {
            node = factory.createProcessingInstruction(place.getNodeName(), place.getNodeValue());
            break;
        }
        case Node.TEXT_NODE: {
            node = factory.createTextNode(place.getNodeValue());
            break;
        }
        default: {
            throw new IllegalArgumentException(
                    "can't copy node type, " + type + " (" + node.getNodeName() + ')');
        }
        }
        dest.appendChild(node);

        // iterate over children
        if (place.hasChildNodes()) {
            parent = place;
            place = place.getFirstChild();
            dest = node;
        }

        // advance
        else {
            place = place.getNextSibling();
            while (place == null && parent != start) {
                place = parent.getNextSibling();
                parent = parent.getParentNode();
                dest = dest.getParentNode();
            }
        }

    }

}

From source file:cz.muni.fi.mir.mathmlunificator.MathMLUnificator.java

/**
 * <p>//from ww  w .  java 2 s.c  om
 * Determine the unification level of the {@link Node} and max level of the
 * unification series. If the node does not possess the appropriate
 * unification level XML attributes the {@link UnificationLevel} object will
 * indicate that by having both {@link UnificationLevel#nodeLevel} and
 * {@link UnificationLevel#maxLevel} set to {@code null}.
 * </p>
 * <p>
 * <strong>Please note that only existance of valid unification level XML
 * attributes is tested. If you want to be sure the node is a valid unified
 * math node use {@link #isUnifiedMathNode(org.w3c.dom.Node)}!</strong>
 * </p>
 *
 * @param node The node to determine the unification level for.
 * @return The node's unification level represented by an instance of
 * {@link UnificationLevel}.
 * @see #unifyMathMLNode(org.w3c.dom.Node, boolean)
 */
public static UnificationLevel getNodeUnificationLevel(Node node) {

    Integer uniLevelValue = 0;
    Integer maxLevelValue = 0;

    if (node != null && node.getNodeType() == Node.ELEMENT_NODE) {
        // Get unification level attributes if exists
        Node uniLevel = node.getAttributes().getNamedItemNS(UNIFIED_MATHML_NS, UNIFIED_MATHML_LEVEL_ATTR);
        Node maxLevel = node.getAttributes().getNamedItemNS(UNIFIED_MATHML_NS, UNIFIED_MATHML_MAX_LEVEL_ATTR);
        if (uniLevel != null && uniLevel.getNodeType() == Node.ATTRIBUTE_NODE && maxLevel != null
                && maxLevel.getNodeType() == Node.ATTRIBUTE_NODE) {
            try {
                uniLevelValue = Integer.parseInt(((Attr) uniLevel).getTextContent());
                maxLevelValue = Integer.parseInt(((Attr) maxLevel).getTextContent());
                if (uniLevelValue > 0 && maxLevelValue > 0) {
                    return new UnificationLevel(uniLevelValue, maxLevelValue);
                }
            } catch (NumberFormatException ex) {
                return new UnificationLevel();
            }
        }
    }

    return new UnificationLevel();

}

From source file:be.ibridge.kettle.core.XMLHandler.java

/**
 * Get all the attributes in a certain node (on the root level)
 * @param node The node to examine/*from  w w w.j  a  va 2s  . com*/
 * @return an array of strings containing the names of the attributes.
 */
public static String[] getNodeAttributes(Node node) {
    NamedNodeMap nnm = node.getAttributes();
    if (nnm != null) {
        String attributes[] = new String[nnm.getLength()];
        for (int i = 0; i < nnm.getLength(); i++) {
            Node attr = nnm.item(i);
            attributes[i] = attr.getNodeName();
        }
        return attributes;
    }
    return null;

}

From source file:edu.stanford.muse.slant.CustomSearchHelper.java

private static void deleteCSE(String authtoken, String cseName)
        throws IOException, ParserConfigurationException, XPathExpressionException {
    // see http://code.google.com/apis/customsearch/docs/api.html

    String url = "http://www.google.com/cse/api/default/annotations/?num=5000"; // w/o num param, returns only top 20 results
    GetMethod get = new GetMethod(url);
    get.addRequestHeader("Content-type", "text/xml");
    get.addRequestHeader("Authorization", "GoogleLogin auth=" + authtoken);
    int statusCode = new HttpClient().executeMethod(get);
    if (statusCode != HttpStatus.SC_OK) {
        log.warn(/*from w ww  . j  a  va 2s.  com*/
                "Unable to read Google CSE annotations, and therefore unable to delete existing annotations! HTTP status = "
                        + statusCode);
        return;
    }

    /* sample xml: 
    <?xml version="1.0" encoding="UTF-8" ?>
    <Annotations start="0" num="2182" total="2182">
    <Annotation about="visualizing.stanford.edu/*" score="0.000810373" timestamp="0x0004b2a4c7d271fd" href="Chp2aXN1YWxpemluZy5zdGFuZm9yZC5lZHUvKhD948m-zNSsAg">
    <Label name="_cse_testengine" />
    <AdditionalData attribute="original_url" value="http://visualizing.stanford.edu/*" />
       </Annotation>
    ...
     */

    // parse xml and get href's for the annotations for this cse.
    String responseBody = IOUtils.toString(get.getResponseBodyAsStream(), "UTF-8");
    InputSource is = new InputSource(new StringReader(responseBody));
    XPath xpath = XPathFactory.newInstance().newXPath();
    String expression = "/Annotations/Annotation/Label[@name='_cse_" + cseName + "']";
    NodeList nodes = (NodeList) xpath.evaluate(expression, is, XPathConstants.NODESET);
    List<String> hrefs = new ArrayList<String>();
    log.info(nodes.getLength() + " existing annotation(s) for search engine " + cseName
            + ". They will be deleted.");
    for (int i = 0; i < nodes.getLength(); i++) {
        Node label = nodes.item(i);
        Node annotation = label.getParentNode();
        Node hrefNode = annotation.getAttributes().getNamedItem("href");
        String href = hrefNode.getNodeValue();
        hrefs.add(href);
    }

    // hrefs now has all the existing href's for this CSE. send a remove command with these href's.
    StringBuilder removeXML = new StringBuilder("<Batch><Remove><Annotations>");
    int batchCount = 0;
    for (Iterator<String> it = hrefs.iterator(); it.hasNext();) {
        String href = it.next();
        removeXML.append(" <Annotation href=\"" + href + "\" />");
        batchCount++;
        if (batchCount == ANNOTATION_UPLOAD_BATCH_SIZE || !it.hasNext()) {
            removeXML.append("</Annotations></Remove></Batch>");
            boolean success = pushAnnotations(authtoken, removeXML.toString());
            if (!success)
                log.warn("Failed to delete " + batchCount + " existing annotations for search engine " + cseName
                        + " xml = " + removeXML);
            else
                log.info("Successfully deleted " + batchCount + " existing annotations for search engine "
                        + cseName);
            removeXML = new StringBuilder("<Batch><Remove><Annotations>");
            batchCount = 0;
        }
    }
}

From source file:edu.stanford.epad.epadws.queries.XNATQueries.java

public static String getXNATSubjectFieldValue(String sessionID, String xnatSubjectID, String fieldName) {
    HttpClient client = new HttpClient();
    GetMethod method = new GetMethod(XNATQueryUtil.buildSubjectURL(xnatSubjectID) + "?format=xml");
    int xnatStatusCode;
    //log.info("Calling XNAT Subject info:" + XNATQueryUtil.buildSubjectURL(xnatSubjectID) + "?format=xml");
    method.setRequestHeader("Cookie", "JSESSIONID=" + sessionID);

    try {/*from w  ww.  j  a  v a2s . c om*/
        xnatStatusCode = client.executeMethod(method);
        String xmlResp = method.getResponseBodyAsString(10000);
        log.debug(xmlResp);
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        InputStream is = new StringBufferInputStream(xmlResp);
        Document doc = db.parse(is);
        doc.getDocumentElement().normalize();
        NodeList nodes = doc.getElementsByTagName("xnat:field");
        String value = "";
        String subjfieldname = "";
        for (int i = 0; i < nodes.getLength(); i++) {
            Node node = nodes.item(i);
            value = node.getTextContent();
            if (value != null)
                value = value.replace('\n', ' ').trim();
            NamedNodeMap attrs = node.getAttributes();
            String attrName = null;
            for (int j = 0; attrs != null && j < attrs.getLength(); j++) {
                attrName = attrs.item(j).getNodeName();
                subjfieldname = attrs.item(j).getNodeValue();
                if (fieldName.equalsIgnoreCase(subjfieldname))
                    return value;
            }
        }
        return value;
    } catch (Exception e) {
        log.warning(
                "Warning: error performing XNAT subject query " + XNATQueryUtil.buildSubjectURL(xnatSubjectID),
                e);
        xnatStatusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    } finally {
        method.releaseConnection();
    }
    return null;
}

From source file:Main.java

private static void renderNode(StringBuffer sb, Node node) {
    if (node == null) {
        sb.append("null");
        return;/*from w  ww . ja v a2 s  . c  om*/
    }
    switch (node.getNodeType()) {

    case Node.DOCUMENT_NODE:
        sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
        Node root = ((Document) node).getDocumentElement();
        renderNode(sb, root);
        break;

    case Node.ELEMENT_NODE:
        String name = getNodeNameWithNamespace(node);
        NamedNodeMap attributes = node.getAttributes();
        if (attributes.getLength() == 0) {
            sb.append("<" + name + ">");
        } else {
            sb.append("<" + name + " ");
            int attrlen = attributes.getLength();
            for (int i = 0; i < attrlen; i++) {
                Node attr = attributes.item(i);
                String attrName = getNodeNameWithNamespace(attr);
                sb.append(attrName + "=\"" + escapeChars(attr.getNodeValue()));
                if (i < attrlen - 1)
                    sb.append("\" ");
                else
                    sb.append("\">");
            }
        }
        NodeList children = node.getChildNodes();
        if (children != null) {
            for (int i = 0; i < children.getLength(); i++) {
                renderNode(sb, children.item(i));
            }
        }
        sb.append("</" + name + ">");
        break;

    case Node.TEXT_NODE:
        sb.append(escapeChars(node.getNodeValue()));
        break;

    case Node.CDATA_SECTION_NODE:
        sb.append("<![CDATA[" + node.getNodeValue() + "]]>");
        break;

    case Node.PROCESSING_INSTRUCTION_NODE:
        sb.append("<?" + node.getNodeName() + " " + escapeChars(node.getNodeValue()) + "?>");
        break;

    case Node.ENTITY_REFERENCE_NODE:
        sb.append("&" + node.getNodeName() + ";");
        break;

    case Node.DOCUMENT_TYPE_NODE:
        // Ignore document type nodes
        break;

    case Node.COMMENT_NODE:
        sb.append("<!--" + node.getNodeValue() + "-->");
        break;
    }
    return;
}

From source file:Main.java

private static String toString(Node node, int level, boolean indent) {

    StringBuilder nodeBuilder = new StringBuilder();

    switch (node.getNodeType()) {
    case Node.TEXT_NODE:
        if (indent) {
            nodeBuilder.append(setIndent(level));
        }//  ww  w.jav  a 2s. c om
        nodeBuilder.append(node.getNodeValue());
        if (indent) {
            nodeBuilder.append("\n");
        }
        break;
    case Node.ELEMENT_NODE:

        NamedNodeMap attributeMap;
        NodeList childList;

        if (indent) {
            nodeBuilder.append(setIndent(level));
        }
        nodeBuilder.append("<");
        nodeBuilder.append(((Element) node).getTagName());

        attributeMap = node.getAttributes();
        for (int loop = 0; loop < attributeMap.getLength(); loop++) {
            nodeBuilder.append(" ");
            nodeBuilder.append(attributeMap.item(loop).getNodeName());
            nodeBuilder.append("=\"");
            nodeBuilder.append(attributeMap.item(loop).getNodeValue());
            nodeBuilder.append("\"");
        }

        if (node.hasChildNodes()) {
            nodeBuilder.append(">");
            if (indent) {
                nodeBuilder.append("\n");
            }

            childList = node.getChildNodes();
            for (int loop = 0; loop < childList.getLength(); loop++) {
                nodeBuilder.append(toString(childList.item(loop), level + 1, indent));
            }

            if (indent) {
                nodeBuilder.append(setIndent(level));
            }
            nodeBuilder.append("</");
            nodeBuilder.append(((Element) node).getTagName());
            nodeBuilder.append(">");
            if (indent) {
                nodeBuilder.append("\n");
            }
        } else {
            nodeBuilder.append("/>");
            if (indent) {
                nodeBuilder.append("\n");
            }
        }
        break;
    default:
        nodeBuilder.append("<Unkown Node Type (");
        nodeBuilder.append(node.getNodeType());
        nodeBuilder.append(")/>");
        if (indent) {
            nodeBuilder.append("\n");
        }
    }

    return nodeBuilder.toString();
}

From source file:com.connexta.arbitro.attr.xacml3.AttributeDesignator.java

/**
 * Creates a new <code>AttributeDesignator</code> based on the DOM root of the XML data.
 *
 * @param root  the DOM root of the AttributeDesignatorType XML type
 * @return the designator//  ww w  . ja va  2 s. c  o m
 * @throws ParsingException if the AttributeDesignatorType was invalid
 */
public static AttributeDesignator getInstance(Node root) throws ParsingException {

    URI type = null;
    URI id = null;
    String issuer = null;
    URI category = null;
    boolean mustBePresent = false;

    // First check to be sure the node passed is indeed a AttributeDesignator node.
    String tagName = DOMHelper.getLocalName(root);
    if (!tagName.equals("AttributeDesignator")) {
        throw new ParsingException(
                "AttributeDesignator cannot be constructed using " + "type: " + DOMHelper.getLocalName(root));
    }

    NamedNodeMap attrs = root.getAttributes();

    try {
        id = new URI(attrs.getNamedItem("AttributeId").getNodeValue());
    } catch (Exception e) {
        throw new ParsingException("Required AttributeId missing in " + "AttributeDesignator", e);
    }

    try {
        category = new URI(attrs.getNamedItem("Category").getNodeValue());
    } catch (Exception e) {
        throw new ParsingException("Required Category missing in " + "AttributeDesignator", e);
    }

    try {
        String nodeValue = attrs.getNamedItem("MustBePresent").getNodeValue();
        if ("true".equals(nodeValue)) {
            mustBePresent = true;
        }
    } catch (Exception e) {
        throw new ParsingException("Required MustBePresent missing in " + "AttributeDesignator", e);
    }

    try {
        type = new URI(attrs.getNamedItem("DataType").getNodeValue());
    } catch (Exception e) {
        throw new ParsingException("Required DataType missing in " + "AttributeDesignator", e);
    }

    try {
        Node node = attrs.getNamedItem("Issuer");
        if (node != null) {
            issuer = node.getNodeValue();
        }
    } catch (Exception e) {
        throw new ParsingException("Error parsing AttributeDesignator " + "optional attributes", e);
    }

    return new AttributeDesignator(type, id, mustBePresent, issuer, category);
}