Example usage for org.w3c.dom Element hasAttributes

List of usage examples for org.w3c.dom Element hasAttributes

Introduction

In this page you can find the example usage for org.w3c.dom Element hasAttributes.

Prototype

public boolean hasAttributes();

Source Link

Document

Returns whether this node (if it is an element) has any attributes.

Usage

From source file:Main.java

protected static String nodeToString(Node node, Set<String> parentPrefixes, String namespaceURI)
        throws Exception {
    StringBuilder b = new StringBuilder();

    if (node == null) {
        return "";
    }/*from ww w .j  av  a2s .  c  om*/

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

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

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

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

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

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

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

    } else if (node.getNodeValue() != null) {

        b.append(encodeText(node.getNodeValue()));
    }

    return b.toString();
}

From source file:Main.java

protected static String nodeToString(Node node, Set<String> parentPrefixes, String namespaceURI)
        throws Exception {
    StringBuilder b = new StringBuilder();

    if (node == null) {
        return "";
    }//from   www .  j a  v  a2  s  . co  m

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

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

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

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

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

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

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

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

    return b.toString();
}

From source file:com.concursive.connect.web.modules.api.beans.Transaction.java

/**
 * Builds a list of TransactionItems from XML
 *
 * @param transactionElement Description of Parameter
 *//*  w  w  w .  j  a  va2s. com*/
public void build(Element transactionElement) {
    if (transactionElement.hasAttributes()) {
        // Use client transaction id
        if (transactionElement.hasAttribute("id")) {
            this.setId(transactionElement.getAttribute("id"));
        }
        // Use a different processor than the default
        if (transactionElement.hasAttribute("processor")) {

        }
    }
    // The default processor
    ArrayList<Element> objectElements = new ArrayList<Element>();
    XMLUtils.getAllChildren(transactionElement, objectElements);
    LOG.debug("Transaction items: " + objectElements.size());
    for (Element objectElement : objectElements) {
        TransactionItem thisItem = new TransactionItem(objectElement, packetContext, transactionContext);
        if (thisItem.getName().equals("meta")) {
            LOG.trace("Meta data found");
            meta = (TransactionMeta) thisItem.getObject();
        } else {
            LOG.trace("Adding transaction item: " + thisItem.getName());
            this.add(thisItem);
        }
    }
}

From source file:com.sqewd.os.maracache.core.Config.java

private ConfigPath load(ConfigNode parent, Element elm) throws ConfigException {
    if (parent instanceof ConfigPath) {
        // Check if there are any attributes.
        // Attributes are treated as Value nodes.
        if (elm.hasAttributes()) {
            NamedNodeMap map = elm.getAttributes();
            if (map.getLength() > 0) {
                for (int ii = 0; ii < map.getLength(); ii++) {
                    Node n = map.item(ii);
                    ((ConfigPath) parent).addValueNode(n.getNodeName(), n.getNodeValue());
                }/*  ww w.  j a  va 2  s. com*/
            }
        }
        if (elm.hasChildNodes()) {
            NodeList children = elm.getChildNodes();
            for (int ii = 0; ii < children.getLength(); ii++) {
                Node cn = children.item(ii);
                if (cn.getNodeType() == Node.ELEMENT_NODE) {
                    Element e = (Element) cn;
                    if (e.hasChildNodes()) {
                        int nc = 0;
                        for (int jj = 0; jj < e.getChildNodes().getLength(); jj++) {
                            Node ccn = e.getChildNodes().item(jj);
                            // Read the text node if there is any.
                            if (ccn.getNodeType() == Node.TEXT_NODE) {
                                String n = e.getNodeName();
                                String v = ccn.getNodeValue();
                                if (!StringUtils.isEmpty(v.trim()))
                                    ((ConfigPath) parent).addValueNode(n, v);
                                nc++;
                            }
                        }
                        // Make sure this in not a text only node.
                        if (e.getChildNodes().getLength() > nc) {
                            // Check if this is a parameter node. Parameters are treated differently.
                            if (e.getNodeName().compareToIgnoreCase(ConfigParams.NODE_NAME) == 0) {
                                ConfigParams cp = ((ConfigPath) parent).addParamNode();
                                setParams(cp, e);
                            } else {
                                ConfigPath cp = ((ConfigPath) parent).addPathNode(e.getNodeName());
                                load(cp, e);
                            }
                        }
                    }
                }
            }
        }
    }
    return (ConfigPath) parent;
}

From source file:it.grid.storm.namespace.config.xml.XMLNamespaceLoader.java

private String getNamespaceSchemaFileName() {

    String schemaName = it.grid.storm.config.Configuration.getInstance().getNamespaceSchemaFilename();

    if (schemaName.equals("Schema UNKNOWN!")) {

        schemaName = "namespace.xsd";
        String namespaceFN = getNamespaceFileName();
        File namespaceFile = new File(namespaceFN);
        if (namespaceFile.exists()) {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            try {
                DocumentBuilder builder = factory.newDocumentBuilder();
                Document doc = builder.parse(namespaceFN);
                Element rootElement = doc.getDocumentElement();
                String tagName = rootElement.getTagName();
                if (tagName.equals("namespace")) {
                    if (rootElement.hasAttributes()) {
                        String value = rootElement.getAttribute("xsi:noNamespaceSchemaLocation");
                        if ((value != null) && (value.length() > 0)) {
                            schemaName = value;
                            // log.debug("namespace schema is : " + schemaName);
                        }//  ww w. java2 s .  c  o m
                    } else {
                        log.error(namespaceFN + " don't have a valid root element attributes");
                    }
                } else {
                    log.error(namespaceFN + "  don't have a valid root element.");
                }

            } catch (ParserConfigurationException e) {
                log.error("Error while parsing " + namespaceFN + e.getMessage());
            } catch (SAXException e) {
                log.error("Error while parsing " + namespaceFN + e.getMessage());
            } catch (IOException e) {
                log.error("Error while parsing " + namespaceFN + e.getMessage());
            }
        }
    }

    return schemaName;

}

From source file:com.alfaariss.oa.util.configuration.ConfigurationManager.java

private synchronized Element getSubSectionByID(Element eRootSection, String sSectionType, String sSectionID) {
    assert eRootSection != null : "Suplied root section is empty";
    //split sectionID (id=ticket) to key/value pair

    int iFirstEquals = sSectionID.indexOf("=");
    if (iFirstEquals == -1) {
        StringBuffer sbError = new StringBuffer("Invalid section ID (must contain a '='): ");
        sbError.append(sSectionID);// w w  w  .j  av a2s  . co  m
        _logger.debug(sbError.toString());
        throw new IllegalArgumentException("Invalid section ID (should be name=value)");
    }

    String sKey = sSectionID.substring(0, iFirstEquals);
    String sValue = sSectionID.substring(iFirstEquals + 1, sSectionID.length());

    //get all childnodes
    NodeList nlChilds = eRootSection.getChildNodes();
    for (int i = 0; i < nlChilds.getLength(); i++) {
        Node nCurrent = nlChilds.item(i);
        //white spaces not supported, so only element_node
        if (nCurrent.getNodeType() == Node.ELEMENT_NODE) {
            Element eCurrent = (Element) nCurrent;
            if (eCurrent.getNodeName().equalsIgnoreCase(sSectionType) && eCurrent.hasAttributes()) {
                //check if node has the strKey attribute and check if
                // its value = strvalue
                if (eCurrent.getAttribute(sKey).equalsIgnoreCase(sValue))
                    return eCurrent;
            }
        }
    }

    return null;
}

From source file:com.alfaariss.oa.util.configuration.ConfigurationManager.java

/**
 * Retrieve a configuration parameter value.
 *
 * Retrieves the value of the config parameter from the config section 
  * that is supplied./* www .j  a v a 2 s  .  c  o m*/
 * @param eSection The base section.
 * @param sName The parameter name.
 * @return The paramater value.
 * @throws ConfigurationException If retrieving fails.
 */
public synchronized String getParam(Element eSection, String sName) throws ConfigurationException {
    if (eSection == null)
        throw new IllegalArgumentException("Suplied section is empty");
    if (sName == null)
        throw new IllegalArgumentException("Suplied name is empty");

    String sValue = null;
    try {
        //check attributes within the section tag
        if (eSection.hasAttributes()) {
            NamedNodeMap oNodeMap = eSection.getAttributes();
            Node nAttribute = oNodeMap.getNamedItem(sName);
            if (nAttribute != null)
                sValue = nAttribute.getNodeValue();
        }

        if (sValue == null) {//check sub sections
            NodeList nlChilds = eSection.getChildNodes();
            for (int i = 0; i < nlChilds.getLength(); i++) {
                Node nTemp = nlChilds.item(i);
                if (nTemp != null && nTemp.getNodeName().equalsIgnoreCase(sName)) {
                    NodeList nlSubNodes = nTemp.getChildNodes();
                    if (nlSubNodes.getLength() > 0) {
                        for (int iSub = 0; iSub < nlSubNodes.getLength(); iSub++) {
                            Node nSubTemp = nlSubNodes.item(iSub);
                            if (nSubTemp.getNodeType() == Node.TEXT_NODE) {
                                sValue = nSubTemp.getNodeValue();
                                if (sValue == null)
                                    sValue = "";

                                return sValue;
                            }
                        }
                    } else {
                        if (sValue == null)
                            sValue = "";

                        return sValue;
                    }
                }
            }
        }
    } catch (DOMException e) {
        _logger.error("Could not retrieve parameter: " + sValue, e);
        throw new ConfigurationException(SystemErrors.ERROR_CONFIG_READ);
    }
    return sValue;
}

From source file:com.concursive.connect.web.modules.api.beans.TransactionItem.java

/**
 * Sets the action attribute of the TransactionItem object
 *
 * @param objectElement The new action value
 *///  w w w.  java 2s  .c o  m
public void setAction(Element objectElement) {
    if (objectElement.hasAttributes()) {
        //Get the action for this item (Insert, Update, Delete, Select, etc.)
        String thisAction = objectElement.getAttribute("type");
        if (thisAction == null || thisAction.trim().equals("")) {
            thisAction = objectElement.getAttribute("action");
        }
        this.setAction(thisAction);
        //If specified, get the client's next id that should be used when
        //sending insert statements to the client
        String thisIdentity = objectElement.getAttribute("identity");
        try {
            identity = Integer.parseInt(thisIdentity);
        } catch (Exception e) {
        }
        // Enable paging
        if (objectElement.hasAttribute("offset") || objectElement.hasAttribute("items")
                || objectElement.hasAttribute("sort")) {
            // Ready for a new pagedListInfo
            pagedListInfo = new PagedListInfo();
            // If specified, get the number of max records to return, and the offset
            // to begin returning records at -- useful for large datasets
            String thisCurrentOffset = objectElement.getAttribute("offset");
            String thisItemsPerPage = objectElement.getAttribute("items");
            if (StringUtils.hasText(thisCurrentOffset) || StringUtils.hasText(thisItemsPerPage)) {
                pagedListInfo.setItemsPerPage(thisItemsPerPage);
                pagedListInfo.setCurrentOffset(thisCurrentOffset);
            }
            // Determine the sort order
            if (objectElement.hasAttribute("sort")) {
                pagedListInfo.setDefaultSort(objectElement.getAttribute("sort"),
                        objectElement.getAttribute("sortOrder"));
            }
        }
        // See if the primary key of this object should be exposed to other
        // items within the same transaction
        shareKey = "true".equals(objectElement.getAttribute("shareKey"));
        cached = "true".equals(objectElement.getAttribute("cached"));
    }
}

From source file:com.alfaariss.oa.util.configuration.ConfigurationManager.java

/**
 * @see com.alfaariss.oa.api.configuration.IConfigurationManager#getParams(org.w3c.dom.Element, java.lang.String)
 *///from w ww .java  2s  .co  m
public synchronized List<String> getParams(Element eSection, String sParamName) throws ConfigurationException {
    if (eSection == null)
        throw new IllegalArgumentException("Suplied section is empty");
    if (sParamName == null)
        throw new IllegalArgumentException("Suplied parameter name is empty");

    List<String> listValues = new Vector<String>();

    try {
        //check attributes within the section tag
        if (eSection.hasAttributes()) {
            NamedNodeMap oNodeMap = eSection.getAttributes();
            Node nAttribute = oNodeMap.getNamedItem(sParamName);
            if (nAttribute != null) {
                String sAttributeValue = nAttribute.getNodeValue();
                if (sAttributeValue != null)
                    listValues.add(sAttributeValue);
            }
        }

        NodeList nlChilds = eSection.getChildNodes();
        for (int i = 0; i < nlChilds.getLength(); i++) {
            Node nTemp = nlChilds.item(i);
            if (nTemp != null && nTemp.getNodeName().equalsIgnoreCase(sParamName)) {
                String sValue = "";
                NodeList nlSubNodes = nTemp.getChildNodes();
                if (nlSubNodes.getLength() > 0) {
                    for (int iSub = 0; iSub < nlSubNodes.getLength(); iSub++) {
                        Node nSubTemp = nlSubNodes.item(iSub);
                        if (nSubTemp.getNodeType() == Node.TEXT_NODE) {
                            sValue = nSubTemp.getNodeValue();
                            if (sValue == null)
                                sValue = "";
                        }
                    }
                }

                listValues.add(sValue);
            }
        }

        if (listValues.isEmpty())
            return null;
    } catch (DOMException e) {
        _logger.error("Could not retrieve parameter: " + sParamName, e);
        throw new ConfigurationException(SystemErrors.ERROR_CONFIG_READ);
    }

    return listValues;
}

From source file:jp.co.acroquest.jsonic.Formatter.java

public boolean format(final JSON json, final Context context, final Object src, final Object o,
        final OutputSource out) throws Exception {
    Element elem = (Element) o;
    out.append('[');
    StringFormatter.serialize(context, elem.getTagName(), out);

    out.append(',');
    if (context.isPrettyPrint()) {
        out.append('\n');
        for (int j = 0; j < context.getDepth() + 1; j++)
            out.append('\t');
    }/*from   w w w  . j  av  a  2 s.  c  om*/
    out.append('{');
    if (elem.hasAttributes()) {
        NamedNodeMap names = elem.getAttributes();
        for (int i = 0; i < names.getLength(); i++) {
            if (i != 0) {
                out.append(',');
            }
            if (context.isPrettyPrint() && names.getLength() > 1) {
                out.append('\n');
                for (int j = 0; j < context.getDepth() + 2; j++)
                    out.append('\t');
            }
            Node node = names.item(i);
            if (node instanceof Attr) {
                StringFormatter.serialize(context, node.getNodeName(), out);
                out.append(':');
                if (context.isPrettyPrint())
                    out.append(' ');
                StringFormatter.serialize(context, node.getNodeValue(), out);
            }
        }
        if (context.isPrettyPrint() && names.getLength() > 1) {
            out.append('\n');
            for (int j = 0; j < context.getDepth() + 1; j++)
                out.append('\t');
        }
    }
    out.append('}');
    if (elem.hasChildNodes()) {
        NodeList nodes = elem.getChildNodes();
        for (int i = 0; i < nodes.getLength(); i++) {
            Object value = nodes.item(i);
            if ((value instanceof Element) || (value instanceof CharacterData && !(value instanceof Comment))) {
                out.append(',');
                if (context.isPrettyPrint()) {
                    out.append('\n');
                    for (int j = 0; j < context.getDepth() + 1; j++)
                        out.append('\t');
                }
                context.enter(i + 2);
                value = json.preformatInternal(context, value);
                json.formatInternal(context, value, out);
                context.exit();
                if (out instanceof Flushable)
                    ((Flushable) out).flush();
            }
        }
    }
    if (context.isPrettyPrint()) {
        out.append('\n');
        for (int j = 0; j < context.getDepth(); j++)
            out.append('\t');
    }
    out.append(']');
    return true;
}