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:controllerTas.config.xml.TasControllerConfigXmlParser.java

public Object parseObject() throws IOException {
    try {//from   w  w w . j a  va  2  s  .  c  o m
        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
        Document doc = docBuilder.parse(new File(this.filePath));
        Node root = doc.getFirstChild();
        return newParsedObject(root);
    } catch (Throwable t) {
        t.printStackTrace();
        System.exit(-1);
    }
    return null; //unreachable
}

From source file:com.prowidesoftware.swift.io.parser.XMLParserTest.java

/**
 * Test for w3 dom parsing behavior/*w  ww .java 2s .c om*/
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws IOException
 */
@Test
public void testNode() throws ParserConfigurationException, SAXException, IOException {
    final String text = "<tag>line1\r\nline2</tag>";
    final DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    InputStream is = new ByteArrayInputStream(text.getBytes("UTF-8"));
    final Document doc = db.parse(is);
    Node n = doc.getFirstChild();
    //this proves that DOM parser removes original carriage return characters from XML
    assertEquals("line1\nline2", n.getFirstChild().getNodeValue());
}

From source file:com.l2jfree.gameserver.document.DocumentBase.java

final void parseDocument(Document doc) {
    final String defaultNodeName = getDefaultNodeName();

    for (Node n = doc.getFirstChild(); n != null; n = n.getNextSibling()) {
        if ("list".equalsIgnoreCase(n.getNodeName())) {
            for (Node d = n.getFirstChild(); d != null; d = d.getNextSibling()) {
                if (defaultNodeName.equalsIgnoreCase(d.getNodeName())) {
                    parseDefaultNode(d);
                } else if (d.getNodeType() == Node.ELEMENT_NODE) {
                    throw new IllegalStateException("Invalid tag <" + d.getNodeName() + ">");
                }/*from ww  w .j  a v a  2s  .co  m*/
            }
        } else if (defaultNodeName.equalsIgnoreCase(n.getNodeName())) {
            parseDefaultNode(n);
        } else if (n.getNodeType() == Node.ELEMENT_NODE) {
            throw new IllegalStateException("Invalid tag <" + n.getNodeName() + ">");
        }
    }
}

From source file:net.bpelunit.framework.control.deploy.activevos9.ActiveVOSAdministrativeFunctions.java

public void deployBpr(String bprFileName, byte[] contents) throws DeployException {
    AesDeployBprType deployBprInput = new AesDeployBprType();
    AesStringResponseType deployBpr;/* w w  w . j  a  v  a  2s  . co m*/

    deployBprInput.setBprFilename(bprFileName);
    deployBprInput.setBase64File(contents);
    deployBpr = getActiveBpelAdminPort().deployBpr(deployBprInput);

    String responseMessage = deployBpr.getResponse();
    try {
        Document xml = XMLUtil.parseXML(responseMessage);
        Node item = xml.getFirstChild().getAttributes().getNamedItem(ATTRIBUTE_ERROR_COUNT);
        if (Integer.parseInt(item.getTextContent()) != 0) {
            throw new DeployException("Errors while deploying process: " + responseMessage);
        }
    } catch (ParserConfigurationException e) {
        throw new DeployException("Internal error: " + e.getMessage(), e);
    } catch (SAXException e) {
        throw new DeployException("Internal reading response XML: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new DeployException(e.getMessage(), e);
    }
}

From source file:com.trifork.batchcopy.client.SosiUtil.java

private Node string2Node(String xmlstr) throws SAXException, IOException {
    InputSource inStream = new InputSource();
    inStream.setCharacterStream(new StringReader(xmlstr));

    Document docBody = builder.parse(inStream);
    return docBody.getFirstChild();
}

From source file:de.mpg.escidoc.services.transformation.Util.java

/**
 * Queries the CoNE service and transforms the result into a DOM node.
 * //from  w w  w .j  av  a 2s .  com
 * @param model The type of object (e.g. "persons")
 * @param name The query string.
 * @param ou Specialty for persons
 * @param coneSession A JSESSIONID to not produce a new session with each call.
 * @return A DOM node containing the results.
 */
public static Node queryConeExact(String model, String name, String ou) {
    DocumentBuilder documentBuilder;

    try {
        logger.info("queryConeExact: " + model + " name: " + name + " ou: " + ou);

        documentBuilder = DocumentBuilderFactoryImpl.newInstance().newDocumentBuilder();

        Document document = documentBuilder.newDocument();
        Element element = document.createElement("cone");
        document.appendChild(element);

        String queryUrl = PropertyReader.getProperty("escidoc.cone.service.url") + model
                + "/query?format=jquery&" + URLEncoder.encode("dc:title", "UTF-8") + "="
                + URLEncoder.encode("\"" + name + "\"", "UTF-8") + "&"
                + URLEncoder.encode("escidoc:position/eprints:affiliatedInstitution", "UTF-8") + "="
                + URLEncoder.encode("\"*" + ou + "*\"", "UTF-8");
        String detailsUrl = PropertyReader.getProperty("escidoc.cone.service.url") + model
                + "/resource/$1?format=rdf";
        HttpClient client = new HttpClient();
        client.getParams().setParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true);
        GetMethod method = new GetMethod(queryUrl);

        String coneSession = getConeSession();

        if (coneSession != null) {
            method.setRequestHeader("Cookie", "JSESSIONID=" + coneSession);
        }
        ProxyHelper.executeMethod(client, method);
        if (logger.isDebugEnabled()) {
            logger.debug("CoNE query: " + queryUrl + " returned " + method.getResponseBodyAsString());
        }
        if (method.getStatusCode() == 200) {
            ArrayList<String> results = new ArrayList<String>();
            results.addAll(Arrays.asList(method.getResponseBodyAsString().split("\n")));
            queryUrl = PropertyReader.getProperty("escidoc.cone.service.url") + model + "/query?format=jquery&"
                    + URLEncoder.encode("dcterms:alternative", "UTF-8") + "="
                    + URLEncoder.encode("\"" + name + "\"", "UTF-8") + "&"
                    + URLEncoder.encode("escidoc:position/eprints:affiliatedInstitution", "UTF-8") + "="
                    + URLEncoder.encode("\"*" + ou + "*\"", "UTF-8");
            client = new HttpClient();
            method = new GetMethod(queryUrl);
            if (coneSession != null) {
                method.setRequestHeader("Cookie", "JSESSIONID=" + coneSession);
            }
            ProxyHelper.executeMethod(client, method);
            if (logger.isDebugEnabled()) {
                logger.debug("CoNE query: " + queryUrl + " returned " + method.getResponseBodyAsString());
            }
            if (method.getStatusCode() == 200) {
                results.addAll(Arrays.asList(method.getResponseBodyAsString().split("\n")));
                Set<String> oldIds = new HashSet<String>();
                for (String result : results) {
                    if (!"".equals(result.trim())) {
                        String id = result.split("\\|")[1];
                        if (!oldIds.contains(id)) {
                            // TODO "&redirect=true" must be reinserted again
                            GetMethod detailMethod = new GetMethod(id + "?format=rdf&eSciDocUserHandle="
                                    + Base64.encode(AdminHelper.getAdminUserHandle().getBytes("UTF-8")));
                            detailMethod.setFollowRedirects(true);

                            ProxyHelper.setProxy(client, detailsUrl.replace("$1", id));
                            client.executeMethod(detailMethod);
                            // TODO "&redirect=true" must be reinserted again
                            if (logger.isDebugEnabled()) {
                                logger.debug("CoNE query: " + id + "?format=rdf&eSciDocUserHandle="
                                        + Base64.encode(AdminHelper.getAdminUserHandle().getBytes("UTF-8"))
                                        + " returned " + detailMethod.getResponseBodyAsString());
                            }
                            if (detailMethod.getStatusCode() == 200) {
                                Document details = documentBuilder
                                        .parse(detailMethod.getResponseBodyAsStream());
                                element.appendChild(document.importNode(details.getFirstChild(), true));
                            } else {
                                logger.error("Error querying CoNE: Status " + detailMethod.getStatusCode()
                                        + "\n" + detailMethod.getResponseBodyAsString());
                            }
                            oldIds.add(id);
                        }
                    }
                }
            }
        } else {
            logger.error("Error querying CoNE: Status " + method.getStatusCode() + "\n"
                    + method.getResponseBodyAsString());
        }
        return document;
    } catch (Exception e) {
        logger.error("Error querying CoNE service. This is normal during unit tests. "
                + "Otherwise it should be clarified if any measures have to be taken.", e);
        return null;
        //throw new RuntimeException(e);
    }
}

From source file:eu.apenet.dpt.standalone.gui.hgcreation.LevelTreeActions.java

private Node stringToNode(Document originalDoc, ReaderInputStream readerInputStream) throws Exception {
    Document doc = DOMUtil.createDocument(readerInputStream);
    return originalDoc.adoptNode(doc.getFirstChild());
}

From source file:XMLDocumentWriter.java

/**
 * Output the specified DOM Node object, printing it using the specified
 * indentation string//from   www  .j a  v a 2  s  .  c om
 */
public void write(Node node, String indent) {
    // The output depends on the type of the node
    switch (node.getNodeType()) {
    case Node.DOCUMENT_NODE: { // If its a Document node
        Document doc = (Document) node;
        out.println(indent + "<?xml version='1.0'?>"); // Output header
        Node child = doc.getFirstChild(); // Get the first node
        while (child != null) { // Loop 'till no more nodes
            write(child, indent); // Output node
            child = child.getNextSibling(); // Get next node
        }
        break;
    }
    case Node.DOCUMENT_TYPE_NODE: { // It is a <!DOCTYPE> tag
        DocumentType doctype = (DocumentType) node;
        // Note that the DOM Level 1 does not give us information about
        // the the public or system ids of the doctype, so we can't output
        // a complete <!DOCTYPE> tag here. We can do better with Level 2.
        out.println("<!DOCTYPE " + doctype.getName() + ">");
        break;
    }
    case Node.ELEMENT_NODE: { // Most nodes are Elements
        Element elt = (Element) node;
        out.print(indent + "<" + elt.getTagName()); // Begin start tag
        NamedNodeMap attrs = elt.getAttributes(); // Get attributes
        for (int i = 0; i < attrs.getLength(); i++) { // Loop through them
            Node a = attrs.item(i);
            out.print(" " + a.getNodeName() + "='" + // Print attr. name
                    fixup(a.getNodeValue()) + "'"); // Print attr. value
        }
        out.println(">"); // Finish start tag

        String newindent = indent + "    "; // Increase indent
        Node child = elt.getFirstChild(); // Get child
        while (child != null) { // Loop
            write(child, newindent); // Output child
            child = child.getNextSibling(); // Get next child
        }

        out.println(indent + "</" + // Output end tag
                elt.getTagName() + ">");
        break;
    }
    case Node.TEXT_NODE: { // Plain text node
        Text textNode = (Text) node;
        String text = textNode.getData().trim(); // Strip off space
        if ((text != null) && text.length() > 0) // If non-empty
            out.println(indent + fixup(text)); // print text
        break;
    }
    case Node.PROCESSING_INSTRUCTION_NODE: { // Handle PI nodes
        ProcessingInstruction pi = (ProcessingInstruction) node;
        out.println(indent + "<?" + pi.getTarget() + " " + pi.getData() + "?>");
        break;
    }
    case Node.ENTITY_REFERENCE_NODE: { // Handle entities
        out.println(indent + "&" + node.getNodeName() + ";");
        break;
    }
    case Node.CDATA_SECTION_NODE: { // Output CDATA sections
        CDATASection cdata = (CDATASection) node;
        // Careful! Don't put a CDATA section in the program itself!
        out.println(indent + "<" + "![CDATA[" + cdata.getData() + "]]" + ">");
        break;
    }
    case Node.COMMENT_NODE: { // Comments
        Comment c = (Comment) node;
        out.println(indent + "<!--" + c.getData() + "-->");
        break;
    }
    default: // Hopefully, this won't happen too much!
        System.err.println("Ignoring node: " + node.getClass().getName());
        break;
    }
}

From source file:net.sourceforge.eclipsetrader.news.providers.RSSNewsProvider.java

private void update() {
    Object[] o = oldItems.toArray();
    for (int i = 0; i < o.length; i++) {
        ((NewsItem) o[i]).setRecent(false);
        CorePlugin.getRepository().save((NewsItem) o[i]);
    }/* w ww  . j  av  a2 s . c  o m*/
    oldItems.clear();

    Job job = new Job(Messages.RSSNewsProvider_JobName) {
        @Override
        protected IStatus run(IProgressMonitor monitor) {
            File file = new File(Platform.getLocation().toFile(), "rss.xml"); //$NON-NLS-1$
            if (file.exists() == true) {
                try {
                    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                    DocumentBuilder builder = factory.newDocumentBuilder();
                    Document document = builder.parse(file);

                    Node firstNode = document.getFirstChild();

                    NodeList childNodes = firstNode.getChildNodes();
                    monitor.beginTask(Messages.RSSNewsProvider_TaskName, childNodes.getLength());
                    log.info("Start fetching RSS News"); //$NON-NLS-1$

                    for (int i = 0; i < childNodes.getLength(); i++) {
                        Node item = childNodes.item(i);
                        String nodeName = item.getNodeName();
                        if (nodeName.equalsIgnoreCase("source")) //$NON-NLS-1$
                            update(new URL(item.getFirstChild().getNodeValue()),
                                    item.getAttributes().getNamedItem("name").getNodeValue()); //$NON-NLS-1$

                        monitor.worked(1);
                    }
                } catch (Exception e) {
                    log.error(e, e);
                }
            }

            monitor.done();
            return Status.OK_STATUS;
        }
    };
    job.setUser(false);
    job.schedule();
}

From source file:net.sourceforge.fenixedu.util.stork.CanonicalAddressAttribute.java

private void setFields(Document doc) {
    /*/*from  www. j  a v  a  2  s . c o m*/
     * Assuming that root node is 'canonicalResidenceAddress'
     */
    String apartmentNumber = "";
    String streetNumber = "";
    Node iterSiblingNode = doc.getFirstChild();
    while (iterSiblingNode != null) {
        if (iterSiblingNode.getNodeName().equals("town")) {
            city = iterSiblingNode.getNodeValue().trim();
        } else if (iterSiblingNode.getNodeName().equals("postalCode")) {
            zipCode = iterSiblingNode.getNodeValue().trim();
        } else if (iterSiblingNode.getNodeName().equals("streetName")) {
            address = iterSiblingNode.getNodeName().trim();
        } else if (iterSiblingNode.getNodeName().equals("streetNumber")) {
            streetNumber = iterSiblingNode.getNodeValue();
        } else if (iterSiblingNode.getNodeName().equals("apartmentNumber")) {
            apartmentNumber = iterSiblingNode.getNodeValue().trim();
        } else if (iterSiblingNode.getNodeName().equals("state")) {
            countryCode = iterSiblingNode.getNodeName().trim();
        }
    }

    this.address = String.format("%s %s %s", this.address, streetNumber, apartmentNumber).trim();
}