Example usage for org.w3c.dom Node getFirstChild

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

Introduction

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

Prototype

public Node getFirstChild();

Source Link

Document

The first child of this node.

Usage

From source file:com.gargoylesoftware.htmlunit.javascript.host.XSLTProcessor.java

/**
 * @return {@link Node} or {@link String}
 *///from   w  w w . ja v a  2 s  .co m
private Object transform(final Node source) {
    try {
        Source xmlSource = new DOMSource(source.getDomNodeOrDie());
        final Source xsltSource = new DOMSource(style_.getDomNodeOrDie());

        final org.w3c.dom.Document containerDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                .newDocument();
        final org.w3c.dom.Element containerElement = containerDocument.createElement("container");
        containerDocument.appendChild(containerElement);

        final DOMResult result = new DOMResult(containerElement);

        final Transformer transformer = TransformerFactory.newInstance().newTransformer(xsltSource);
        for (final Map.Entry<String, Object> entry : parameters_.entrySet()) {
            transformer.setParameter(entry.getKey(), entry.getValue());
        }
        transformer.transform(xmlSource, result);

        final org.w3c.dom.Node transformedNode = result.getNode();
        if (transformedNode.getFirstChild().getNodeType() == Node.ELEMENT_NODE) {
            return transformedNode;
        }
        //output is not DOM (text)
        xmlSource = new DOMSource(source.getDomNodeOrDie());
        final StringWriter writer = new StringWriter();
        final Result streamResult = new StreamResult(writer);
        transformer.transform(xmlSource, streamResult);
        return writer.toString();
    } catch (final Exception e) {
        throw Context.reportRuntimeError("Exception: " + e);
    }
}

From source file:net.sourceforge.eclipsetrader.core.internal.TradingSystemRepository.java

private TradingSystemGroup loadGroup(NodeList node) {
    TradingSystemGroup group = new TradingSystemGroup(
            new Integer(Integer.parseInt(((Node) node).getAttributes().getNamedItem("id").getNodeValue()))); //$NON-NLS-1$

    for (int i = 0; i < node.getLength(); i++) {
        Node item = node.item(i);
        String nodeName = item.getNodeName();
        Node value = item.getFirstChild();
        if (value != null) {
            if (nodeName.equals("description")) //$NON-NLS-1$
                group.setDescription(value.getNodeValue());
        }// w  w w  . ja  v  a 2 s .  c  om
        if (nodeName.equals("system")) //$NON-NLS-1$
        {
            TradingSystem system = loadSystem(item.getChildNodes());
            system.setGroup(group);
            group.getTradingSystems().add(system);
        } else if (nodeName.equals("group")) //$NON-NLS-1$
        {
            TradingSystemGroup grp = loadGroup(item.getChildNodes());
            grp.setParent(group);
            group.getGroups().add(grp);
        }
    }

    group.clearChanged();
    tsGroupMap.put(group.getId(), group);
    repository.getTradingSystemGroups().add(group);

    return group;
}

From source file:com.gargoylesoftware.htmlunit.javascript.host.XSLTProcessor.java

/**
 * Transforms the node source applying the stylesheet given by the importStylesheet() function.
 * The owner document of the output node owns the returned document fragment.
 *
 * @param source the node to be transformed
 * @return the result of the transformation
 *///from   w w w. ja  v a  2s  .  c  o m
@JsxFunction(@WebBrowser(FF))
public XMLDocument transformToDocument(final Node source) {
    final XMLDocument doc = new XMLDocument();
    doc.setPrototype(getPrototype(doc.getClass()));
    doc.setParentScope(getParentScope());

    final Object transformResult = transform(source);
    final org.w3c.dom.Node node;
    if (transformResult instanceof org.w3c.dom.Node) {
        final org.w3c.dom.Node transformedDoc = (org.w3c.dom.Node) transformResult;
        node = transformedDoc.getFirstChild();
    } else {
        node = null;
    }
    final XmlPage page = new XmlPage(node, getWindow().getWebWindow());
    doc.setDomNode(page);
    return doc;
}

From source file:net.sourceforge.eclipsetrader.core.internal.TradingSystemRepository.java

private TradingSystem loadSystem(NodeList node) {
    TradingSystem system = new TradingSystem(
            new Integer(Integer.parseInt(((Node) node).getAttributes().getNamedItem("id").getNodeValue()))); //$NON-NLS-1$
    system.setPluginId(((Node) node).getAttributes().getNamedItem("pluginId").getNodeValue()); //$NON-NLS-1$

    for (int i = 0; i < node.getLength(); i++) {
        Node item = node.item(i);
        String nodeName = item.getNodeName();
        Node value = item.getFirstChild();
        if (value != null) {
            if (nodeName.equals("security")) //$NON-NLS-1$
                system.setSecurity(//from  www.  jav  a2s .  c o m
                        (Security) repository.load(Security.class, new Integer(value.getNodeValue())));
            else if (nodeName.equals("account")) //$NON-NLS-1$
                system.setAccount((Account) repository.load(Account.class, new Integer(value.getNodeValue())));
            else if (nodeName.equalsIgnoreCase("date")) //$NON-NLS-1$
            {
                try {
                    system.setDate(dateTimeFormat.parse(value.getNodeValue()));
                } catch (Exception e) {
                    logger.warn(e.toString(), e);
                }
            } else if (nodeName.equalsIgnoreCase("signal")) //$NON-NLS-1$
                system.setSignal(Integer.parseInt(value.getNodeValue()));
            else if (nodeName.equalsIgnoreCase("max_exposure")) //$NON-NLS-1$
                system.setMaxExposure(Double.parseDouble(value.getNodeValue()));
            else if (nodeName.equalsIgnoreCase("min_amount")) //$NON-NLS-1$
                system.setMinAmount(Double.parseDouble(value.getNodeValue()));
            else if (nodeName.equalsIgnoreCase("max_amount")) //$NON-NLS-1$
                system.setMaxAmount(Double.parseDouble(value.getNodeValue()));
            else if (nodeName.equalsIgnoreCase("param")) //$NON-NLS-1$
            {
                String key = ((Node) item).getAttributes().getNamedItem("key").getNodeValue(); //$NON-NLS-1$
                system.getParameters().put(key, value.getNodeValue());
            }
        }
    }

    system.clearChanged();
    tsMap.put(system.getId(), system);
    repository.getTradingSystems().add(system);

    return system;
}

From source file:com.konakart.bl.modules.payment.globalcollect.GlobalCollectUtils.java

/**
 * @param gatewayResp//from   ww  w  .java 2  s .c  o m
 * @param arrayLocation
 * @return a Map of objects found in the XML string returned by the gateway
 * @throws Exception
 */
public Map<String, String> parseGlobalCollectResponseToMap(String gatewayResp, String arrayLocation)
        throws Exception {
    Map<String, String> xmlMap = new HashMap<String, String>();

    if (gatewayResp != null) {
        try {
            DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = builderFactory.newDocumentBuilder();
            ByteArrayInputStream bais = new ByteArrayInputStream(gatewayResp.getBytes());
            Document doc = builder.parse(bais);
            int arrayIndx = -1;

            // get the root node
            Node rootnode = doc.getDocumentElement();
            String rootName = rootnode.getNodeName();

            if (rootName != "XML") {
                throw new KKException("Unexpected root element in Initial Response: " + rootName);
            }

            // get all elements
            NodeList list = doc.getElementsByTagName("*");
            for (int i = 0; i < list.getLength(); i++) {
                Node node = list.item(i);
                String name = node.getNodeName();
                if (name != null) {
                    Node firstNode = node.getFirstChild();
                    if (firstNode == null) {
                        continue;
                    }
                    if (firstNode instanceof Text) {
                        Text dataNode = (Text) firstNode;
                        String path = getXmlPath(firstNode, arrayIndx, arrayLocation);
                        xmlMap.put(path, dataNode.getData());
                        continue;
                    } else {
                        if (arrayLocation != null && getXmlPath(firstNode).equals(arrayLocation)) {
                            arrayIndx++;
                        }
                    }
                }
            }

            if (log.isDebugEnabled()) {
                log.debug("Map: " + xmlMap);
            }
        } catch (Exception e) {
            // Problems parsing the XML
            if (log.isDebugEnabled()) {
                log.debug("Problems parsing Initial response: " + e.getMessage());
            }
            throw e;
        }
    }

    return xmlMap;
}

From source file:elaborate.editor.export.tei.TeiMaker.java

private int processEntry(int _pageno, Element body, String _currentFolio, ProjectEntry projectEntry) {
    int pageno = _pageno;
    String currentFolio = _currentFolio;
    String folio = StringUtils.defaultIfBlank(projectEntry.getMetadataValue("Folio number"), "")
            + StringUtils.defaultIfBlank(projectEntry.getMetadataValue("Folio side"), "");
    if (!currentFolio.equals(folio)) {
        pageno = addPb(body, pageno, projectEntry, folio);
    }/*from  ww  w  .j  a v  a2s  .  c o m*/
    // addCb(body, projectEntry);
    currentFolio = folio;

    Element entryDiv = tei.createElement("div");
    entryDiv.setAttribute("xml:id", "e" + projectEntry.getId());
    entryDiv.setAttribute("n", projectEntry.getName());

    addEntryInterpGrp(entryDiv, projectEntry);

    List<Transcription> orderedTranscriptions = Lists.newArrayList(projectEntry.getTranscriptions());
    Collections.sort(orderedTranscriptions, ORDER_BY_TYPE);
    for (Transcription transcription : orderedTranscriptions) {
        HtmlTeiConverter htmlTeiConverter = new HtmlTeiConverter(transcription.getBody(), config,
                transcription.getTranscriptionType().getName(), entityManager);
        Node transcriptionNode = htmlTeiConverter.getContent();
        Node importedTranscriptionNode = tei.importNode(transcriptionNode, true);
        Node child = importedTranscriptionNode.getFirstChild();
        while (child != null) {
            Node nextSibling = child.getNextSibling();
            if (child.getNodeName().equals("div") && child.hasChildNodes()) {
                entryDiv.appendChild(child);
            }
            child = nextSibling;
        }
    }
    body.appendChild(entryDiv);
    return pageno;
}

From source file:com.netspective.commons.lang.ClassJavaDoc.java

protected void setXmlDocument(Document xmlDocument) {
    this.xmlDocument = xmlDocument;
    if (xmlDocument == null) {
        setFound(false);//from w ww  .jav  a  2s . c  om
        return;
    }

    try {
        Node descrLeadNode = XPathAPI.selectSingleNode(xmlDocument.getDocumentElement(), "/*/description/lead");
        Node descrDetailNode = XPathAPI.selectSingleNode(xmlDocument.getDocumentElement(),
                "/*/description/detail");

        if (descrLeadNode != null)
            setDescriptionLead(descrLeadNode.getFirstChild().getNodeValue());

        if (descrDetailNode != null)
            setDescriptionDetail(descrDetailNode.getFirstChild().getNodeValue());
    } catch (Exception e) {
        log.error("Error retrieving description for class " + getOwner(), e);
        setRetrievalError(e);
    }
}

From source file:com.amalto.core.history.accessor.UnaryFieldAccessor.java

private Element internalCreate() {
    parent.create();/* ww w.j  a  va  2s.c  om*/
    Document domDocument = document.asDOM();
    Element element = getElement();
    if (element == null) {
        Element newElement = domDocument.createElementNS(domDocument.getNamespaceURI(), fieldName);
        Node parentNode = parent.getNode();
        Node lastAccessedNode = document.getLastAccessedNode();
        if (parentNode == lastAccessedNode) {
            parentNode.insertBefore(newElement, parentNode.getFirstChild());
        } else if (lastAccessedNode != null && lastAccessedNode.getParentNode() == parentNode) {
            parentNode.insertBefore(newElement, lastAccessedNode.getNextSibling());
        } else {
            parentNode.appendChild(newElement);
        }
        element = newElement;
        document.setLastAccessedNode(element);
    }
    return element;
}

From source file:de.innovationgate.igutils.pingback.PingBackClient.java

/**
 * checks if the given sourceURI is reachable, has textual content and contains a link to the given target
 * if present the title of the sourceURI is returned
 * @param sourceURI - the sourceURI to check
 * @param targetURI - the targetURI to search as link 
 * @throws PingBackException - thrown if check fails
 * @returns title of the sourceURI - null if not present or found
 *///from   w w  w .j ava2  s . c om
public String checkSourceURI(String sourceURI, String targetURI) throws PingBackException {
    HttpClient client = WGFactory.getHttpClientFactory().createHttpClient();
    GetMethod sourceGET = new GetMethod(sourceURI);
    sourceGET.setFollowRedirects(false);
    try {
        int responseCode = client.executeMethod(sourceGET);
        if (responseCode != HttpURLConnection.HTTP_OK) {
            if (responseCode == HttpURLConnection.HTTP_FORBIDDEN) {
                throw new PingBackException(PingBackException.ERROR_ACCESS_DENIED,
                        "Access denied on source uri '" + sourceURI + "'.");
            } else if (responseCode == HttpURLConnection.HTTP_BAD_GATEWAY) {
                throw new PingBackException(PingBackException.ERROR_UPSTREAM_SERVER_COMMUNICATION_ERROR,
                        "Get request on source uri '" + sourceURI + "' returned '" + responseCode + "'.");
            } else {
                throw new PingBackException(PingBackException.ERROR_GENERIC,
                        "Source uri is unreachable. Get request on source uri '" + sourceURI + "' returned '"
                                + responseCode + "'.");
            }
        }

        checkTextualContentType(sourceGET);

        // search link to target in source
        InputStream sourceIn = sourceGET.getResponseBodyAsStream();
        String searchTerm = targetURI.toLowerCase();
        boolean linkFound = false;
        String title = null;
        if (sourceIn == null) {
            throw new PingBackException(PingBackException.ERROR_SOURCE_URI_HAS_NO_LINK,
                    "Source uri contains no link to target '" + targetURI + "'.");
        } else {
            // first of all read response into a fix buffer of 2Mb - all further content will be ignored for doS-reason
            ByteArrayOutputStream htmlPageBuffer = new ByteArrayOutputStream();
            inToOut(sourceGET.getResponseBodyAsStream(), htmlPageBuffer, 1024, documentSizeLimit);

            try {
                // search for title
                DOMParser parser = new DOMParser();
                parser.parse(new InputSource(new ByteArrayInputStream(htmlPageBuffer.toByteArray())));
                Document doc = parser.getDocument();
                NodeList titleElements = doc.getElementsByTagName("title");
                if (titleElements.getLength() > 0) {
                    // retrieve first title
                    Node titleNode = titleElements.item(0);
                    title = titleNode.getFirstChild().getNodeValue();
                }
            } catch (Exception e) {
                // ignore any parsing exception - title is just a goodie
            }

            // read line per line and search for link
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    new ByteArrayInputStream(htmlPageBuffer.toByteArray()), sourceGET.getResponseCharSet()));
            String line = reader.readLine();
            while (line != null) {
                line = line.toLowerCase();
                if (line.indexOf(searchTerm) != -1) {
                    linkFound = true;
                    break;
                }
                line = reader.readLine();
            }
        }

        if (!linkFound) {
            throw new PingBackException(PingBackException.ERROR_SOURCE_URI_HAS_NO_LINK,
                    "Source uri '" + sourceURI + "' contains no link to target '" + targetURI + "'.");
        } else {
            return title;
        }
    } catch (HttpException e) {
        throw new PingBackException(PingBackException.ERROR_GENERIC,
                "Unable to check source uri '" + sourceURI + "'.", e);
    } catch (IOException e) {
        throw new PingBackException(PingBackException.ERROR_GENERIC,
                "Unable to check source uri '" + sourceURI + "'.", e);
    }
}

From source file:com.connectutb.xfuel.FuelPlanner.java

public final String getElementValue(Node elem) {
    Node child;//from w w  w .j  a  v  a2  s . co  m
    if (elem != null) {
        if (elem.hasChildNodes()) {
            for (child = elem.getFirstChild(); child != null; child = child.getNextSibling()) {
                if (child.getNodeType() == Node.TEXT_NODE) {
                    return child.getNodeValue();
                }
            }
        }
    }
    return "";
}