Example usage for org.w3c.dom Element getFirstChild

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

Introduction

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

Prototype

public Node getFirstChild();

Source Link

Document

The first child of this node.

Usage

From source file:com.twinsoft.convertigo.engine.print.PrintHTML.java

@Override
public String print(String location) throws IOException, EngineException, SAXException,
        TransformerFactoryConfigurationError, TransformerException, ParserConfigurationException {
    super.print(location);
    out.close();//from   w  ww.ja v a 2s . c o  m

    updateStatus("Create Ressources Directory", 70);

    //get the dom
    Document fopResult = XMLUtils.parseDOM(outputFile);
    Element root = fopResult.getDocumentElement();
    String templateFileName = Engine.TEMPLATES_PATH + "/doc/doc.html.xsl";
    File htmlFile = new File(templateFileName);
    Source xsltSrc = new StreamSource(new FileInputStream(htmlFile), localizedDir);

    //create the ressources repository               
    String ressourcesFolder = outputFolder + "/ressources";
    File repository = new File(ressourcesFolder);
    if (!repository.exists()) {
        repository.mkdir();
    }

    //export images
    NodeList images = fopResult.getElementsByTagName("image");
    Node image;
    String attrImg, attrImgName;
    InputStream imagesIn;
    OutputStream imagesOut;
    for (int i = 0; i < images.getLength(); i++) {
        image = images.item(i);
        attrImg = image.getAttributes().getNamedItem("url").getTextContent();
        attrImgName = attrImg.replaceAll("(.*)/", "");
        image.getAttributes().getNamedItem("url").setTextContent(attrImgName);
        imagesIn = new FileInputStream(attrImg);
        imagesOut = new FileOutputStream(ressourcesFolder + "/" + attrImgName);
        org.apache.commons.io.IOUtils.copy(imagesIn, imagesOut);
        imagesIn.close();
        imagesOut.close();
    }

    //export css
    FileInputStream cssIn = new FileInputStream(Engine.TEMPLATES_PATH + "/doc/style.css");
    FileOutputStream cssOut = new FileOutputStream(ressourcesFolder + "/style.css");
    org.apache.commons.io.IOUtils.copy(cssIn, cssOut);
    cssIn.close();
    cssOut.close();

    updateStatus("HTML Transformation", 85);

    // transformation of the dom
    Transformer xslt = TransformerFactory.newInstance().newTransformer(xsltSrc);
    Element xsl = fopResult.createElement("xsl");
    xslt.transform(new DOMSource(fopResult), new DOMResult(xsl));
    fopResult.removeChild(root);
    fopResult.appendChild(xsl.getFirstChild());

    //write the dom
    String newOutputFileName = outputFolder + "/" + projectName + ".html";
    outputFile = new File(newOutputFileName);
    out = new FileOutputStream(outputFile);
    out = new java.io.BufferedOutputStream(out);
    OutputStreamWriter output = new OutputStreamWriter(out);
    output.write(XMLUtils.prettyPrintDOM(fopResult));
    output.close();

    //remove the temp file
    new File(outputFileName).delete();

    updateStatus("Printing finished", 100);

    return newOutputFileName;
}

From source file:com.commonsware.android.service.WeatherPlusService.java

List<Forecast> buildForecasts(String raw) throws Exception {
    List<Forecast> forecasts = new ArrayList<Forecast>();
    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document doc = builder.parse(new InputSource(new StringReader(raw)));
    NodeList times = doc.getElementsByTagName("start-valid-time");

    for (int i = 0; i < times.getLength(); i++) {
        Element time = (Element) times.item(i);
        Forecast forecast = new Forecast();

        forecasts.add(forecast);/*from w w w  .jav  a  2  s .  c o m*/
        forecast.setTime(time.getFirstChild().getNodeValue());
    }

    NodeList temps = doc.getElementsByTagName("value");

    for (int i = 0; i < temps.getLength(); i++) {
        Element temp = (Element) temps.item(i);
        Forecast forecast = forecasts.get(i);

        forecast.setTemp(new Integer(temp.getFirstChild().getNodeValue()));
    }

    NodeList icons = doc.getElementsByTagName("icon-link");

    for (int i = 0; i < icons.getLength(); i++) {
        Element icon = (Element) icons.item(i);
        Forecast forecast = forecasts.get(i);

        forecast.setIcon(icon.getFirstChild().getNodeValue());
    }

    return (forecasts);
}

From source file:com.wandrell.example.swss.test.util.test.integration.endpoint.AbstractITEndpoint.java

/**
 * Acquires a child element based on the name.
 *
 * @param parent/*from  w  w  w.  ja  v  a 2 s  .c  om*/
 *            the element where the search will be made
 * @param name
 *            the name of the child to return
 * @return the child with the specified name
 */
private final Element getChild(final Element parent, final String name) {
    Element result = null; // The wanted child

    for (Node child = parent.getFirstChild(); child != null; child = child.getNextSibling()) {
        if ((child instanceof Element) && (name.equals(child.getNodeName()))) {
            result = (Element) child;
        }
    }

    return result;
}

From source file:com.amalto.core.save.context.BeforeSaving.java

public void save(SaverSession session, DocumentSaverContext context) {
    // Invoke the beforeSaving
    MutableDocument updateReportDocument = context.getUpdateReportDocument();
    if (updateReportDocument == null) {
        throw new IllegalStateException("Update report is missing."); //$NON-NLS-1$
    }//from   www . j a v  a2s .  c  o  m
    OutputReport outputreport = session.getSaverSource().invokeBeforeSaving(context, updateReportDocument);

    if (outputreport != null) { // when a process was found
        String errorCode;
        message = outputreport.getMessage();
        if (!validateFormat(message))
            throw new BeforeSavingFormatException(message);
        try {
            Document doc = Util.parse(message);
            // handle output_report
            String xpath = "//report/message"; //$NON-NLS-1$
            Node errorNode;
            synchronized (XPATH) {
                errorNode = (Node) XPATH.evaluate(xpath, doc, XPathConstants.NODE);
            }
            errorCode = null;
            if (errorNode instanceof Element) {
                Element errorElement = (Element) errorNode;
                errorCode = errorElement.getAttribute("type"); //$NON-NLS-1$
                Node child = errorElement.getFirstChild();
                if (child instanceof org.w3c.dom.Text) {
                    message = child.getTextContent();
                } else {
                    message = ""; //$NON-NLS-1$   
                }
            }

            if (!"info".equals(errorCode)) { //$NON-NLS-1$
                throw new BeforeSavingErrorException(message);
            }

            // handle output_item
            if (outputreport.getItem() != null) {
                xpath = "//exchange/item"; //$NON-NLS-1$
                SkipAttributeDocumentBuilder builder = new SkipAttributeDocumentBuilder(
                        SaverContextFactory.DOCUMENT_BUILDER, false);
                doc = builder.parse(new InputSource(new StringReader(outputreport.getItem())));
                Node item;
                synchronized (XPATH) {
                    item = (Node) XPATH.evaluate(xpath, doc, XPathConstants.NODE);
                }
                if (item != null && item instanceof Element) {
                    Node node = null;
                    Node current = item.getFirstChild();
                    while (current != null) {
                        if (current instanceof Element) {
                            node = current;
                            break;
                        }
                        current = item.getNextSibling();
                    }
                    if (node != null) {
                        // set back the modified item by the process
                        DOMDocument document = new DOMDocument(node, context.getUserDocument().getType(),
                                context.getDataCluster(), context.getDataModelName());
                        context.setUserDocument(document);
                        context.setDatabaseDocument(null);
                        // Redo a set of actions and security checks.
                        // TMDM-4599: Adds UpdateReport phase so a new update report is generated based on latest changes.
                        next = new ID(
                                new GenerateActions(new Security(new UpdateReport(new ApplyActions(next)))));
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("Exception occurred during before saving phase.", e); //$NON-NLS-1$
        }
    }

    next.save(session, context);
}

From source file:com.karlchu.mo.web.sitemesh.MyConfigLoader.java

private void populatePathMapper(State newState, NodeList patternNodes, String role, String name,
        String decorId) {/*from ww w. ja  v a2  s  . c  om*/
    for (int j = 0; j < patternNodes.getLength(); j++) {
        Element p = (Element) patternNodes.item(j);
        Text patternText = (Text) p.getFirstChild();
        if (patternText != null) {
            String pattern = patternText.getData().trim();
            if (pattern != null) {
                if (newState.pathMapperMap.get(decorId) == null) {
                    newState.pathMapperMap.put(decorId, new PathMapper());
                }
                if (role != null) {
                    // concatenate name and role to allow more
                    // than one decorator per role
                    newState.pathMapperMap.get(decorId).put(name + role, pattern);
                } else {
                    newState.pathMapperMap.get(decorId).put(name, pattern);
                }
            }
        }
    }
}

From source file:importer.handler.post.stages.Discriminator.java

/**
 * Get the last child element that is not corrected or deleted
 * @param elem the element to test//w w  w  .j av  a 2  s. com
 * @return its last uncancelled/uncorrected child or null
 */
Element lastOpenChild(Element elem) {
    Node child = elem.getFirstChild();
    Element last = null;
    while (child != null) {
        if (child.getNodeType() == Node.ELEMENT_NODE) {
            Element cElem = (Element) child;
            if (!isDeleted(cElem) && !isCorrected(cElem))
                last = cElem;
        }
        child = child.getNextSibling();
    }
    return last;
}

From source file:com.digitalpebble.storm.crawler.filtering.regex.RegexURLNormalizer.java

private List<Rule> readConfiguration(Reader reader) {
    List<Rule> rules = new ArrayList<Rule>();
    try {/*from   ww w  .  j  a v a2 s .  co  m*/

        // borrowed heavily from code in Configuration.java
        Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(reader));
        Element root = doc.getDocumentElement();
        if ((!"regex-normalize".equals(root.getTagName())) && (LOG.isErrorEnabled())) {
            LOG.error("bad conf file: top-level element not <regex-normalize>");
        }
        NodeList regexes = root.getChildNodes();
        for (int i = 0; i < regexes.getLength(); i++) {
            Node regexNode = regexes.item(i);
            if (!(regexNode instanceof Element)) {
                continue;
            }
            Element regex = (Element) regexNode;
            if ((!"regex".equals(regex.getTagName())) && (LOG.isWarnEnabled())) {
                LOG.warn("bad conf file: element not <regex>");
            }
            NodeList fields = regex.getChildNodes();
            String patternValue = null;
            String subValue = null;
            for (int j = 0; j < fields.getLength(); j++) {
                Node fieldNode = fields.item(j);
                if (!(fieldNode instanceof Element)) {
                    continue;
                }
                Element field = (Element) fieldNode;
                if ("pattern".equals(field.getTagName()) && field.hasChildNodes()) {
                    patternValue = ((Text) field.getFirstChild()).getData();
                }
                if ("substitution".equals(field.getTagName()) && field.hasChildNodes()) {
                    subValue = ((Text) field.getFirstChild()).getData();
                }
                if (!field.hasChildNodes()) {
                    subValue = "";
                }
            }
            if (patternValue != null && subValue != null) {
                Rule rule = createRule(patternValue, subValue);
                rules.add(rule);
            }
        }
    } catch (Exception e) {
        LOG.error("error parsing conf file", e);
        return EMPTY_RULES;
    }
    if (rules.size() == 0) {
        return EMPTY_RULES;
    }
    return rules;
}

From source file:com.digitalpebble.stormcrawler.filtering.regex.RegexURLNormalizer.java

private List<Rule> readConfiguration(Reader reader) {
    List<Rule> rules = new ArrayList<>();
    try {/*  ww w .  j  av a  2  s. c  o  m*/

        // borrowed heavily from code in Configuration.java
        Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(reader));
        Element root = doc.getDocumentElement();
        if ((!"regex-normalize".equals(root.getTagName())) && (LOG.isErrorEnabled())) {
            LOG.error("bad conf file: top-level element not <regex-normalize>");
        }
        NodeList regexes = root.getChildNodes();
        for (int i = 0; i < regexes.getLength(); i++) {
            Node regexNode = regexes.item(i);
            if (!(regexNode instanceof Element)) {
                continue;
            }
            Element regex = (Element) regexNode;
            if ((!"regex".equals(regex.getTagName())) && (LOG.isWarnEnabled())) {
                LOG.warn("bad conf file: element not <regex>");
            }
            NodeList fields = regex.getChildNodes();
            String patternValue = null;
            String subValue = null;
            for (int j = 0; j < fields.getLength(); j++) {
                Node fieldNode = fields.item(j);
                if (!(fieldNode instanceof Element)) {
                    continue;
                }
                Element field = (Element) fieldNode;
                if ("pattern".equals(field.getTagName()) && field.hasChildNodes()) {
                    patternValue = ((Text) field.getFirstChild()).getData();
                }
                if ("substitution".equals(field.getTagName()) && field.hasChildNodes()) {
                    subValue = ((Text) field.getFirstChild()).getData();
                }
                if (!field.hasChildNodes()) {
                    subValue = "";
                }
            }
            if (patternValue != null && subValue != null) {
                Rule rule = createRule(patternValue, subValue);
                rules.add(rule);
            }
        }
    } catch (Exception e) {
        LOG.error("error parsing conf file", e);
        return EMPTY_RULES;
    }
    if (rules.size() == 0) {
        return EMPTY_RULES;
    }
    return rules;
}

From source file:it.unibas.spicy.persistence.xml.operators.ExportXSD.java

private void processConstraints(IDataSourceProxy dataSource, Document document) {
    Element rootDocument = document.getDocumentElement();
    Node child = rootDocument.getFirstChild();
    if (child == null) {
        throw new IllegalArgumentException(
                " Unable to find right child root node for: " + dataSource.getIntermediateSchema().getLabel());
    }/*from  w w  w.  j  a  v  a  2s . c  om*/
    processKeyConstraints(dataSource, child, document);
    processForeignKeyConstraints(dataSource, child, document);
}

From source file:com.aipo.container.gadgets.render.AipoRenderingGadgetRewriter.java

@Override
public void rewrite(Gadget gadget, MutableContent mutableContent) throws RewritingException {
    // Don't touch sanitized gadgets.
    if (gadget.sanitizeOutput()) {
        return;/*from w  ww.  j  a va2 s.c o  m*/
    }
    try {
        Document document = mutableContent.getDocument();

        Element head = (Element) DomUtil.getFirstNamedChildNode(document.getDocumentElement(), "head");

        // Insert new content before any of the existing children of the head
        // element
        Node firstHeadChild = head.getFirstChild();

        Element contentLanguage = document.createElement("meta");
        contentLanguage.setAttribute("http-equiv", "Content-Language");
        contentLanguage.setAttribute("content", "ja");
        head.insertBefore(contentLanguage, firstHeadChild);

        Element contentType = document.createElement("meta");
        contentType.setAttribute("http-equiv", "Content-Type");
        contentType.setAttribute("content", "text/html; charset=UTF-8");
        head.insertBefore(contentType, firstHeadChild);

        Element contentStyleType = document.createElement("meta");
        contentStyleType.setAttribute("http-equiv", "Content-Style-Type");
        contentStyleType.setAttribute("content", "text/css");
        head.insertBefore(contentStyleType, firstHeadChild);

        Element contentScriptType = document.createElement("meta");
        contentScriptType.setAttribute("http-equiv", "Content-Script-Type");
        contentScriptType.setAttribute("content", "text/javascript");
        head.insertBefore(contentScriptType, firstHeadChild);

        // Only inject default styles if no doctype was specified.
        // if (document.getDoctype() == null) {
        boolean isAipoStyle = gadget.getAllFeatures().contains("aipostyle")
                && gadget.getSpec().getModulePrefs().getFeatures().keySet().contains("aipostyle");
        Element defaultStyle = document.createElement("style");
        defaultStyle.setAttribute("type", "text/css");
        head.insertBefore(defaultStyle, firstHeadChild);
        defaultStyle.appendChild(
                defaultStyle.getOwnerDocument().createTextNode(isAipoStyle ? aipoStyleCss : DEFAULT_CSS));
        // }

        injectBaseTag(gadget, head);
        injectGadgetBeacon(gadget, head, firstHeadChild);
        injectFeatureLibraries(gadget, head, firstHeadChild);

        // This can be one script block.
        Element mainScriptTag = document.createElement("script");
        GadgetContext context = gadget.getContext();
        MessageBundle bundle = messageBundleFactory.getBundle(gadget.getSpec(), context.getLocale(),
                context.getIgnoreCache(), context.getContainer());
        injectMessageBundles(bundle, mainScriptTag);
        injectDefaultPrefs(gadget, mainScriptTag);
        injectPreloads(gadget, mainScriptTag);

        // We need to inject our script before any developer scripts.
        head.insertBefore(mainScriptTag, firstHeadChild);

        Element body = (Element) DomUtil.getFirstNamedChildNode(document.getDocumentElement(), "body");

        body.setAttribute("dir", bundle.getLanguageDirection());

        injectOnLoadHandlers(body);

        mutableContent.documentChanged();
    } catch (GadgetException e) {
        throw new RewritingException(e.getLocalizedMessage(), e, e.getHttpStatusCode());
    }
}