Example usage for org.w3c.dom Node hasChildNodes

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

Introduction

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

Prototype

public boolean hasChildNodes();

Source Link

Document

Returns whether this node has any children.

Usage

From source file:org.dasein.cloud.ibm.sce.compute.disk.SCEDisk.java

private SCEOffering findOffering(int sizeInGb) throws InternalException, CloudException {
    SCEOffering offering = null;//from  w  w  w .  ja  va2 s  . c o m

    ProviderContext ctx = provider.getContext();

    if (ctx == null) {
        throw new SCEConfigException("No context was configured for this request");
    }
    SCEMethod method = new SCEMethod(provider);

    Document xml = method.getAsXML("offerings/storage");

    if (xml == null) {
        throw new CloudException("No storage offerings exist");
    }
    NodeList nodes = xml.getElementsByTagName("Offerings");

    for (int i = 0; i < nodes.getLength(); i++) {
        Node item = nodes.item(i);

        if (item.hasChildNodes()) {
            NodeList attrs = item.getChildNodes();
            String id = null, format = null;
            int[] sizes = new int[0];

            for (int j = 0; j < attrs.getLength(); j++) {
                Node attr = attrs.item(j);
                String n = attr.getNodeName();

                if (n.equalsIgnoreCase("ID")) {
                    id = attr.getFirstChild().getNodeValue().trim();
                } else if (n.equalsIgnoreCase("SupportedSizes")) {
                    String s = attr.getFirstChild().getNodeValue().trim();
                    String[] parts;

                    if (s.contains(",")) {
                        parts = s.split(",");
                    } else {
                        parts = new String[] { s };
                    }
                    sizes = new int[parts.length];
                    for (int k = 0; k < parts.length; k++) {
                        sizes[k] = Integer.parseInt(parts[k].trim());
                    }
                } else if (n.equalsIgnoreCase("SupportedFormats") && attr.hasChildNodes()) {
                    NodeList formats = attr.getChildNodes();

                    for (int k = 0; k < formats.getLength(); k++) {
                        Node fmt = formats.item(k);

                        if (fmt.getNodeName().equalsIgnoreCase("Format") && fmt.hasChildNodes()) {
                            NodeList fa = fmt.getChildNodes();

                            for (int l = 0; l < fa.getLength(); l++) {
                                Node fan = fa.item(l);

                                if (fan.getNodeName().equalsIgnoreCase("ID") && fan.hasChildNodes()) {
                                    format = fan.getFirstChild().getNodeValue().trim();
                                    if (!format.equalsIgnoreCase("RAW")) {
                                        format = null;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            if (sizes.length > 0 && format != null) {
                if (offering == null) {
                    offering = new SCEOffering();
                    offering.format = format;
                    offering.offeringId = id;
                    if (sizes[0] > sizeInGb) {
                        offering.size = sizes[0];
                    } else {
                        int sz = 0;

                        for (int s : sizes) {
                            if (s < sizeInGb && s >= sz) {
                                sz = s;
                            } else {
                                break;
                            }
                        }
                        offering.size = sz;
                    }
                }
            }
        }
    }
    if (offering == null) {
        throw new CloudException("No storage offerings exist");
    }
    return offering;
}

From source file:org.apache.zeppelin.sap.universe.UniverseClient.java

private List<List<String>> parseResults(NodeList resultsNodeList) {
    List<List<String>> results = new ArrayList<>();
    if (resultsNodeList != null) {
        int count = resultsNodeList.getLength();
        for (int i = 0; i < count; i++) {
            Node node = resultsNodeList.item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE && node.hasChildNodes()) {
                NodeList properties = node.getChildNodes();
                if (properties != null) {
                    int countProperties = properties.getLength();
                    List<String> headers = new ArrayList<>();
                    List<String> row = new ArrayList<>();
                    // first property is id
                    for (int j = 1; j < countProperties; j++) {
                        Node propertyNode = properties.item(j);
                        if (i == 0) {
                            headers.add(propertyNode.getNodeName().replaceAll("^\\w*:", StringUtils.EMPTY));
                        }//w w  w  .  j  a  v  a 2 s.  c om
                        row.add(propertyNode.getTextContent());
                    }
                    if (i == 0) {
                        results.add(headers);
                    }
                    results.add(row);
                }
            }
        }
    }

    return results;
}

From source file:org.dasein.cloud.ibm.sce.compute.disk.SCEDisk.java

private @Nullable ExtendedVolume toVolume(@Nonnull ProviderContext ctx, @Nullable Node node)
        throws CloudException, InternalException {
    if (node == null || !node.hasChildNodes()) {
        return null;
    }//from w w  w .java 2 s.c  o  m
    NodeList attributes = node.getChildNodes();
    ExtendedVolume volume = new ExtendedVolume();

    volume.setCurrentState(VolumeState.PENDING);
    volume.setType(VolumeType.HDD);
    volume.setFormat(VolumeFormat.BLOCK);
    for (int i = 0; i < attributes.getLength(); i++) {
        Node attr = attributes.item(i);
        String nodeName = attr.getNodeName();

        if (nodeName.equalsIgnoreCase("ID") && attr.hasChildNodes()) {
            volume.setProviderVolumeId(attr.getFirstChild().getNodeValue().trim());
        } else if (nodeName.equalsIgnoreCase("Name") && attr.hasChildNodes()) {
            volume.setName(attr.getFirstChild().getNodeValue().trim());
        } else if (nodeName.equalsIgnoreCase("Description") && attr.hasChildNodes()) {
            volume.setName(attr.getFirstChild().getNodeValue().trim());
        } else if (nodeName.equalsIgnoreCase("Location") && attr.hasChildNodes()) {
            volume.setProviderRegionId(attr.getFirstChild().getNodeValue().trim());
            volume.setProviderDataCenterId(volume.getProviderRegionId());
        } else if (nodeName.equalsIgnoreCase("Size") && attr.hasChildNodes()) {
            volume.setSize(new Storage<Gigabyte>(Integer.parseInt(attr.getFirstChild().getNodeValue().trim()),
                    Storage.GIGABYTE));
        } else if (nodeName.equalsIgnoreCase("State") && attr.hasChildNodes()) {
            String status = attr.getFirstChild().getNodeValue().trim();

            volume.setCurrentState(toState(status));
            volume.setRealState(status);
        } else if (nodeName.equalsIgnoreCase("CreatedTime") && attr.hasChildNodes()) {
            volume.setCreationTimestamp(provider.parseTimestamp(attr.getFirstChild().getNodeValue().trim()));
        } else if (nodeName.equalsIgnoreCase("InstanceID") && attr.hasChildNodes()) {
            volume.setProviderVirtualMachineId(attr.getFirstChild().getNodeValue().trim());
        }
    }
    if (volume.getProviderVolumeId() == null) {
        return null;
    }
    String regionId = volume.getProviderRegionId();

    if (regionId == null || !regionId.equals(ctx.getRegionId())) {
        return null;
    }
    if (volume.getName() == null) {
        volume.setName(volume.getProviderVolumeId());
    }
    return volume;
}

From source file:com.jaspersoft.studio.data.xml.XMLDataAdapterDescriptor.java

private void findChildFields(NodeList nodes, LinkedHashMap<String, JRDesignField> fieldsMap, String prefix) {
    if (nodes != null) {
        List<String> childrenNames = new ArrayList<String>(); // temp list
        // to avoid
        // duplicates
        // at the
        // same/*  w w  w.  ja va2  s.c o  m*/
        // level
        for (int i = 0; i < nodes.getLength(); i++) {
            Node item = nodes.item(i);
            String nodeName = item.getNodeName();
            if ((item.getNodeType() == Node.ELEMENT_NODE || item.getNodeType() == Node.ATTRIBUTE_NODE)
                    && !childrenNames.contains(nodeName)) {
                if (recursiveFind) {
                    findDirectChildrenAttributes(item, fieldsMap, prefix + nodeName + "/");
                }
                if (considerEmptyNodes || StringUtils.isNotBlank(DOMUtil.getChildText(item))) {
                    addNewField(nodeName, fieldsMap, item, prefix);
                }
                if (recursiveFind && item.hasChildNodes()) {
                    findChildFields(item.getChildNodes(), fieldsMap, prefix + nodeName + "/");
                }
            }
        }
    }
}

From source file:org.apache.zeppelin.sap.universe.UniverseClient.java

private void loadUniverses(String token, int offset, Map<String, UniverseInfo> universesMap)
        throws UniverseException {
    int limit = 50;
    HttpGet httpGet = new HttpGet(
            String.format("%s%s?offset=%s&limit=%s", apiUrl, "/sl/v1/universes", offset, limit));
    setHeaders(httpGet, token);/*from  w ww.  ja  va 2 s.  c o  m*/
    HttpResponse response = null;
    try {
        response = httpClient.execute(httpGet);
    } catch (Exception e) {
        throw new UniverseException(String.format(errorMessageTemplate,
                "UniverseClient " + "(get universes): Request failed", ExceptionUtils.getStackTrace(e)));
    }
    if (response != null && response.getStatusLine().getStatusCode() == 200) {
        try (InputStream xmlStream = response.getEntity().getContent()) {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(xmlStream);
            XPathFactory xPathfactory = XPathFactory.newInstance();
            XPath xpath = xPathfactory.newXPath();
            XPathExpression expr = xpath.compile("//universe");
            NodeList universesNodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
            if (universesNodes != null) {
                int count = universesNodes.getLength();
                for (int i = 0; i < count; i++) {
                    Node universe = universesNodes.item(i);
                    if (universe.hasChildNodes()) {
                        NodeList universeParameters = universe.getChildNodes();
                        int parapetersCount = universeParameters.getLength();
                        String id = null;
                        String name = null;
                        String type = null;
                        for (int j = 0; j < parapetersCount; j++) {
                            Node parameterNode = universeParameters.item(j);
                            parameterNode.getNodeName();
                            if (parameterNode.getNodeType() == Node.ELEMENT_NODE) {
                                if (parameterNode.getNodeName().equalsIgnoreCase("id")) {
                                    id = parameterNode.getTextContent();
                                    continue;
                                }
                                if (parameterNode.getNodeName().equalsIgnoreCase("name")) {
                                    name = parameterNode.getTextContent();
                                    continue;
                                }
                                if (parameterNode.getNodeName().equalsIgnoreCase("type")) {
                                    type = parameterNode.getTextContent();
                                    continue;
                                }
                            }
                        }
                        if (StringUtils.isNotBlank(type)) {
                            name = name.replaceAll(String.format("\\.%s$", type), StringUtils.EMPTY);
                        }
                        universesMap.put(name, new UniverseInfo(id, name, type));
                    }
                }
                if (count == limit) {
                    offset += limit;
                    loadUniverses(token, offset, universesMap);
                }
            }
        } catch (IOException e) {
            throw new UniverseException(String.format(errorMessageTemplate,
                    "UniverseClient " + "(get universes): Response processing failed",
                    ExceptionUtils.getStackTrace(e)));
        } catch (ParserConfigurationException | SAXException | XPathExpressionException e) {
            throw new UniverseException(String.format(errorMessageTemplate,
                    "UniverseClient " + "(get universes): Response processing failed",
                    ExceptionUtils.getStackTrace(e)));
        }
    }
}

From source file:org.dasein.cloud.aws.platform.SimpleDB.java

@Override
public KeyValueDatabase getDatabase(String domainId) throws CloudException, InternalException {
    APITrace.begin(provider, "KVDB.getDatabase");
    try {//from ww w.  j  a v  a2 s  .  c  o  m
        Map<String, String> parameters = provider.getStandardSimpleDBParameters(provider.getContext(),
                DOMAIN_META_DATA);
        EC2Method method;
        Document doc;

        parameters.put("DomainName", domainId);
        method = new EC2Method(SERVICE_ID, provider, parameters);
        try {
            doc = method.invoke();
        } catch (EC2Exception e) {
            String code = e.getCode();

            if (code != null && code.equals("NoSuchDomain")) {
                return null;
            }
            throw new CloudException(e);
        }
        KeyValueDatabase database = new KeyValueDatabase();

        database.setProviderOwnerId(provider.getContext().getAccountNumber());
        database.setProviderRegionId(provider.getContext().getRegionId());
        database.setProviderDatabaseId(domainId);
        database.setName(domainId);
        database.setDescription(domainId);
        NodeList blocks = doc.getElementsByTagName("DomainMetadataResult");
        if (blocks.getLength() > 0) {
            for (int i = 0; i < blocks.getLength(); i++) {
                NodeList items = blocks.item(i).getChildNodes();

                for (int j = 0; j < items.getLength(); j++) {
                    Node item = items.item(j);
                    String name = item.getNodeName();

                    if (name.equals("ItemCount")) {
                        if (item.hasChildNodes()) {
                            database.setItemCount(Integer.parseInt(item.getFirstChild().getNodeValue()));
                        }
                    } else if (name.equals("AttributeValueCount")) {
                        if (item.hasChildNodes()) {
                            database.setKeyValueCount(Integer.parseInt(item.getFirstChild().getNodeValue()));
                        }
                    } else if (name.equals("AttributeNameCount")) {
                        if (item.hasChildNodes()) {
                            database.setKeyCount(Integer.parseInt(item.getFirstChild().getNodeValue()));
                        }
                    } else if (name.equals("ItemNamesSizeBytes")) {
                        if (item.hasChildNodes()) {
                            database.setItemSize(Integer.parseInt(item.getFirstChild().getNodeValue()));
                        }
                    } else if (name.equals("AttributeValuesSizeBytes")) {
                        if (item.hasChildNodes()) {
                            database.setKeyValueSize(Integer.parseInt(item.getFirstChild().getNodeValue()));
                        }
                    } else if (name.equals("AttributeNamesSizeBytes")) {
                        if (item.hasChildNodes()) {
                            database.setKeySize(Integer.parseInt(item.getFirstChild().getNodeValue()));
                        }
                    }
                }
            }
        }
        return database;
    } finally {
        APITrace.end();
    }
}

From source file:com.inbravo.scribe.rest.service.crm.ms.MSCRMMessageFormatUtils.java

/**
 * //from   w w w.j  av  a 2s  .  c o m
 * @param entity
 * @return
 * @throws Exception
 */
public static final List<Element> createV5EntityFromBusinessObject(final Entity entity) throws Exception {

    /* Create list of elements */
    final List<Element> elementList = new ArrayList<Element>();

    /* Set entity id */
    elementList.add(createMessageElement("id", entity.getId()));

    /* Step 2: get all node attributes */
    final AttributeCollection attCol = entity.getAttributes();

    /* Check if entity is not null */
    if (attCol != null) {

        /* Get all attributes for the CRM field */
        final KeyValuePairOfstringanyType[] kvpsatArr = attCol.getKeyValuePairOfstringanyTypeArray();

        /* This is to avoid : 'DOM Level 3 Not implemented' error */
        final DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        final Document document = builder.newDocument();

        if (logger.isDebugEnabled()) {
            logger.debug("----Inside createV5EntityFromBusinessObject: no of crm fields: " + kvpsatArr.length);
        }

        /* Iterate over all attributes */
        for (final KeyValuePairOfstringanyType kvpsat : kvpsatArr) {

            /* Get field name */
            final String fieldName = kvpsat.getKey();

            if (logger.isDebugEnabled()) {
                logger.debug("----Inside createV5EntityFromBusinessObject: crm field name: " + fieldName);
            }

            /* Get field value */
            String fieldValue = null;

            /* Get field value node */
            final XmlObject xo = kvpsat.getValue();

            /* If object is valid */
            if (xo != null) {

                /* Get DOM node from Xo */
                final Node node = xo.getDomNode();

                /* Check if node is not null */
                if (node != null && node.hasChildNodes()) {

                    /* Get all child nodes */
                    final NodeList nodeList = node.getChildNodes();

                    /* Create new map for attributes */
                    final Map<String, String> attributeMap = new HashMap<String, String>();

                    /* If more than 1 elements in node list */
                    if (nodeList.getLength() > 1) {

                        /* Iterate on all child node list */
                        for (int i = 0; i < nodeList.getLength(); i++) {

                            if (nodeList.item(i) instanceof Element) {

                                final Element childElement = (Element) document.importNode(nodeList.item(i),
                                        true);

                                if (childElement.getNodeName() != null
                                        && childElement.getNodeName().contains(":")) {

                                    /* Get attribute name */
                                    final String attName = childElement.getNodeName().split(":")[1];

                                    /* Get attribute value */
                                    final String attValue = childElement.getTextContent();

                                    if ("id".equalsIgnoreCase(attName)) {

                                        fieldValue = attValue;
                                    } else {

                                        /* Put values in map */
                                        attributeMap.put(attName, attValue);
                                    }
                                }
                            }
                        }

                        /* Create node with attributes */
                        elementList.add(createMessageElement(fieldName, fieldValue, attributeMap));

                    } else if (nodeList.getLength() == 1) {

                        /* Iterate on all child node list */
                        if (nodeList.item(0) instanceof Element) {

                            final Element childElement = (Element) document.importNode(nodeList.item(0), true);

                            /* Get attribute value */
                            fieldValue = childElement.getTextContent();

                            /* Create node with attributes */
                            elementList.add(createMessageElement(fieldName, fieldValue));
                        } else {

                            /* Create node with attributes */
                            elementList.add(createMessageElement(fieldName, nodeList.item(0).getNodeValue()));
                        }
                    }
                } else {

                    /* Create node with attributes */
                    elementList.add(createMessageElement(fieldName, node.getTextContent()));
                }
            }
        }
    }

    return elementList;
}

From source file:org.apache.zeppelin.sap.universe.UniverseClient.java

private void parseUniverseInfo(NodeList universeInfoNodes, Map<String, UniverseNodeInfo> nodes) {
    if (universeInfoNodes != null) {
        int count = universeInfoNodes.getLength();
        for (int i = 0; i < count; i++) {
            Node node = universeInfoNodes.item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE && node.hasChildNodes()) {
                String name = node.getNodeName();
                NodeList childNodes = node.getChildNodes();
                int childNodesCount = childNodes.getLength();
                if (name.equalsIgnoreCase(EL_FOLDER)) {
                    NodeSet list = new NodeSet();
                    for (int j = 0; j < childNodesCount; j++) {
                        Node childNode = childNodes.item(j);
                        if (childNode.getNodeType() == Node.ELEMENT_NODE && childNode.hasChildNodes()) {
                            String childNodeName = childNode.getNodeName();
                            if (childNodeName.equalsIgnoreCase(EL_FOLDER)
                                    || childNodeName.equalsIgnoreCase(EL_ITEM)) {
                                list.addNode(childNode);
                            }/*  www . j  a  va2  s .c  o  m*/
                        }
                    }
                    if (list.getLength() > 0) {
                        parseUniverseInfo(list, nodes);
                    }
                } else if (name.equalsIgnoreCase(EL_ITEM)) {
                    String nodeId = null;
                    String nodeName = null;
                    String nodePath = null;
                    for (int j = 0; j < childNodesCount; j++) {
                        Node childNode = childNodes.item(j);
                        if (childNode.getNodeType() == Node.ELEMENT_NODE) {
                            String childNodeName = childNode.getNodeName();
                            if (childNodeName.equalsIgnoreCase(EL_NAME)) {
                                nodeName = childNode.getTextContent();
                                continue;
                            }
                            if (childNodeName.equalsIgnoreCase(EL_ID)) {
                                nodeId = childNode.getTextContent();
                                continue;
                            }
                            if (childNodeName.equalsIgnoreCase(EL_PATH)) {
                                nodePath = childNode.getTextContent();
                                continue;
                            }
                        }
                    }
                    String folder = null;
                    StringBuilder key = new StringBuilder();
                    if (StringUtils.isNotBlank(nodeName)) {
                        String nodeType = null;
                        if (StringUtils.isNotBlank(nodePath)) {
                            String[] parts = nodePath.split("\\\\");
                            List<String> path = new ArrayList();
                            for (String part : parts) {
                                String[] p = part.split("\\|");
                                if (p.length == 2) {
                                    if (p[1].equalsIgnoreCase("folder")) {
                                        path.add(p[0]);
                                    } else {
                                        nodeName = p[0];
                                        nodeType = p[1];
                                        if (p[1].equalsIgnoreCase("dimension")) {
                                            addAttributesToDimension(node, nodes);
                                        }
                                    }
                                }
                            }
                            folder = StringUtils.join(path, "\\");
                            if (path.isEmpty()) {
                                key.append(String.format("[%s]", nodeName));
                            } else {
                                key.append("[");
                                key.append(StringUtils.join(path, "].["));
                                key.append(String.format("].[%s]", nodeName));
                            }
                        }
                        nodes.put(key.toString(),
                                new UniverseNodeInfo(nodeId, nodeName, nodeType, folder, nodePath));
                    }
                }
            }
        }
    }
}

From source file:org.jetbrains.webdemo.help.HelpLoader.java

private String getTagValueWithTagName(Node node) {
    StringBuilder result = new StringBuilder();

    if (node.getNodeType() == 3) {
        result.append(node.getNodeValue());
    } else {/*from  www  .  j  av  a2  s  . co  m*/
        result.append("<");
        result.append(node.getNodeName());
        if (node.getNodeName().equals("a")) {
            result.append(" target=\"_blank\" ");
        }
        if (node.hasAttributes()) {
            result.append(" ");
            NamedNodeMap map = node.getAttributes();
            for (int i = 0; i < map.getLength(); i++) {
                result.append(map.item(i).getNodeName());
                result.append("=\"");
                result.append(map.item(i).getTextContent());
                result.append("\" ");
            }
        }
        result.append(">");
        if (node.hasChildNodes()) {
            NodeList nodeList = node.getChildNodes();
            for (int i = 0; i < nodeList.getLength(); i++) {
                result.append(getTagValueWithTagName(nodeList.item(i)));
            }
        }
        result.append("</");
        result.append(node.getNodeName());
        result.append(">");
    }
    return result.toString();
}

From source file:de.qucosa.webapi.v1.DocumentResource.java

private void removeEmtpyFields(Document doc) {
    Element root = (Element) doc.getElementsByTagName("Opus_Document").item(0);
    NodeList childNodes = root.getChildNodes();

    // removing nodes from the node list changes the node list
    // so for iteration is not invariant.
    ArrayList<Node> removees = new ArrayList<>(childNodes.getLength());

    for (int i = 0; i < childNodes.getLength(); i++) {
        Node childNode = childNodes.item(i);
        if (!childNode.hasChildNodes())
            removees.add(childNode);//from w  w  w .j  a  v a 2s  . c o m
    }
    for (Node n : removees)
        root.removeChild(n);

}