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:com.marklogic.client.functionaltest.TestSparqlQueryManager.java

@Test
public void testExecuteDescribeFromRDFJSON() throws IOException, SAXException, ParserConfigurationException {
    System.out.println("In SPARQL Query Manager Test testExecuteDescribeFromRDFJSON method");
    SPARQLQueryManager sparqlQmgr = readclient.newSPARQLQueryManager();
    StringBuffer sparqlQuery = new StringBuffer().append("DESCRIBE <http://example.org/about>");

    SPARQLQueryDefinition qdef = sparqlQmgr.newQueryDefinition(sparqlQuery.toString());
    String jsonResults = sparqlQmgr.executeDescribe(qdef, new StringHandle()).get();
    // Verify result 1 value.
    System.out.println(jsonResults);
    String[] resultString = jsonResults.split(" ");
    assertEquals("Method testExecuteDescribeFromRDFJSON subject is incorrect", "<http://example.org/about>",
            resultString[0]);/*  w w w. ja v a  2 s .  co m*/
    assertEquals("Method testExecuteDescribeFromRDFJSON predicate is incorrect",
            "<http://purl.org/dc/elements/1.1/title>", resultString[1]);
    String objectStr = resultString[2] + " " + resultString[3];
    assertEquals("Method testExecuteDescribeFromRDFJSON object is incorrect", "\"Anna's Homepage\"", objectStr);

    // Verifying default mime types- Using JacksonHandle
    JacksonHandle jh = new JacksonHandle();
    JsonNode jsonNodes = sparqlQmgr.executeDescribe(qdef, jh).get();
    JsonNode jsonNodeValue = jsonNodes.path("http://example.org/about")
            .path("http://purl.org/dc/elements/1.1/title").get(0);

    // Verify Mime type on the handle and value.
    System.out.println("testQueryOnMultibyeGraphName query result size is " + jsonNodeValue.get("value"));
    assertEquals("Element person's value incorrect", RDFMimeTypes.RDFJSON, jh.getMimetype());
    assertEquals("Result returned from testQueryOnMultibyeGraphName query is incorrect ", "Anna\'s Homepage",
            jsonNodeValue.get("value").asText());

    // Verifying default mime types- Using DOMHandle
    DOMHandle dh = new DOMHandle();
    Document xmlDoc = sparqlQmgr.executeDescribe(qdef, dh).get();

    Node description = xmlDoc.getFirstChild().getFirstChild();
    NamedNodeMap attrs = description.getFirstChild().getAttributes();
    // attrs NodeMap should have two nodes.
    assertEquals("Attribute length value incorrect", 2, attrs.getLength());

    if (attrs.item(0).getNodeName().equalsIgnoreCase("rdf:datatype")) {
        assertEquals("Element rdf:datatype value incorrect", "http://www.w3.org/2001/XMLSchema#string",
                attrs.item(0).getNodeValue());
        assertEquals("Element xmlns data value incorrect", "http://purl.org/dc/elements/1.1/",
                attrs.item(1).getNodeValue());
    } else if (attrs.item(0).getNodeName().equalsIgnoreCase("xmlns")) {
        assertEquals("Element rdf:datatype value incorrect", "http://www.w3.org/2001/XMLSchema#string",
                attrs.item(1).getNodeValue());
        assertEquals("Element xmlns data value incorrect", "http://purl.org/dc/elements/1.1/",
                attrs.item(0).getNodeValue());
    }
    String value = description.getFirstChild().getFirstChild().getNodeValue();
    assertEquals("Expected value read from DOMHandle incorrect", "Anna\'s Homepage", value);
}

From source file:com.marklogic.client.functionaltest.TestSparqlQueryManager.java

@Test
public void testBaseUri() throws IOException, SAXException, ParserConfigurationException {
    System.out.println("In SPARQL Query Manager Test testBaseUri method");
    SPARQLQueryManager sparqlQmgr = writeclient.newSPARQLQueryManager();

    StringBuffer sparqlQuery = new StringBuffer().append(" PREFIX foaf: <http://xmlns.com/foaf/0.1/>");
    sparqlQuery.append(newline);/*  w  w w. j  ava 2s . c o  m*/
    sparqlQuery.append("CONSTRUCT { <qatest1> <qatest2> <qatest3> }");
    sparqlQuery.append(newline);
    sparqlQuery.append("WHERE { ?s ?p ?o . } LIMIT 1");

    SPARQLQueryDefinition qdef = sparqlQmgr.newQueryDefinition(sparqlQuery.toString());

    // Base URI set.
    qdef.setBaseUri("http://qa.marklogic.com/functional/tests/one/");

    // Verifying Git Issue 356 also, below with JacksonHandle.
    JacksonHandle jh = new JacksonHandle();
    JsonNode jsonResults = sparqlQmgr.executeConstruct(qdef, jh).get();
    String s = jsonResults.fieldNames().next();
    String p = jsonResults.get(s).fieldNames().next();
    JsonNode o = jsonResults.get(s).get(p);

    // Verify the mimetype of the handle.
    assertEquals("Method testBaseUri MIME type is incorrect", RDFMimeTypes.RDFJSON, jh.getMimetype());
    assertEquals("Method testBaseUri in-memory subject base URI is incorrect",
            "http://qa.marklogic.com/functional/tests/one/qatest1", s);
    assertEquals("Method testBaseUri in-memory predicte base URI is incorrect",
            "http://qa.marklogic.com/functional/tests/one/qatest2", p);
    assertEquals("Method testBaseUri in-memory object base URI is incorrect",
            "http://qa.marklogic.com/functional/tests/one/qatest3", o.path(0).path("value").asText());

    // Verify if defaulting to RDFJSON when XMLHandle is used. Git Issue 356.
    DOMHandle handle = new DOMHandle();
    Document xmlDoc = sparqlQmgr.executeConstruct(qdef, handle).get();
    Node description = xmlDoc.getFirstChild().getFirstChild();
    NamedNodeMap attrs = description.getFirstChild().getAttributes();

    String oXML = attrs.getNamedItemNS("http://www.w3.org/1999/02/22-rdf-syntax-ns#", "resource")
            .getTextContent();

    assertEquals("Method testBaseUri MIME type is incorrect", RDFMimeTypes.RDFXML, handle.getMimetype());
    assertEquals("Method testBaseUri in-memory subject base URI is incorrect",
            "http://qa.marklogic.com/functional/tests/one/qatest1",
            description.getAttributes().item(0).getTextContent());
    assertEquals("Method testBaseUri in-memory predicate base URI is incorrect", "qatest2",
            description.getFirstChild().getNodeName());
    assertEquals("Method testBaseUri in-memory object base URI is incorrect",
            "http://qa.marklogic.com/functional/tests/one/qatest3", oXML);
}

From source file:edu.wpi.margrave.MCommunicator.java

public static void handleXMLCommand(InputStream commandStream) {
    DocumentBuilder docBuilder = null;
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    try {//w w  w  .  j ava 2  s .  c o m
        docBuilder = docFactory.newDocumentBuilder();
    } catch (ParserConfigurationException ex) {
        Logger.getLogger(MCommunicator.class.getName()).log(Level.SEVERE, null, ex);
        writeToLog(
                "\nParserConfigurationException at beginning of handleXMLCommand: " + ex.getLocalizedMessage());
        writeToLog("\nTerminating engine...");
        System.exit(200);
    }

    // Save this command for use in exception messages
    //MEnvironment.lastCommandReceived = command.trim();

    Document inputXMLDoc = null;

    try {
        // doc = docBuilder.parse(new InputSource(new StringReader(command)));
        writeToLog("========================================\n========================================\n");
        writeToLog("\n" + commandStream.available());

        StringBuffer inputStringBuffer = new StringBuffer();
        while (true) {
            // if available=0; we want to block. But don't want to allocate too much room:
            if (commandStream.available() < 1) {
                int b = commandStream.read();
                inputStringBuffer.append((char) b);
                //writeToLog("\n(Blocked and then got) character: `"+(char)b+"`");
            } else {
                byte[] inputBytes = new byte[commandStream.available()];
                @SuppressWarnings("unused")
                int bytesRead = commandStream.read(inputBytes);
                String block = new String(inputBytes);
                inputStringBuffer.append(block);
                //writeToLog("\n(Didn't block for) String: `"+block+"`");
            }

            // Bad kludge. Couldn't get proper XML parse function working, so
            // did this. Should re-write (preferably with correct XML handling functions!)
            // The trim() call below is especially egregious... - TN

            String sMargraveCommandEnding = "</MARGRAVE-COMMAND>";
            String bufferStr = inputStringBuffer.toString();
            if (bufferStr.trim().endsWith(sMargraveCommandEnding))
                break;
        } // end while(true) for kludge

        String cmdString = inputStringBuffer.toString();
        writeToLog("\n\n*********************************\nDONE! Received command: `" + cmdString + "`\n");

        inputXMLDoc = docBuilder.parse(new InputSource(new StringReader(cmdString)));

        //doc = docBuilder.parse(commandStream);
        //doc = docBuilder.parse(new InputSource(commandStream));
        writeToLog((new Date()).toString());
        writeToLog("\nExecuting command: " + transformXMLToString(inputXMLDoc) + "\n");
    } // end try
    catch (SAXException ex) {
        Logger.getLogger(MCommunicator.class.getName()).log(Level.SEVERE, null, ex);
        writeToLog(
                "\nSAXException in handleXMLCommand while parsing command stream: " + ex.getLocalizedMessage());
    } catch (IOException ex) {
        Logger.getLogger(MCommunicator.class.getName()).log(Level.SEVERE, null, ex);
        writeToLog(
                "\nIOException in handleXMLCommand while parsing command stream: " + ex.getLocalizedMessage());
    }

    /////////////////////////////////////////////////////
    // Done parsing input. Now prepare the response.

    Document theResponse;
    try {
        // protect against getFirstChild() call
        if (inputXMLDoc != null)
            theResponse = xmlHelper(inputXMLDoc.getFirstChild(), "");
        else
            theResponse = MEnvironment.errorResponse(MEnvironment.sNotDocument, MEnvironment.sCommand, "");
    } catch (Exception e) {
        // Construct an exception response;
        theResponse = MEnvironment.exceptionResponse(e);
    } catch (Throwable e) {
        // This would ordinarily be a terrible thing to do (catching Throwable)
        // However, we need to warn the client that we're stuck.

        try {
            // First log that we got an exception:
            writeToLog("\n~~~ Throwable caught: " + e.getClass());
            writeToLog("\n    " + e.getLocalizedMessage());
            writeToLog("\n" + Arrays.toString(e.getStackTrace()));
            writeToLog("\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");
            theResponse = MEnvironment.exceptionResponse(e);
        } catch (Throwable f) {
            // If we can't even warn the client, at least close down the engine. Client will detect EOF.
            theResponse = null;
            System.exit(101);
        }

        // Last resort
        System.exit(100);
    }

    try {
        addBuffers(theResponse);

        writeToLog("Returning: " + transformXMLToString(theResponse) + "\n");
        out.write(transformXMLToByteArray(theResponse));
    } catch (IOException e) {
        // don't do this. would go through System.err
        //e.printStackTrace();
    }
    out.flush(); // ALWAYS FLUSH!

}

From source file:de.escidoc.core.test.EscidocTestBase.java

/**
 * Gets the root element of the provided document.
 * /*from ww  w. j  a  v  a2  s .  c o  m*/
 * @param doc
 *            The document to get the root element from.
 * @return Returns the first child of the document htat is an element node.
 * @throws Exception
 *             If anything fails.
 */
public static Element getRootElement(final Document doc) throws Exception {

    Node node = doc.getFirstChild();
    while (node != null) {
        if (node != null && node.getNodeType() == Node.ELEMENT_NODE) {
            return (Element) node;
        }
        node = node.getNextSibling();
    }
    return null;
}

From source file:com.ext.portlet.epsos.EpsosHelperService.java

private Node generateDispensedLinesHtml(List<ViewResult> dispensedLines, DocumentBuilder db) {
    String result = null;//from   w  ww  . j a v a 2s .  c o m
    StringBuffer buf = new StringBuffer(1000);
    buf.append("<table><caption>Dispensed Items</caption>");
    buf.append("<thead><tr styleCode=\"border-bottom: 2px solid black\">");
    buf.append(
            "<td>Identifier</td><td>Name</td><td>Strength</td><td>Form</td><td>Package</td><td>Quantity</td><td>Number of Packs</td></tr></thead><tbody>");
    for (int i = 0; i < dispensedLines.size(); i++) {
        ViewResult d_line = dispensedLines.get(i);
        /**
         * ViewResult d_line = new ViewResult(id, dispensed_id, dispensed_name, substitute,
                   dispensed_strength, dispensed_form, dispensed_package, dispensed_quantity, 
                   dispensed_nrOfPacks, prescriptionid, materialid, active);
         */

        buf.append("<tr>");

        buf.append("<td>");
        buf.append(d_line.getField9());
        buf.append("</td>");

        buf.append("<td>");
        buf.append(d_line.getField2());
        buf.append("</td>");

        buf.append("<td>");
        buf.append(d_line.getField4());
        buf.append("</td>");

        buf.append("<td>");
        buf.append(d_line.getField5());
        buf.append("</td>");

        buf.append("<td>");
        buf.append(d_line.getField6());
        buf.append("</td>");

        buf.append("<td>");
        buf.append(d_line.getField7());
        buf.append("</td>");

        buf.append("<td>");
        buf.append(d_line.getField8());
        buf.append("</td>");

        buf.append("</tr>");
    }
    buf.append("</tbody></table>");
    result = buf.toString();

    try {
        Document dom = db.parse(new ByteArrayInputStream(result.getBytes()));
        return dom.getFirstChild();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:be.docarch.odt2braille.PEF.java

/**
 * Converts the flat .odt filt to a .pef file according to the braille settings.
 *
 * This function/* w  w  w .  j av a2  s.  co  m*/
 * <ul>
 * <li>uses {@link ODT} to convert the .odt file to multiple DAISY-like xml files,</li>
 * <li>uses {@link LiblouisXML} to translate these files into braille, and</li>
 * <li>recombines these braille files into one single .pef file.</li>
 * </ul>
 *
 * First, the document <i>body</i> is processed and split in volumes, then the <i>page ranges</i> are calculated
 * and finally the <i>preliminary pages</i> of each volume are processed and inserted at the right places.
 * The checker checks the DAISY-like files and the volume lengths.
 *
 */

public boolean makePEF() throws IOException, ParserConfigurationException, TransformerException,
        InterruptedException, SAXException, ConversionException, LiblouisXMLException, Exception {

    logger.entering("PEF", "makePEF");

    Configuration settings = odt.getConfiguration();

    Element[] volumeElements;
    Element sectionElement;
    File bodyFile = null;
    File brailleFile = null;
    File preliminaryFile = null;

    List<Volume> volumes = manager.getVolumes();

    String volumeInfo = capitalizeFirstLetter(
            ResourceBundle.getBundle(L10N, settings.mainLocale).getString("in")) + " " + volumes.size() + " "
            + ResourceBundle.getBundle(L10N, settings.mainLocale)
                    .getString((volumes.size() > 1) ? "volumes" : "volume")
            + "\n@title\n@pages";

    volumeElements = new Element[volumes.size()];

    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    docFactory.setValidating(false);
    docFactory.setNamespaceAware(true);
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    DOMImplementation impl = docBuilder.getDOMImplementation();

    Document document = impl.createDocument(pefNS, "pef", null);
    Element root = document.getDocumentElement();
    root.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", pefNS);
    root.setAttributeNS(null, "version", "2008-1");

    Element headElement = document.createElementNS(pefNS, "head");
    Element metaElement = document.createElementNS(pefNS, "meta");
    metaElement.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:dc", "http://purl.org/dc/elements/1.1/");
    Element dcElement = document.createElementNS("http://purl.org/dc/elements/1.1/", "dc:identifier");
    dcElement.appendChild(document.createTextNode(Integer.toHexString((int) (Math.random() * 1000000)) + " "
            + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format((new Date()))));
    metaElement.appendChild(dcElement);
    dcElement = document.createElementNS("http://purl.org/dc/elements/1.1/", "dc:format");
    dcElement.appendChild(document.createTextNode("application/x-pef+xml"));
    metaElement.appendChild(dcElement);
    headElement.appendChild(metaElement);

    root.appendChild(headElement);

    int columns = pefSettings.getColumns();
    int rows = pefSettings.getRows();
    boolean duplex = pefSettings.getDuplex();
    int rowgap = pefSettings.getEightDots() ? 1 : 0;
    int beginPage = settings.getBeginningBraillePageNumber();

    if (statusIndicator != null) {
        statusIndicator.start();
        statusIndicator.setSteps(volumes.size());
        statusIndicator.setStatus(ResourceBundle.getBundle(L10N, statusIndicator.getPreferredLocale())
                .getString("statusIndicatorStep"));
    }

    for (int volumeCount = 0; volumeCount < volumes.size(); volumeCount++) {

        volumeElements[volumeCount] = document.createElementNS(pefNS, "volume");
        volumeElements[volumeCount].setAttributeNS(null, "cols", String.valueOf(columns));
        volumeElements[volumeCount].setAttributeNS(null, "rows",
                String.valueOf(rows + (int) Math.ceil(((rows - 1) * rowgap) / 4d)));
        volumeElements[volumeCount].setAttributeNS(null, "rowgap", String.valueOf(rowgap));
        volumeElements[volumeCount].setAttributeNS(null, "duplex", duplex ? "true" : "false");

        Volume volume = volumes.get(volumeCount);

        // Body section

        logger.info("Processing volume " + (volumeCount + 1) + " : " + volume.getTitle());

        if (!(volume instanceof PreliminaryVolume)) {

            bodyFile = File.createTempFile(TMP_NAME, ".daisy.body." + (volumeCount + 1) + ".xml", TMP_DIR);
            bodyFile.deleteOnExit();
            brailleFile = File.createTempFile(TMP_NAME, ".txt", TMP_DIR);
            brailleFile.deleteOnExit();

            odt.getBodyMatter(bodyFile, volume);
            liblouisXML.configure(bodyFile, brailleFile, false, beginPage);
            liblouisXML.run();

            // Read pages
            sectionElement = document.createElementNS(pefNS, "section");
            int pageCount = addPagesToSection(document, sectionElement, brailleFile, rows, columns, -1);
            volumeElements[volumeCount].appendChild(sectionElement);

            // Checker
            if (checker != null) {
                checker.checkDaisyFile(bodyFile);
            }

            // Braille page range
            volume.setBraillePagesStart(beginPage);
            volume.setNumberOfBraillePages(pageCount);
            beginPage += pageCount;

            // Print page range
            if (volume.getFrontMatter() && settings.getVolumeInfoEnabled()) {
                extractPrintPageRange(bodyFile, volume, settings);
            }
        }

        // Special symbols list
        if (volume.getSpecialSymbolListEnabled()) {
            extractSpecialSymbols(bodyFile, volume, volumeCount, settings);
        }

        // Preliminary section

        if (volume.getFrontMatter() || volume.getTableOfContent() || volume.getTranscribersNotesPageEnabled()
                || volume.getSpecialSymbolListEnabled()) {

            preliminaryFile = File.createTempFile(TMP_NAME, ".daisy.front." + (volumeCount + 1) + ".xml",
                    TMP_DIR);
            preliminaryFile.deleteOnExit();
            brailleFile = File.createTempFile(TMP_NAME, ".txt", TMP_DIR);
            brailleFile.deleteOnExit();

            odt.getFrontMatter(preliminaryFile, volume, volumeInfo);
            liblouisXML.configure(preliminaryFile, brailleFile, true,
                    volume.getTableOfContent() ? volume.getFirstBraillePage() : 1);
            liblouisXML.run();

            // Page range
            int pageCount = countPages(brailleFile, volume);
            volume.setNumberOfPreliminaryPages(pageCount);

            // Translate again with updated volume info and without volume separator marks
            brailleFile = File.createTempFile(TMP_NAME, ".txt", TMP_DIR);
            brailleFile.deleteOnExit();
            odt.getFrontMatter(preliminaryFile, volume, volumeInfo);
            liblouisXML.configure(preliminaryFile, brailleFile, false,
                    volume.getTableOfContent() ? volume.getFirstBraillePage() : 1);
            liblouisXML.run();

            // Read pages
            sectionElement = document.createElementNS(pefNS, "section");
            addPagesToSection(document, sectionElement, brailleFile, rows, columns, pageCount);
            volumeElements[volumeCount].insertBefore(sectionElement,
                    volumeElements[volumeCount].getFirstChild());

            // Checker
            if (checker != null) {
                checker.checkDaisyFile(preliminaryFile);
            }
        }

        if (statusIndicator != null) {
            statusIndicator.increment();
        }
    }

    if (checker != null) {
        checker.checkVolumes(volumes);
    }

    Element bodyElement = document.createElementNS(pefNS, "body");

    for (int volumeCount = 0; volumeCount < volumes.size(); volumeCount++) {
        bodyElement.appendChild(volumeElements[volumeCount]);
    }

    root.appendChild(bodyElement);

    document.insertBefore((ProcessingInstruction) document.createProcessingInstruction("xml-stylesheet",
            "type='text/css' href='pef.css'"), document.getFirstChild());

    OdtUtils.saveDOM(document, pefFile);

    logger.exiting("PEF", "makePEF");

    if (!validatePEF(pefFile)) {
        return false;
    }

    return true;
}

From source file:netinf.common.communication.MessageEncoderXML.java

private void encodeRSMDHTAck(Document xml, RSMDHTAck m, SerializeFormat serializeFormat) {

    appendElementWithValue(xml, xml.getFirstChild(), EL_USER_NAME, m.getUserName().toString());
}

From source file:netinf.common.communication.MessageEncoderXML.java

private void encodeESFFetchMissedEventsResponse(Document xml, ESFFetchMissedEventsResponse m,
        SerializeFormat serializeFormat) {
    appendElementWithValue(xml, xml.getFirstChild(), EL_PRIVATE_KEY, m.getPrivateKey().toString());
    appendElementWithValue(xml, xml.getFirstChild(), EL_USER_NAME, m.getUserName().toString());
    appendElementWithValue(xml, xml.getFirstChild(), EL_ERROR_MESSAGE, m.getErrorMessage().toString());

}