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:org.shirdrn.tinyframework.core.conf.Context.java

private void loadResource(Properties properties, Object name, boolean quiet) {
    try {// w  w  w .  jav  a  2s .com
        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        //ignore all comments inside the xml file
        docBuilderFactory.setIgnoringComments(true);

        //allow includes in the xml file
        docBuilderFactory.setNamespaceAware(true);
        try {
            docBuilderFactory.setXIncludeAware(true);
        } catch (UnsupportedOperationException e) {
            LOG.error("Failed to set setXIncludeAware(true) for parser " + docBuilderFactory + ":" + e, e);
        }
        DocumentBuilder builder = docBuilderFactory.newDocumentBuilder();
        Document doc = null;
        Element root = null;

        if (name instanceof URL) { // an URL resource
            URL url = (URL) name;
            if (url != null) {
                if (!quiet) {
                    LOG.info("parsing " + url);
                }
                doc = builder.parse(url.toString());
            }
        } else if (name instanceof String) { // a CLASSPATH resource
            URL url = getResource((String) name);
            if (url != null) {
                if (!quiet) {
                    LOG.info("parsing " + url);
                }
                doc = builder.parse(url.toString());
            }
        } else if (name instanceof InputStream) {
            try {
                doc = builder.parse((InputStream) name);
            } finally {
                ((InputStream) name).close();
            }
        } else if (name instanceof Element) {
            root = (Element) name;
        }

        if (doc == null && root == null) {
            if (quiet)
                return;
            throw new RuntimeException(name + " not found");
        }

        if (root == null) {
            root = doc.getDocumentElement();
        }
        if (!"configuration".equals(root.getTagName()))
            LOG.fatal("bad conf file: top-level element not <configuration>");
        NodeList props = root.getChildNodes();
        for (int i = 0; i < props.getLength(); i++) {
            Node propNode = props.item(i);
            if (!(propNode instanceof Element))
                continue;
            Element prop = (Element) propNode;
            if ("configuration".equals(prop.getTagName())) {
                loadResource(properties, prop, quiet);
                continue;
            }
            if (!"property".equals(prop.getTagName()))
                LOG.warn("bad conf file: element not <property>");
            NodeList fields = prop.getChildNodes();
            String attr = null;
            String value = null;
            boolean finalParameter = false;
            for (int j = 0; j < fields.getLength(); j++) {
                Node fieldNode = fields.item(j);
                if (!(fieldNode instanceof Element))
                    continue;
                Element field = (Element) fieldNode;
                if ("name".equals(field.getTagName()) && field.hasChildNodes())
                    attr = ((Text) field.getFirstChild()).getData().trim();
                if ("value".equals(field.getTagName()) && field.hasChildNodes())
                    value = ((Text) field.getFirstChild()).getData();
                if ("final".equals(field.getTagName()) && field.hasChildNodes())
                    finalParameter = "true".equals(((Text) field.getFirstChild()).getData());
            }

            // Ignore this parameter if it has already been marked as 'final'
            if (attr != null && value != null) {
                if (!finalParameters.contains(attr)) {
                    properties.setProperty(attr, value);
                    if (finalParameter)
                        finalParameters.add(attr);
                } else {
                    LOG.warn(name + ":a attempt to override final parameter: " + attr + ";  Ignoring.");
                }
            }
        }

    } catch (IOException e) {
        LOG.fatal("error parsing conf file: " + e);
        throw new RuntimeException(e);
    } catch (DOMException e) {
        LOG.fatal("error parsing conf file: " + e);
        throw new RuntimeException(e);
    } catch (SAXException e) {
        LOG.fatal("error parsing conf file: " + e);
        throw new RuntimeException(e);
    } catch (ParserConfigurationException e) {
        LOG.fatal("error parsing conf file: " + e);
        throw new RuntimeException(e);
    }
}

From source file:org.wso2.carbon.bpel.b4p.extension.BPEL4PeopleExtensionOperation.java

/**
 * Called when the response for the above service is received
 *
 * @param mexId MessageExchange id/*from  w w w.j  a v a  2 s  . c o  m*/
 */
@Override
public void onRequestReceived(String mexId) throws FaultException {
    if (log.isDebugEnabled()) {
        log.debug("People Activity Response received : mexId " + mexId);
    }

    Element notificationMessageEle = extensionContext.getInternalInstance().getMyRequest(mexId);

    if ("".equals(outputVarName) || outputVarName == null) {
        // if output variable is null or empty, these is no way to process the response from the task as we do
        // not have
        // a variable from bpel file to assign the values to. Hence what what we can do is to return a fault and
        // exit.
        log.error(
                "Output variable not specified correctly for the remoteTask activity.Hence the error condition."
                        + "Please verify and correct your BPEL process remoteTask");

        extensionContext.completeWithFault(cid,
                new FaultException(BPEL4PeopleConstants.B4P_FAULT, BPEL4PeopleConstants.NON_RECOVERABLE_ERROR));
    } else {
        Node part = extensionContext.getPartData(notificationMessageEle, outputVarName);

        if (messageTraceLog.isTraceEnabled()) {
            messageTraceLog.trace("B4P Response Message: " + DOMUtils.domToString(notificationMessageEle));
            messageTraceLog.trace("B4P Response Part: " + DOMUtils.domToString(part));

        }

        if (CoordinationConfiguration.getInstance().isHumantaskCoordinationEnabled()
                && notificationMessageEle.hasChildNodes()) {
            String taskID = "";
            Element correlationHeader = DOMUtils.findChildByName(notificationMessageEle,
                    new QName(BPEL4PeopleConstants.B4P_NAMESPACE, BPEL4PeopleConstants.B4P_CORRELATION_HEADER),
                    true);
            if (correlationHeader != null) {
                taskID = correlationHeader.getAttributeNS(BPEL4PeopleConstants.B4P_NAMESPACE,
                        BPEL4PeopleConstants.B4P_CORRELATION_HEADER_ATTRIBUTE);
                try {
                    deleteCoordinationTaskData(taskID);
                } catch (Exception e) {
                    log.error("Error occurred while cleaning coordination data for task id " + taskID, e);
                }
            }

            //Checking for fault
            Element fault = DOMUtils.findChildByName(notificationMessageEle,
                    new QName(WSConstants.WS_HT_COORDINATION_PROTOCOL_FAULT));
            if (fault != null) {
                if (fault.hasAttribute("headerPart")) {
                    if (log.isDebugEnabled()) {
                        log.debug(
                                "Throwing Fault to People Activity Scope since received Fault Protocol Message "
                                        + "for task" + taskID + ".");
                    }
                    extensionContext.completeWithFault(cid, new FaultException(BPEL4PeopleConstants.B4P_FAULT,
                            BPEL4PeopleConstants.NON_RECOVERABLE_ERROR));
                    ;
                }
            }
            //Checking for Skip
            Element skipped = DOMUtils.findChildByName(notificationMessageEle,
                    new QName(WSConstants.WS_HT_COORDINATION_PROTOCOL_SKIPPED));
            if (skipped != null) {
                if (skipped.hasAttribute("headerPart")) {
                    if (log.isDebugEnabled()) {
                        log.debug("Skipping People Activity since received Skipped Protocol Message for task "
                                + taskID + ".");
                    }
                    //Set extension as complete, since task is skipped. No value write to output variable.
                    extensionContext.complete(cid);
                    return;
                }
            }
        }
        extensionContext.writeVariable(outputVarName, notificationMessageEle);
        extensionContext.complete(cid);
    }
}

From source file:org.wso2.carbon.core.bootup.validator.util.ConfigValidationXMLProcessor.java

/**
 * Initializes an instance of the ConfigurationValidator class with the
 * fully/*from  www.ja v  a  2  s.co  m*/
 * qualified class name given in the xml element.
 * 
 * @param elem
 * @return ConfigurationValidator object
 * @throws ClassNotFoundException
 * @throws IllegalAccessException
 * @throws InstantiationException
 */
private ConfigurationValidator initConfigValidator(Element elem)
        throws InstantiationException, IllegalAccessException, ClassNotFoundException {

    HashMap<String, String> validationParams = new HashMap<String, String>();
    String className = elem.getAttribute(CLASS_ATTRIBUTE);
    // loading the ConfigurationValidator class
    ConfigurationValidator validator = (ConfigurationValidator) Class.forName(className).newInstance();
    NodeList nl = elem.getElementsByTagName(PARAMETER_TAG);
    if (nl != null && nl.getLength() > 0) {
        for (int i = 0; i < nl.getLength(); i++) {
            Element el = (Element) nl.item(i);
            String paramName = el.getAttribute(ID_ATTRIBUTE);
            if (el.hasChildNodes()) {
                String val = el.getFirstChild().getNodeValue();
                if (paramName != null && val != null) {
                    validationParams.put(paramName, val);
                }
            }
        }
    }
    // setting the recommededConfigurations for this configValidator
    validator.setRecommendedConfigurations(validationParams);
    return validator;
}

From source file:org.wso2.carbon.humantask.core.engine.util.CommonTaskUtil.java

/**
 * Returns the element with the given name.
 *
 * @param inputMessage : The input message.
 * @param partName     : The part name for which the data element is required.
 * @return : The matching element./*from  w  ww . j  a va2  s .  com*/
 */
public static Element getMessagePart(MessageDAO inputMessage, String partName) {
    Element node = inputMessage.getBodyData();
    if (node.hasChildNodes()) {
        Element matchingElement = null;

        if (node.getElementsByTagName(partName).getLength() > 0) {
            matchingElement = (Element) node.getElementsByTagName(partName).item(0);
        }

        if (matchingElement != null && matchingElement.getFirstChild() != null) {
            return (Element) matchingElement.getFirstChild();
        }

        return matchingElement;
    } else {
        throw new HumanTaskRuntimeException("The input message does not have any child elements");
    }

}

From source file:org.xwiki.filter.xml.internal.parameter.XStreamParameterManager.java

@Override
public Object unSerialize(Type type, Element rootElement) {
    if (type != null && !rootElement.hasChildNodes()) {
        Object value = XMLUtils.emptyValue(ReflectionUtils.getTypeClass(type));
        if (value != null) {
            return value;
        }/*from ww  w .j ava2s . co  m*/
    }

    DataHolder dataHolder = new MapBackedDataHolder();

    dataHolder.put(DDEFAULTTYPE_NAME, type);

    return this.xstream.unmarshal(new DomReader(rootElement), null, dataHolder);
}

From source file:org.xwiki.rendering.xdomxmlcurrent.internal.parameter.XStreamParameterManager.java

@Override
public Object unSerialize(Type type, Element rootElement) {
    if (type != null && !rootElement.hasChildNodes()) {
        Object value = XDOMXMLCurrentUtils.defaultValue(ReflectionUtils.getTypeClass(type));
        if (value != null) {
            return value;
        }/*from   w  w w.  j  a v  a 2s  . c o  m*/
    }

    DataHolder dataHolder = new MapBackedDataHolder();

    dataHolder.put("type", type);

    return this.xstream.unmarshal(new DomReader(rootElement), null, dataHolder);
}

From source file:org.xwiki.rendering.xml.internal.parameter.XStreamParameterManager.java

@Override
public Object unSerialize(Type type, Element rootElement) {
    if (type != null && !rootElement.hasChildNodes()) {
        Object value = XMLUtils.defaultValue(ReflectionUtils.getTypeClass(type));
        if (value != null) {
            return value;
        }//from   w  w w.j  a v  a  2 s . c  o m
    }

    DataHolder dataHolder = new MapBackedDataHolder();

    dataHolder.put(TYPE_NAME, type);

    return this.xstream.unmarshal(new DomReader(rootElement), null, dataHolder);
}

From source file:uk.co.anthonycampbell.java.mp4reader.util.Util.java

/**
 * Utility method to parse iTunes meta XML.
 * //ww  w .ja  va2  s. c  o m
 * @param xml - the XML to parse.
 */
public static Map<String, List<String>> parseITunesMeta(final String xml) {
    // Initialise result
    final Map<String, List<String>> iTunesMap = new HashMap<>();

    // Validate
    if (StringUtils.isNotEmpty(xml)) {
        try {
            final InputSource inputSource = new InputSource();
            inputSource.setCharacterStream(new StringReader(xml));

            final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            final DocumentBuilder builder = factory.newDocumentBuilder();
            final Document document = builder.parse(inputSource);

            final NodeList plists = document.getElementsByTagName("plist");
            for (int i = 0; i < plists.getLength(); ++i) {
                final Element plist = (Element) plists.item(i);

                if (plist != null && plist.hasChildNodes()) {
                    final NodeList nodes = plist.getChildNodes();

                    if (nodes != null) {
                        for (int j = 0; j < nodes.getLength(); ++j) {
                            final Node node = nodes.item(j);

                            if (node != null && node.getNodeType() == Node.ELEMENT_NODE
                                    && "dict".equals(node.getNodeName())) {
                                iTunesMap.putAll(parseDictionary(node));
                            }
                        }
                    }
                }
            }
        } catch (ParserConfigurationException pce) {
        } catch (SAXException saxe) {
        } catch (IOException ioe) {
        }

    } else {
        throw new IllegalArgumentException("Provided XML is invalid! (xml=" + xml + ")");
    }

    return iTunesMap;
}

From source file:util.XmlWriter.java

public void write(Element element, int tabs) throws IOException {
    if (!isNewLine)
        write(endl);/*from w ww  . j  a v  a  2 s .  co m*/
    if (!element.hasChildNodes()) {
        writeTabs(tabs);
        write("<" + element.getTagName() + writeAttributes(element) + "/>");
    } else {
        writeTabs(tabs);
        write("<" + element.getTagName() + writeAttributes(element) + ">");
        write(element.getChildNodes(), tabs + 1);
        if (isNewLine)
            writeTabs(tabs);
        write("</" + element.getTagName() + ">");
    }
    write(endl);
}