Example usage for org.w3c.dom Document getFirstChild

List of usage examples for org.w3c.dom Document getFirstChild

Introduction

In this page you can find the example usage for org.w3c.dom Document getFirstChild.

Prototype

public Node getFirstChild();

Source Link

Document

The first child of this node.

Usage

From source file:org.n52.wps.server.handler.RequestHandler.java

/**
 * Handles requests of type HTTP_POST (currently executeProcess). A Document
 * is used to represent the client input. This Document must first be parsed
 * from an InputStream./*from   w  w w  .  j  a  v  a 2 s .  c o  m*/
 * 
 * @param is
 *            The client input
 * @param os
 *            The OutputStream to write the response to.
 * @throws ExceptionReport
 */
public RequestHandler(InputStream is, OutputStream os) throws ExceptionReport {
    String nodeName, localName, nodeURI, version = null;
    Document doc;
    this.os = os;

    boolean isCapabilitiesNode = false;

    try {
        System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
                "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");

        DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
        fac.setNamespaceAware(true);

        // parse the InputStream to create a Document
        doc = fac.newDocumentBuilder().parse(is);

        // Get the first non-comment child.
        Node child = doc.getFirstChild();
        while (child.getNodeName().compareTo("#comment") == 0) {
            child = child.getNextSibling();
        }
        nodeName = child.getNodeName();
        localName = child.getLocalName();
        nodeURI = child.getNamespaceURI();
        Node versionNode = child.getAttributes().getNamedItem("version");

        /*
         * check for service parameter. this has to be present for all requests
         */
        Node serviceNode = child.getAttributes().getNamedItem("service");

        if (serviceNode == null) {
            throw new ExceptionReport("Parameter <service> not specified.",
                    ExceptionReport.MISSING_PARAMETER_VALUE, "service");
        } else {
            if (!serviceNode.getNodeValue().equalsIgnoreCase("WPS")) {
                throw new ExceptionReport("Parameter <service> not specified.",
                        ExceptionReport.INVALID_PARAMETER_VALUE, "service");
            }
        }

        isCapabilitiesNode = nodeName.toLowerCase().contains("capabilities");
        if (versionNode == null && !isCapabilitiesNode) {
            throw new ExceptionReport("Parameter <version> not specified.",
                    ExceptionReport.MISSING_PARAMETER_VALUE, "version");
        }
        //TODO: I think this can be removed, as capabilities requests do not have a version parameter (BenjaminPross)
        if (!isCapabilitiesNode) {
            //            version = child.getFirstChild().getTextContent();//.getNextSibling().getFirstChild().getNextSibling().getFirstChild().getNodeValue();
            version = child.getAttributes().getNamedItem("version").getNodeValue();
        }
        /*
         * check language, if not supported, return ExceptionReport
         * Fix for https://bugzilla.52north.org/show_bug.cgi?id=905
         */
        Node languageNode = child.getAttributes().getNamedItem("language");
        if (languageNode != null) {
            String language = languageNode.getNodeValue();
            Request.checkLanguageSupported(language);
        }
    } catch (SAXException e) {
        throw new ExceptionReport("There went something wrong with parsing the POST data: " + e.getMessage(),
                ExceptionReport.NO_APPLICABLE_CODE, e);
    } catch (IOException e) {
        throw new ExceptionReport("There went something wrong with the network connection.",
                ExceptionReport.NO_APPLICABLE_CODE, e);
    } catch (ParserConfigurationException e) {
        throw new ExceptionReport("There is a internal parser configuration error",
                ExceptionReport.NO_APPLICABLE_CODE, e);
    }
    //Fix for Bug 904 https://bugzilla.52north.org/show_bug.cgi?id=904
    if (!isCapabilitiesNode && version == null) {
        throw new ExceptionReport("Parameter <version> not specified.", ExceptionReport.MISSING_PARAMETER_VALUE,
                "version");
    }
    if (!isCapabilitiesNode && !version.equals(Request.SUPPORTED_VERSION)) {
        throw new ExceptionReport("Version not supported.", ExceptionReport.INVALID_PARAMETER_VALUE, "version");
    }
    // get the request type
    if (nodeURI.equals(WebProcessingService.WPS_NAMESPACE) && localName.equals("Execute")) {
        req = new ExecuteRequest(doc);
        setResponseMimeType((ExecuteRequest) req);
    } else if (nodeURI.equals(WebProcessingService.WPS_NAMESPACE) && localName.equals("GetCapabilities")) {
        req = new CapabilitiesRequest(doc);
        this.responseMimeType = "text/xml";
    } else if (nodeURI.equals(WebProcessingService.WPS_NAMESPACE) && localName.equals("DescribeProcess")) {
        req = new DescribeProcessRequest(doc);
        this.responseMimeType = "text/xml";

    } else if (!localName.equals("Execute")) {
        throw new ExceptionReport(
                "The requested Operation not supported or not applicable to the specification: " + nodeName,
                ExceptionReport.OPERATION_NOT_SUPPORTED, localName);
    } else if (nodeURI.equals(WebProcessingService.WPS_NAMESPACE)) {
        throw new ExceptionReport("specified namespace is not supported: " + nodeURI,
                ExceptionReport.INVALID_PARAMETER_VALUE);
    }
}

From source file:org.n52.wps.server.request.CapabilitiesRequest.java

public CapabilitiesRequest(Document doc) throws ExceptionReport {
    super(doc);// w w w.  j  a va 2s  . c o  m
    this.map = new CaseInsensitiveMap();

    Node fc = this.doc.getFirstChild();
    String name = fc.getNodeName();
    this.map.put(REQUEST_DOC, name);

    Node serviceItem = fc.getAttributes().getNamedItem("service");
    if (serviceItem != null) {
        String service = serviceItem.getNodeValue();
        String[] serviceArray = { service };

        this.map.put(PARAM_SERVICE, serviceArray);
    }

    NodeList nList = doc.getFirstChild().getChildNodes();
    ArrayList<String> versionList = new ArrayList<String>();

    for (int i = 0; i < nList.getLength(); i++) {
        Node n = nList.item(i);
        if (n.getLocalName() != null) {
            if (n.getLocalName().equalsIgnoreCase(ACCEPT_VERSIONS_ELEMENT_NAME)) {

                NodeList nList2 = n.getChildNodes();

                for (int j = 0; j < nList2.getLength(); j++) {
                    Node n2 = nList2.item(j);

                    if (n2.getLocalName() != null
                            && n2.getLocalName().equalsIgnoreCase(RequestHandler.VERSION_ATTRIBUTE_NAME)) {
                        versionList.add(n2.getTextContent());
                    }
                }
                break;
            }
        }
    }

    if (!versionList.isEmpty()) {
        this.map.put(PARAM_VERSION, versionList.toArray(new String[versionList.size()]));
    }

}

From source file:org.n52.wps.server.request.DescribeProcessRequest.java

/**
 * Creates a DescribeProcessRequest based on a Document (SOAP?)
 * @param doc The client input/*  w w  w. j  a  v a2s  .  com*/
 * @throws ExceptionReport
 */
public DescribeProcessRequest(Document doc) throws ExceptionReport {
    super(doc);

    //put the respective elements of the document in the map
    NamedNodeMap nnm = doc.getFirstChild().getAttributes();

    map = new CaseInsensitiveMap();

    for (int i = 0; i < nnm.getLength(); i++) {

        Node n = nnm.item(i);
        if (n.getLocalName().equalsIgnoreCase("service")) {
            map.put(n.getLocalName(), new String[] { n.getNodeValue() });
        } else if (n.getLocalName().equalsIgnoreCase("version")) {
            map.put(n.getLocalName(), new String[] { n.getNodeValue() });
        }
    }
    //get identifier
    String identifierList = "";

    NodeList nList = doc.getFirstChild().getChildNodes();

    boolean identifierParameterExists = false;

    for (int i = 0; i < nList.getLength(); i++) {
        Node n = nList.item(i);
        if (n.getLocalName() != null && n.getLocalName().equalsIgnoreCase("identifier")) {
            identifierParameterExists = true;
            String s = n.getTextContent();
            if (s != null && !s.isEmpty()) {
                identifierList = identifierList.concat(s + ",");
            }
        }
    }
    if (identifierParameterExists) {
        map.put("identifier", new String[] { identifierList });
    }
}

From source file:org.ojbc.util.fedquery.entityResolution.EntityResolutionResponseHandlerAggregator.java

@SuppressWarnings({ "unchecked", "rawtypes" })
public void aggregateMergedMessageWithErrorResponses(Exchange groupedExchange) throws Exception {
    //Get the grouped exchanged consisting of the aggregated search results and merged results
    List<Exchange> grouped = groupedExchange.getProperty(Exchange.GROUPED_EXCHANGE, List.class);

    boolean responseHasErrors = false;
    Document erResponseBodyDocument = null;
    Document psResultsBeforeER = null;

    for (Exchange exchange : grouped) {
        //This is the original exchange, it contains the aggregated response message before the Person Search to ER XSLT
        if (grouped.indexOf(exchange) == 0) {
            String messageID = (String) exchange.getIn().getHeader("federatedQueryRequestGUID");

            //The new grouped exchange does not get the message headers from the original exchange so we manually copy the message ID
            groupedExchange.getIn().setHeader("federatedQueryRequestGUID", messageID);

            //Get header to see if we have error nodes.  This is the exchange before calling ER so it has these headers, subsequent exchanges do not.
            String errorResponseNodeCountString = (String) exchange.getIn().getHeader("errorResponseNodeCount");

            Integer errorResponseNodeCount = null;

            if (errorResponseNodeCountString != null) {
                errorResponseNodeCount = Integer.valueOf(errorResponseNodeCountString);
            } else {
                errorResponseNodeCount = 0;
            }//from   ww w  . java  2  s  . c  o m

            if (errorResponseNodeCount > 0) {
                responseHasErrors = true;

                if (exchange.getIn().getBody().getClass().equals("java.lang.String")) {
                    String aggregatedResponse = (String) exchange.getIn().getBody();

                    //Load up the aggregated results into a document
                    psResultsBeforeER = OJBUtils.loadXMLFromString(aggregatedResponse);

                }

                //Load up the aggregated results into a document
                psResultsBeforeER = exchange.getIn().getBody(Document.class);
            }

        }

        //This is the actual response from the ER service, it will always be exchange indexed at position 1
        else {
            //Uncomment the line below to see the individual aggregated message
            //log.debug("This is the body of the exchange in the exchange group: " + exchange.getIn().getBody());

            CxfPayload cxfPayload = (CxfPayload) exchange.getIn().getBody();
            List<Element> elementList = cxfPayload.getBody();

            erResponseBodyDocument = elementList.get(0).getOwnerDocument();
        }

    }

    //The ER service did not return with an actual response, it is down or has timed out.  Set a static error response and return.
    if (erResponseBodyDocument == null) {
        String returnMessage = MergeNotificationErrorProcessor
                .returnMergeNotificationErrorMessageEntityResolution();
        groupedExchange.getIn().setBody(returnMessage);
        return;
    }

    //If we have errors, splice them into the response
    if (responseHasErrors) {
        log.debug("Response has errors, splice them in here");

        NodeList list = psResultsBeforeER.getElementsByTagNameNS(
                "http://ojbc.org/IEPD/Extensions/SearchResultsMetadata/1.0", "SearchResultsMetadata");
        Element searchResultsMetadataElement = (Element) erResponseBodyDocument.importNode(list.item(0), true);

        Element searchResultsMetadataCollectionElement = erResponseBodyDocument.createElementNS(
                "http://nij.gov/IEPD/Exchange/EntityMergeResultMessage/1.0", "SearchResultsMetadataCollection");
        searchResultsMetadataCollectionElement.appendChild(searchResultsMetadataElement);

        erResponseBodyDocument.getFirstChild().appendChild(searchResultsMetadataCollectionElement);

    }

    //Set the response
    groupedExchange.getIn().setBody(erResponseBodyDocument);

}

From source file:org.omg.bpmn.miwg.util.xml.XPathUtil.java

/**
 * Returns result of xpath query on document's first child node. See {@link #getQueryResult(Node, String)}.
 * //from   www .  java 2s  .co m
 * @throws XPathExpressionException
 */
public static NodeList getQueryResult(Document document, String query) throws XPathExpressionException {
    return getQueryResult(document.getFirstChild(), query);
}

From source file:org.openbravo.erpCommon.modules.ImportModule.java

/**
 * Adds a single classpath entry to the xml file
 *///from  w  w w  .ja  va 2s. c  o  m
private void addClassPathEntry(Document doc, String dir) throws Exception {
    log4j.info("adding entry for directory" + dir);
    final Node root = doc.getFirstChild();
    final Node classpath = doc.createElement("classpathentry");
    final NamedNodeMap cpAttributes = classpath.getAttributes();

    Attr attr = doc.createAttribute("kind");
    attr.setValue("src");
    cpAttributes.setNamedItem(attr);

    attr = doc.createAttribute("path");
    attr.setValue(dir);
    cpAttributes.setNamedItem(attr);

    root.appendChild(classpath);

}

From source file:org.openehealth.coms.cc.web_frontend.consentcreator.service.DocumentFactory.java

/**
 * Creates a PolicySet for the given user under the aspect whether he wants
 * to participate or not./*  w w w  .  j  a  v  a  2 s .  c o m*/
 * 
 * @param participation
 * @param user
 * @return
 */
public Document getSkeletonPolicySet(boolean participation, User user) {

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

    Document domPolicySet = null;

    String document = urlPolicySetSkeleton.toString();
    String rule = "";
    String text = "";

    if (participation) {
        text = "Dies ist die Einwilligungserklrung von " + user.getForename() + " " + user.getName();
        rule = urlRuleBasicParticipation.toString();
    } else {
        text = user.getForename() + " " + user.getName()
                + " verweigert mit diesem Dokument die Teilnahme an ISIS";
        rule = urlRuleDenyParticipation.toString();
    }

    try {
        DocumentBuilder db = dbf.newDocumentBuilder();

        domPolicySet = db.parse(document);

        NodeList listDesc = domPolicySet.getDocumentElement().getElementsByTagName("Description");

        listDesc.item(0).setTextContent(text);

        Document rdw = db.parse(rule);

        Node nm = rdw.getFirstChild();

        Element el = (Element) nm;

        Date k = new Date();

        el.setAttribute("RuleId", "urn:oasis:names:tc:xacml:2.0:example:ruleid:" + k.getTime());

        NodeList t = rdw.getElementsByTagName("AttributeValue");

        String value = getResources().get(0).getIdentifier();

        t.item(0).setNodeValue(value);

        Node f = domPolicySet.importNode(rdw.getDocumentElement(), true);

        NodeList l = domPolicySet.getElementsByTagName("Policy");

        l.item(3).appendChild(f);

        domPolicySet.getElementsByTagName("AttributeValue").item(1).setTextContent(value);

        if (!participation) {

            l.item(0).getParentNode().removeChild(l.item(0));
            l.item(0).getParentNode().removeChild(l.item(0));
            l.item(0).getParentNode().removeChild(l.item(0));
        }

    } catch (Exception e) {
        Logger.getLogger(this.getClass()).error(e);
    }

    return domPolicySet;
}

From source file:org.openengsb.openengsbplugin.base.ConfiguredMojo.java

private void insertConfigProfileIntoOrigPom(Document originalPom, Document mojoConfiguration,
        String profileName) throws XPathExpressionException {
    Node profileNode = mojoConfiguration.getFirstChild();

    Node idNode = mojoConfiguration.createElementNS(POM_NS_URI, "id");
    idNode.setTextContent(profileName);// w  ww.j ava2  s  .  c  o  m
    profileNode.insertBefore(idNode, profileNode.getFirstChild());

    Node importedProfileNode = originalPom.importNode(profileNode, true);

    Tools.insertDomNode(originalPom, importedProfileNode, POM_PROFILE_XPATH, NS_CONTEXT);
}

From source file:org.openhab.binding.yamahareceiver.internal.protocol.xml.DeviceDescriptorXML.java

/**
 * Tires to get the XML descriptor for the AVR
 *
 * @param con/*w  ww  .  j a  va  2s.co  m*/
 * @return
 */
private Node tryGetDescriptor(XMLConnection con) {
    for (String path : Arrays.asList("/YamahaRemoteControl/desc.xml", "/YamahaRemoteControl/UnitDesc.xml")) {
        try {
            String descXml = con.getResponse(path);
            Document doc = XMLUtils.xml(descXml);
            Node root = doc.getFirstChild();
            if (root != null && "Unit_Description".equals(root.getNodeName())) {
                logger.debug("Retrieved descriptor from {}", path);
                return root;
            }
            logger.debug("The {} response was invalid: {}", path, descXml);
        } catch (IOException e) {
            // The XML document under specified path does not exist for this model
            logger.debug("No descriptor at path {}", path);
        } catch (Exception e) {
            // Note: We were able to get the XML, but likely cannot parse it properly
            logger.warn("Could not parse descriptor at path {}", path, e);
            break;
        }
    }
    logger.warn("Could not retrieve descriptor");
    return null;
}

From source file:org.openhab.binding.yamahareceiver.internal.protocol.xml.InputWithDabControlXML.java

@Override
public void update() throws IOException, ReceivedMessageParseException {
    AbstractConnection com = comReference.get();
    String response = com.sendReceive(wrInput("<Play_Info>GetParam</Play_Info>"));
    Document doc = XMLUtils.xml(response);
    if (doc.getFirstChild() == null) {
        throw new ReceivedMessageParseException("<Play_Info>GetParam failed: " + response);
    }/* w  w w  .j  a  va 2s. co m*/

    // @formatter:off

    //Sample response:
    //<YAMAHA_AV rsp="GET" RC="0">
    //    <DAB>
    //        <Play_Info>
    //            <Feature_Availability>Ready</Feature_Availability>
    //            <FM>
    //                <Preset>
    //                    <Preset_Sel>1</Preset_Sel>
    //                </Preset>
    //                <Tuning>
    //                    <Freq>
    //                        <Val>9945</Val>
    //                        <Exp>2</Exp>
    //                        <Unit>MHz</Unit>
    //                    </Freq>
    //                </Tuning>
    //                <FM_Mode>Auto</FM_Mode>
    //                <Signal_Info>
    //                    <Tuned>Assert</Tuned>
    //                    <Stereo>Assert</Stereo>
    //                </Signal_Info>
    //                <Meta_Info>
    //                    <Program_Type>POP M</Program_Type>
    //                    <Program_Service>  22:59</Program_Service>
    //                    <Radio_Text>tel. 22 333 33 33   * Trojka *   e-mail: trojka@polskieradio.pl</Radio_Text>
    //                    <Clock_Time>22:59</Clock_Time>
    //                </Meta_Info>
    //            </FM>
    //            <DAB>
    //                <Status>Ready</Status>
    //                <Preset>
    //                    <Preset_Sel>No Preset</Preset_Sel>
    //                </Preset>
    //                <ID>2</ID>
    //                <Signal_Info>
    //                    <Freq>
    //                        <Val>218640</Val>
    //                        <Exp>3</Exp>
    //                        <Unit>MHz</Unit>
    //                    </Freq>
    //                    <Category>Primary</Category>
    //                    <Audio_Mode>Stereo</Audio_Mode>
    //                    <Bit_Rate>
    //                        <Val>128</Val>
    //                        <Exp>0</Exp>
    //                        <Unit>Kbps</Unit>
    //                    </Bit_Rate>
    //                    <Quality>82</Quality>
    //                    <Tune_Aid>45</Tune_Aid>
    //                    <Off_Air>Negate</Off_Air>
    //                    <DAB_PLUS>Assert</DAB_PLUS>
    //                </Signal_Info>
    //                <Meta_Info>
    //                    <Ch_Label>11B</Ch_Label>
    //                    <Service_Label>PR Czwrka</Service_Label>
    //                    <DLS>Kluboteka  Polskie Radio S.A.</DLS>
    //                    <Ensemble_Label>Polskie Radio</Ensemble_Label>
    //                    <Program_Type>Pop</Program_Type>
    //                    <Date_and_Time>12AUG&apos;17 23:47</Date_and_Time>
    //                </Meta_Info>
    //            </DAB>
    //            <Band>FM</Band>
    //        </Play_Info>
    //    </DAB>
    //</YAMAHA_AV>

    // @formatter:on

    DabBandState msgForBand = new DabBandState();
    PresetInfoState msgForPreset = new PresetInfoState();
    PlayInfoState msgForPlayInfo = new PlayInfoState();

    msgForBand.band = XMLUtils.getNodeContentOrDefault(doc.getFirstChild(), "DAB/Play_Info/Band",
            msgForBand.band);
    logger.debug("Band set to {} for input {}", msgForBand.band, inputID);

    // store last state of band
    bandState = msgForBand;

    if (StringUtils.isEmpty(msgForBand.band)) {
        logger.warn(
                "Band is unknown for input {}, therefore preset and playback information will not be available",
                inputID);
    } else {
        Node playInfoNode = XMLUtils.getNode(doc.getFirstChild(), "DAB/Play_Info/" + msgForBand.band);

        msgForPreset.presetChannel = XMLUtils.getNodeContentOrDefault(playInfoNode, "Preset/Preset_Sel", -1);
        logger.debug("Preset set to {} for input {}", msgForPreset.presetChannel, inputID);

        Node metaInfoNode = XMLUtils.getNode(playInfoNode, "Meta_Info");
        if (metaInfoNode != null) {
            msgForPlayInfo.album = XMLUtils.getNodeContentOrDefault(metaInfoNode, "Program_Type",
                    msgForPlayInfo.album);
            if (BAND_FM.equals(msgForBand.band)) {
                msgForPlayInfo.station = XMLUtils.getNodeContentOrDefault(metaInfoNode, "Program_Service",
                        msgForPlayInfo.station);
                msgForPlayInfo.artist = XMLUtils.getNodeContentOrDefault(metaInfoNode, "Station",
                        msgForPlayInfo.artist);
                msgForPlayInfo.song = XMLUtils.getNodeContentOrDefault(metaInfoNode, "Radio_Text",
                        msgForPlayInfo.song);
            } else if (BAND_DAB.equals(msgForBand.band)) {
                msgForPlayInfo.station = XMLUtils.getNodeContentOrDefault(metaInfoNode, "Service_Label",
                        msgForPlayInfo.station);
                msgForPlayInfo.artist = XMLUtils.getNodeContentOrDefault(metaInfoNode, "Ensemble_Label",
                        msgForPlayInfo.artist);
                msgForPlayInfo.song = XMLUtils.getNodeContentOrDefault(metaInfoNode, "DLS",
                        msgForPlayInfo.song);
            }
        }
    }

    // DAB does not provide channel names, the channel list will be empty
    msgForPreset.presetChannelNamesChanged = true;
    msgForPreset.presetChannelNames = new String[0];

    if (observerForBand != null) {
        observerForBand.dabBandUpdated(msgForBand);
    }
    if (observerForPreset != null) {
        observerForPreset.presetInfoUpdated(msgForPreset);
    }
    if (observerForPlayInfo != null) {
        observerForPlayInfo.playInfoUpdated(msgForPlayInfo);
    }
}