Example usage for org.w3c.dom Element hasChildNodes

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

Introduction

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

Prototype

public boolean hasChildNodes();

Source Link

Document

Returns whether this node has any children.

Usage

From source file:com.vmware.qe.framework.datadriven.utils.XMLUtil.java

/**
 * Gets the descendant elements which have an attribute with the specified name and value
 * /*from  w w  w .j  av a  2  s . c  o  m*/
 * @param parentNode - Node whose children are to be searched
 * @param attrId - attribute name
 * @param attrVal - attribute value
 * @return List of all children nodes
 * @throws Exception
 */
public static List<Element> getElements(Node parentNode, String attrId, String attrVal) throws Exception {
    NodeList nodeList = parentNode.getChildNodes();
    List<Element> elements = new ArrayList<Element>();
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node child = nodeList.item(i);
        if (child instanceof Element) {
            Element element = (Element) child;
            if (attrVal.equalsIgnoreCase(element.getAttribute(attrId))) {
                elements.add(element);
            }
            if (element.hasChildNodes()) {
                // recursive call to search for child's children
                List<Element> children = getElements(element, attrId, attrVal);
                if (children != null) {
                    elements.addAll(children);
                }
            }
        }
    }
    return elements.isEmpty() ? null : elements;
}

From source file:com.fota.Link.sdpApi.java

public static String getNcnInfo(String CTN) throws JDOMException {
    String resultStr = "";
    String logData = "";
    try {//w ww .  j  av a 2  s  .  co m
        String endPointUrl = PropUtil.getPropValue("sdp.oif516.url");

        String strRequest = "<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' "
                + "xmlns:oas='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd'"
                + " xmlns:sdp='http://kt.com/sdp'>" + "     <soapenv:Header>" + "         <oas:Security>"
                + "             <oas:UsernameToken>" + "                 <oas:Username>"
                + PropUtil.getPropValue("sdp.id") + "</oas:Username>" + "                 <oas:Password>"
                + PropUtil.getPropValue("sdp.pw") + "</oas:Password>" + "             </oas:UsernameToken>"
                + "         </oas:Security>" + "     </soapenv:Header>"

                + "     <soapenv:Body>" + "         <sdp:getBasicUserInfoAndMarketInfoRequest>"
                + "         <!--You may enterthe following 6 items in any order-->"
                + "             <sdp:CALL_CTN>" + CTN + "</sdp:CALL_CTN>"
                + "         </sdp:getBasicUserInfoAndMarketInfoRequest>\n" + "     </soapenv:Body>\n"
                + "</soapenv:Envelope>";

        logData = "\r\n---------- Get Ncn Req Info start ----------\r\n";
        logData += " get Ncn Req Info - endPointUrl : " + endPointUrl;
        logData += "\r\n get Ncn Req Info - Content-type : text/xml;charset=utf-8";
        logData += "\r\n get Ncn Req Info - RequestMethod : POST";
        logData += "\r\n get Ncn Req Info - xml : " + strRequest;
        logData += "\r\n---------- Get Ncn Req Info end ----------";

        logger.info(logData);

        // connection
        URL url = new URL(endPointUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestProperty("Content-type", "text/xml;charset=utf-8");
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.connect();

        // output
        OutputStream os = connection.getOutputStream();
        // os.write(strRequest.getBytes(), 0, strRequest.length());
        os.write(strRequest.getBytes("utf-8"));
        os.flush();
        os.close();

        // input
        InputStream is = connection.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is, "utf-8"));
        String line = "";
        String resValue = "";
        String parseStr = "";
        while ((line = br.readLine()) != null) {
            System.out.println(line);
            parseStr = line;

        }

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        InputSource temp = new InputSource();
        temp.setCharacterStream(new StringReader(parseStr));
        Document doc = builder.parse(temp); //xml?

        NodeList list = doc.getElementsByTagName("*");

        int i = 0;
        Element element;
        String contents;

        String contractNum = "";
        String customerId = "";
        while (list.item(i) != null) {
            element = (Element) list.item(i);
            if (element.hasChildNodes()) {
                contents = element.getFirstChild().getNodeValue();
                System.out.println(element.getNodeName() + " / " + element.getFirstChild().getNodeName());

                if (element.getNodeName().equals("sdp:NS_CONTRACT_NUM")) {
                    //                  resultStr = element.getFirstChild().getNodeValue();
                    contractNum = element.getFirstChild().getNodeValue();
                }
                if (element.getNodeName().equals("sdp:NS_CUSTOMER_ID")) {
                    customerId = element.getFirstChild().getNodeValue();
                }

                //               System.out.println(" >>>>> " + contents);
            }
            i++;
        }

        //         System.out.println("contractNum : " + contractNum + " / cusomerId : " + customerId);

        resultStr = getNcnFromContractnumAndCustomerId(contractNum, customerId);
        //         System.out.println("ncn : " + resultStr);

        //resultStr = resValue;         
        //         resultStr = java.net.URLDecoder.decode(resultStr, "euc-kr");
        connection.disconnect();

    } catch (Exception e) {
        e.printStackTrace();
    }

    return resultStr;
}

From source file:com.viadee.acceptancetests.roo.addon.PluginDependency.java

private void removeAllChildNodes(Element element) {
    while (element.hasChildNodes()) {
        element.removeChild(element.getFirstChild());
    }//from  w  w  w.j a  v a  2s  .c  o  m
}

From source file:de.betterform.xml.dom.DOMUtil.java

/**
 * check, if the passed element node has non-whitespace children.
 *
 * @return true, if any Element nodes are found, otherwise false
 *///from  www. j a  va 2  s. c  o m
public static boolean hasNonWhitespaceChildren(Element element) {
    if (element.hasChildNodes()) {
        NodeList children = element.getChildNodes();
        int len = children.getLength();
        Node n = null;

        for (int i = 0; i < len; i++) {
            n = children.item(i);

            if (n.getNodeType() == Node.ELEMENT_NODE) {
                return true;
            }
        }

        return false;
    } else {
        return false;
    }
}

From source file:com.hp.autonomy.searchcomponents.idol.search.fields.FieldsParserImpl.java

@Override
public void parseDocumentFields(final Hit hit, final IdolSearchResult.Builder searchResultBuilder) {
    final FieldsInfo fieldsInfo = configService.getConfig().getFieldsInfo();
    final Map<String, FieldInfo<?>> fieldConfig = fieldsInfo.getFieldConfigByName();

    final DocContent content = hit.getContent();
    Map<String, FieldInfo<?>> fieldMap = Collections.emptyMap();
    String qmsId = null;//from w  w w . j  av  a2s.  co  m
    PromotionCategory promotionCategory = PromotionCategory.NONE;
    if (content != null) {
        final Element docContent = (Element) content.getContent().get(0);
        if (docContent.hasChildNodes()) {
            final NodeList childNodes = docContent.getChildNodes();
            fieldMap = new HashMap<>(childNodes.getLength());

            parseAllFields(fieldConfig, childNodes, fieldMap, docContent.getNodeName());

            qmsId = parseField(docContent, IdolDocumentFieldsService.QMS_ID_FIELD_INFO, String.class);
            promotionCategory = determinePromotionCategory(docContent, hit.getPromotionname(),
                    hit.getDatabase());
        }
    }

    searchResultBuilder.setFieldMap(fieldMap).setQmsId(qmsId).setPromotionCategory(promotionCategory);
}

From source file:com.francetelecom.clara.cloud.db.liquibase.CompareChangeLogWithHibernateAutoCreateIT.java

private boolean searchForDifferenceInXml(File xmlFile) {
    boolean differenceFound = false;
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(false);//  ww  w . j a v  a2s  .c  om
    factory.setIgnoringElementContentWhitespace(true);
    try {
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(xmlFile);
        Element databaseChangeLogRoot = document.getDocumentElement();
        differenceFound = databaseChangeLogRoot.hasChildNodes();
        // Do something with the document here.
    } catch (ParserConfigurationException | IOException | SAXException e) {
        LOGGER.info("Failed to parse xml file: {}", xmlFile, e);
    }
    return differenceFound;
}

From source file:com.opengamma.web.bundle.BundleParser.java

private boolean hasChildren(Element element) {
    if (element.hasChildNodes()) {
        return true;
    }/*from  ww  w  .  ja  va 2 s.  c  o  m*/
    throw new OpenGammaRuntimeException("parsing bundle XML : missing children elements in bundle");
}

From source file:eap.config.AspectJAutoProxyBeanDefinitionParser.java

private void extendBeanDefinition(Element element, ParserContext parserContext) {
    BeanDefinition beanDef = parserContext.getRegistry()
            .getBeanDefinition(AopConfigUtils.AUTO_PROXY_CREATOR_BEAN_NAME);
    if (element.hasChildNodes()) {
        addIncludePatterns(element, parserContext, beanDef);
    }/*from  w w  w .ja  v  a  2s . co  m*/
}

From source file:com.tacitknowledge.flip.spring.config.FeatureServiceHandlerParser.java

@Override
protected AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) {
    BeanDefinitionBuilder factoryBuilder = BeanDefinitionBuilder
            .rootBeanDefinition(FeatureServiceDirectFactory.class);
    RootBeanDefinition factoryBean = (RootBeanDefinition) factoryBuilder.getBeanDefinition();
    parserContext.getRegistry().registerBeanDefinition(FlipSpringAspect.FEATURE_SERVICE_FACTORY_BEAN_NAME,
            factoryBean);/*from  w  w w.j a  v  a 2s.c o  m*/

    MutablePropertyValues factoryPropertyValues = new MutablePropertyValues();
    factoryBean.setPropertyValues(factoryPropertyValues);

    String environmentBean = element.getAttribute("environment");
    if (environmentBean != null && !environmentBean.isEmpty()) {
        factoryPropertyValues.addPropertyValue("environment", new RuntimeBeanNameReference(environmentBean));
    }

    Element contextProvidersElement = DomUtils.getChildElementByTagName(element, "context-providers");
    if (contextProvidersElement != null) {
        List contextProvidersList = parserContext.getDelegate().parseListElement(contextProvidersElement,
                factoryBean);
        if (contextProvidersList != null && !contextProvidersList.isEmpty()) {
            factoryPropertyValues.addPropertyValue("contextProviders", contextProvidersList);
        }
    }

    Element propertyReadersElement = DomUtils.getChildElementByTagName(element, "property-readers");
    if (propertyReadersElement != null && propertyReadersElement.hasChildNodes()) {
        List propertyReadersList = parserContext.getDelegate().parseListElement(propertyReadersElement,
                factoryBean);
        if (propertyReadersList != null && !propertyReadersList.isEmpty()) {
            factoryPropertyValues.addPropertyValue("propertyReaders", propertyReadersList);
        }
    }

    Element propertiesElement = DomUtils.getChildElementByTagName(element, "properties");
    if (propertiesElement != null && propertiesElement.hasChildNodes()) {
        Properties properties = parserContext.getDelegate().parsePropsElement(propertiesElement);
        if (properties != null && !properties.isEmpty()) {
            factoryPropertyValues.addPropertyValue("properties", properties);
        }
    }

    BeanDefinitionBuilder featureServiceBuilder = BeanDefinitionBuilder.genericBeanDefinition();
    BeanDefinition featureServiceRawBean = featureServiceBuilder.getRawBeanDefinition();
    featureServiceRawBean.setFactoryBeanName(FlipSpringAspect.FEATURE_SERVICE_FACTORY_BEAN_NAME);
    featureServiceRawBean.setFactoryMethodName("createFeatureService");
    parserContext.getRegistry().registerBeanDefinition(FlipSpringAspect.FEATURE_SERVICE_BEAN_NAME,
            featureServiceBuilder.getBeanDefinition());

    return null;
}

From source file:com.digitalpebble.storm.crawler.filtering.regex.RegexURLNormalizer.java

private List<Rule> readConfiguration(Reader reader) {
    List<Rule> rules = new ArrayList<Rule>();
    try {/*from   ww  w .  j a  v  a  2  s.c om*/

        // borrowed heavily from code in Configuration.java
        Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(reader));
        Element root = doc.getDocumentElement();
        if ((!"regex-normalize".equals(root.getTagName())) && (LOG.isErrorEnabled())) {
            LOG.error("bad conf file: top-level element not <regex-normalize>");
        }
        NodeList regexes = root.getChildNodes();
        for (int i = 0; i < regexes.getLength(); i++) {
            Node regexNode = regexes.item(i);
            if (!(regexNode instanceof Element)) {
                continue;
            }
            Element regex = (Element) regexNode;
            if ((!"regex".equals(regex.getTagName())) && (LOG.isWarnEnabled())) {
                LOG.warn("bad conf file: element not <regex>");
            }
            NodeList fields = regex.getChildNodes();
            String patternValue = null;
            String subValue = null;
            for (int j = 0; j < fields.getLength(); j++) {
                Node fieldNode = fields.item(j);
                if (!(fieldNode instanceof Element)) {
                    continue;
                }
                Element field = (Element) fieldNode;
                if ("pattern".equals(field.getTagName()) && field.hasChildNodes()) {
                    patternValue = ((Text) field.getFirstChild()).getData();
                }
                if ("substitution".equals(field.getTagName()) && field.hasChildNodes()) {
                    subValue = ((Text) field.getFirstChild()).getData();
                }
                if (!field.hasChildNodes()) {
                    subValue = "";
                }
            }
            if (patternValue != null && subValue != null) {
                Rule rule = createRule(patternValue, subValue);
                rules.add(rule);
            }
        }
    } catch (Exception e) {
        LOG.error("error parsing conf file", e);
        return EMPTY_RULES;
    }
    if (rules.size() == 0) {
        return EMPTY_RULES;
    }
    return rules;
}