Example usage for org.w3c.dom Element insertBefore

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

Introduction

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

Prototype

public Node insertBefore(Node newChild, Node refChild) throws DOMException;

Source Link

Document

Inserts the node newChild before the existing child node refChild.

Usage

From source file:org.jolokia.roo.JolokiaCommands.java

private void updateJsr160Proxy(Element configuration, Document webXmlDoc) {
    String paramName = getJsr160InitArg(configuration, "param-name");
    String paramValue = getJsr160InitArg(configuration, "param-value");

    Element servlet = XmlUtils.findFirstElement("/web-app/servlet[servlet-name = 'jolokia']",
            webXmlDoc.getDocumentElement());
    if (servlet == null) {
        throw new IllegalArgumentException("Internal: No servlet 'jolokia' found in WEB-INF/web.xml");
    }// w ww . j  ava  2 s  . c  o  m
    Element initParam = XmlUtils.findFirstElement("init-param[param-name = '" + paramName + "']", servlet);
    if (initParam == null) {
        // Create missing init param
        initParam = new XmlElementBuilder("init-param", webXmlDoc)
                .addChild(new XmlElementBuilder("param-name", webXmlDoc).setText(paramName).build())
                .addChild(new XmlElementBuilder("param-value", webXmlDoc).setText(paramValue).build()).build();

        Element lastElement = XmlUtils.findFirstElement("load-on-startup", servlet);
        if (lastElement != null) {
            servlet.insertBefore(initParam, lastElement);
        } else {
            servlet.appendChild(initParam);
        }
    } else {
        Element value = XmlUtils.findFirstElement("param-value", initParam);
        value.setTextContent(paramValue);
    }
}

From source file:com.bstek.dorado.view.config.XmlDocumentPreprocessor.java

@SuppressWarnings("unchecked")
private void postProcessNodeReplacement(Element element) {
    Document ownerDocument = element.getOwnerDocument();
    Node child = element.getFirstChild();
    while (child != null) {
        Node nextChild = child.getNextSibling();
        if (child instanceof Element) {
            if (child.getUserData("dorado.delete") != null) {
                List<Element> replaceContent = (List<Element>) child.getUserData("dorado.replace");
                if (replaceContent != null) {
                    for (Element el : replaceContent) {
                        Element clonedElement = (Element) ownerDocument.importNode(el, true);
                        element.insertBefore(clonedElement, child);
                    }/*  w w  w  .  j  ava 2s  .  com*/
                    child.setUserData("dorado.replace", null, null);
                }
                element.removeChild(child);
                child.setUserData("dorado.delete", null, null);
            }
        }
        child = nextChild;
    }
}

From source file:edu.clemson.lph.civet.xml.StdeCviXmlBuilder.java

/**
 * Used to add address to Veterinarian, Origin and Destination
 * @param e/* w w  w  . ja v  a  2 s  .co m*/
 * @param sStreet
 * @param sCity
 * @param sState
 * @param sZip
 * @return
 */
public Element setAddress(Element e, String sStreet, String sCity, String sState, String sZip) {
    if (!isValidDoc())
        return null;
    Element address = null;
    if (e != null) {
        address = getAddress(e, sStreet, sCity, sState, sZip);
        if (address != null)
            return address;
        address = childElementByName(e, "Address");
        if (address == null) {
            String sElement = e.getTagName();
            Node nPerson = null;
            if (!"Veterinarian".equals(sElement)) {
                nPerson = childNodeByName(e, "Person");
            }
            address = doc.createElement("Address");
            e.insertBefore(address, nPerson);
        }
        Node line1 = childNodeByName(address, "Line1");
        if (line1 == null) {
            line1 = doc.createElement("Line1");
            address.appendChild(line1);
        }
        if (sStreet != null) {
            line1.setTextContent(sStreet.trim());
        } else {
            line1.setTextContent("");
        }
        Node town = childNodeByName(address, "Town");
        if (town == null) {
            town = doc.createElement("Town");
            address.appendChild(town);
        }
        if (sCity != null) {
            town.setTextContent(sCity.trim());
        } else {
            town.setTextContent("Not Provided");
        }
        Node state = childNodeByName(address, "State");
        if (state == null) {
            state = doc.createElement("State");
            address.appendChild(state);
        }
        if (sState != null) {
            state.setTextContent(sState.trim());
        } else {
            logger.error("Attempt to add address with no state.", new Exception());
            state.setTextContent("ERROR");
        }
        Node zip = childNodeByName(address, "ZIP");
        if (zip == null) {
            zip = doc.createElement("ZIP");
            address.appendChild(zip);
        }
        if (sZip != null && sZip.trim().length() > 0) {
            zip.setTextContent(sZip.trim());
        } else {
            zip.setTextContent("00000");
        }
        Node country = childNodeByName(address, "Country");
        if (country == null) {
            country = doc.createElement("Country");
            address.appendChild(country);
        }
        country.setTextContent("USA");
    }
    return address;
}

From source file:org.gvnix.web.report.roo.addon.addon.ReportMetadata.java

/**
 * Creates a sample jrxml report file based in the template
 * report/JasperReport-template.jrxml with:
 * <ul>/*from  ww w  . j a  v a  2  s  .  c  o  m*/
 * <li>3 field elements or less if the entity in fromBackingObject doesn't
 * has more than 3 member fields</li>
 * <li>As many staticText/textField element pairs as fields have been
 * created</li>
 * </ul>
 * The jrxml is copied to the WEB-INF/reports foder with the name
 * entity_report_name.jrxml
 * 
 * @param installedReport
 * @param fromBackingObject
 */
private void installJasperReportTemplate(String installedReport, JavaType fromBackingObject) {
    // Check if a jrxml file exists
    PathResolver pathResolver = projectOperations.getPathResolver();
    String reportJrXml = pathResolver.getIdentifier(LogicalPath.getInstance(Path.SRC_MAIN_WEBAPP, ""),
            "WEB-INF/reports/".concat(fromBackingObject.getSimpleTypeName().toLowerCase()).concat("_")
                    .concat(installedReport.toLowerCase()).concat(".jrxml"));

    if (fileManager.exists(reportJrXml)) {
        // We can't modify the existing jrxml file just in case the user has
        // modified it
        return;
    }

    // Get member details of fromBackingObject type
    MemberDetails memberDetails = getMemberDetails(fromBackingObject);
    List<FieldMetadata> elegibleFields = webMetadataService.getScaffoldEligibleFieldMetadata(fromBackingObject,
            memberDetails, governorPhysicalTypeMetadata.getId());
    /*
     * We only use 3 fields in the sample report. By now we only use field
     * types accepted by JasperReports XMLSchema
     */
    List<FieldMetadata> usableFields = new ArrayList<FieldMetadata>();
    Iterator<FieldMetadata> it = elegibleFields.iterator();
    FieldMetadata field = null;
    while (it.hasNext() && usableFields.size() < 3) {
        field = it.next();
        if (ReportValidTypes.VALID_TYPES.contains(field.getFieldType().getFullyQualifiedTypeName())) {
            usableFields.add(field);
        }
    }

    InputStream templateInputStream = FileUtils.getInputStream(getClass(),
            "report/JasperReport-template.jrxml");

    Document jrxml;
    try {
        jrxml = XmlUtils.getDocumentBuilder().parse(templateInputStream);
    } catch (Exception ex) {
        throw new IllegalStateException("Could not open JasperReport-template.jrxml file", ex);
    }

    Element jasperReport = jrxml.getDocumentElement();

    // Add a field definition and its use in the detail band per
    // usableFields
    String textHeight = "20";
    String sTextW = "64";
    String fTextW = "119";
    String yPos = "0";
    int xPos = 0; // we need xPos as int in order to modify its value.
    Element staticText;
    Element textField;
    Element detailBand = XmlUtils.findFirstElement("/jasperReport/detail/band", jasperReport);
    Node backgroundNode = XmlUtils.findNode("/jasperReport/background", jasperReport);
    for (FieldMetadata fieldMetadata : usableFields) {
        jasperReport.insertBefore(new XmlElementBuilder("field", jrxml)
                .addAttribute("name", fieldMetadata.getFieldName().getSymbolName())
                .addAttribute("class", fieldMetadata.getFieldType().getFullyQualifiedTypeName()).build(),
                backgroundNode);
        staticText = (Element) new XmlElementBuilder("staticText", jrxml).build();
        staticText.appendChild(new XmlElementBuilder("reportElement", jrxml)
                .addAttribute("x", String.valueOf(xPos)).addAttribute("y", yPos).addAttribute("width", sTextW)
                .addAttribute("height", textHeight).build());
        staticText.appendChild(new XmlElementBuilder("textElement", jrxml).build());
        staticText.appendChild(new XmlElementBuilder("text", jrxml)
                .addChild(jrxml.createCDATASection(fieldMetadata.getFieldName().getReadableSymbolName()))
                .build());
        detailBand.appendChild(staticText);
        // Increment xPos for the next text box
        xPos += (Integer.parseInt(sTextW) + 1);
        textField = (Element) new XmlElementBuilder("textField", jrxml).build();
        textField.appendChild(new XmlElementBuilder("reportElement", jrxml)
                .addAttribute("x", String.valueOf(xPos)).addAttribute("y", yPos).addAttribute("width", fTextW)
                .addAttribute("height", textHeight).build());
        textField.appendChild(new XmlElementBuilder("textElement", jrxml).build());
        textField
                .appendChild(new XmlElementBuilder("textFieldExpression", jrxml)
                        .addAttribute("class", fieldMetadata.getFieldType().getFullyQualifiedTypeName())
                        .addChild(jrxml.createCDATASection(
                                "$F{".concat(fieldMetadata.getFieldName().getSymbolName()).concat("}")))
                        .build());
        detailBand.appendChild(textField);
        // Increment xPos for the next text box
        xPos += (Integer.parseInt(fTextW) + 1);
    }

    // We are sure that reportJrXml file doesn't exist so we can write it
    // with the jrxml document content
    MutableFile mutableFile = fileManager.createFile(reportJrXml);
    Validate.notNull(mutableFile, "Could not create jrxml file '".concat(reportJrXml).concat("'"));

    try {
        // Build a string representation of the jrxml
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        XmlUtils.writeXml(XmlUtils.createIndentingTransformer(), byteArrayOutputStream, jrxml);
        String jrxmlContent = byteArrayOutputStream.toString();

        // We need to write the file out (it's a new file, or the existing
        // file has different contents)
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            inputStream = IOUtils.toInputStream(jrxmlContent);
            outputStream = mutableFile.getOutputStream();
            IOUtils.copy(inputStream, outputStream);
        } finally {
            IOUtils.closeQuietly(inputStream);
            IOUtils.closeQuietly(outputStream);
        }
    } catch (IOException ioe) {
        throw new IllegalStateException("Could not output '".concat(mutableFile.getCanonicalPath()).concat("'"),
                ioe);
    }

}

From source file:com.bstek.dorado.view.config.XmlDocumentPreprocessor.java

private void mergeModels(Document templateDocument, TemplateContext templateContext) throws Exception {
    Element templateDocumentElement = templateDocument.getDocumentElement();
    Element templateModelElement = ViewConfigParserUtils.findModelElement(templateDocumentElement,
            templateContext.getResource());

    Document document = templateContext.getSourceDocument();
    Element modelElement = ViewConfigParserUtils.findModelElement(document.getDocumentElement(),
            templateContext.getSourceContext().getResource());

    if (modelElement != null) {
        List<Element> modelElements = DomUtils.getChildElements(modelElement);
        if (!modelElements.isEmpty()) {
            if (templateModelElement == null) {
                templateModelElement = templateDocument.createElement(ViewXmlConstants.MODEL);
                Element viewElement = ViewConfigParserUtils.findViewElement(templateDocumentElement,
                        templateContext.getResource());
                templateDocumentElement.insertBefore(templateModelElement, viewElement);
            }//  w w w  .  j a  va2  s .  c o  m

            for (Element model : modelElements) {
                Element clonedElement = (Element) templateDocument.importNode(model, true);
                templateModelElement.appendChild(clonedElement);
            }
        }
    }
}

From source file:com.enonic.esl.xml.XMLTool.java

public static Element createElement(Document doc, Element root, String name, String text, String sortAttribute,
        String sortValue) {/*from   w  ww  .  ja  v a  2 s  .co  m*/

    if (name == null) {
        throw new XMLToolException("Element name cannot be null!");
    } else if (name.trim().length() == 0) {
        throw new XMLToolException("Element name has to contain at least one character!");
    }

    Element elem = doc.createElement(name);
    if (text != null) {
        Text textNode = doc.createTextNode(StringUtil.getXMLSafeString(text));
        elem.appendChild(textNode);
    }

    if (sortAttribute == null || sortValue == null) {
        root.appendChild(elem);
    } else {
        Element[] childElems = getElements(root);
        if (childElems.length == 0) {
            root.appendChild(elem);
        } else {
            int i = 0;
            for (; i < childElems.length; i++) {
                String childValue = childElems[i].getAttribute(sortAttribute);
                if (childValue != null && childValue.compareToIgnoreCase(sortValue) >= 0) {
                    break;
                }
            }

            if (i < childElems.length) {
                root.insertBefore(elem, childElems[i]);
            } else {
                root.appendChild(elem);
            }
        }
    }

    return elem;
}

From source file:io.fabric8.tooling.archetype.builder.ArchetypeBuilder.java

/**
 * Returns new or existing Element from <code>parent</code>
 *
 * @param doc//from ww w  .j a  v a 2  s.c  om
 * @param parent
 * @param name
 * @param beforeNames
 * @return
 */
private Element replaceOrAddElement(Document doc, Element parent, String name, List<String> beforeNames) {
    NodeList children = parent.getChildNodes();
    List<Element> elements = new LinkedList<Element>();
    for (int cn = 0; cn < children.getLength(); cn++) {
        if (children.item(cn) instanceof Element && children.item(cn).getNodeName().equals(name)) {
            elements.add((Element) children.item(cn));
        }
    }
    Element element = null;
    if (elements.isEmpty()) {
        Element newElement = doc.createElement(name);
        Node first = null;
        for (String n : beforeNames) {
            first = findChild(parent, n);
            if (first != null) {
                break;
            }
        }

        Node node = null;
        if (first != null) {
            node = first;
        } else {
            node = parent.getFirstChild();
        }
        Text text = doc.createTextNode("\n" + indent);
        parent.insertBefore(text, node);
        parent.insertBefore(newElement, text);
        element = newElement;
    } else {
        element = elements.get(0);
    }

    return element;
}

From source file:org.gvnix.web.menu.roo.addon.MenuEntryOperationsImpl.java

/** {@inheritDoc} */
public void moveBefore(JavaSymbolName pageId, JavaSymbolName beforeId) {
    Document document = getMenuDocument();

    // make the root element of the menu the one with the menu identifier
    // allowing for different decorations of menu
    Element rootElement = XmlUtils.findFirstElement(ID_MENU_EXP, (Element) document.getFirstChild());

    if (!rootElement.getNodeName().equals(GVNIX_MENU)) {
        throw new IllegalArgumentException(INVALID_XML);
    }/*from w  ww . j av  a  2s .c o  m*/

    // check for existence of menu category by looking for the identifier
    // provided
    Element pageElement = XmlUtils.findFirstElement(ID_EXP.concat(pageId.getSymbolName()).concat("']"),
            rootElement);

    // exit if menu entry doesn't exist
    Validate.notNull(pageElement, PAGE.concat(pageId.getSymbolName()).concat(NOT_FOUND));

    Element beforeElement = XmlUtils.findFirstElement(ID_EXP.concat(beforeId.getSymbolName()).concat("']"),
            rootElement);

    // exit if menu entry doesn't exist
    Validate.notNull(beforeElement, PAGE.concat(beforeId.getSymbolName()).concat(NOT_FOUND));

    // page parent element where remove menu entry element
    Element pageParentEl = (Element) pageElement.getParentNode();
    pageParentEl.removeChild(pageElement);

    // before parent element where execute insert before
    Element beforeParentEl = (Element) beforeElement.getParentNode();
    beforeParentEl.insertBefore(pageElement, beforeElement);

    writeXMLConfigIfNeeded(document);
}

From source file:com.springsource.hq.plugin.tcserver.plugin.serverconfig.general.GeneralConfigConverter.java

/**
 * This method sifts through server.xml to find the AprLifecycleListener. If it exists, but is not defined in the
 * locally cached copy of GeneralConfig, it is stripped out when pushing a new copy of server.xml. If it exists,
 * then the className is forced to the correct fully qualified class name. If it doesn't exist, and IS defined in
 * GeneralConfig, it is added to server.xml.
 *///from www.  j  a va 2 s.  co m
private void convertAprLifecycleListener(Document document, Element server,
        AprLifecycleListener configuredAprLifecycleListener) {
    Element aprLifecycleListenerXmlElementInServerXml = null;
    Element lastListener = null;
    boolean foundAprLifecycleXmlElementInServerXml = false;

    List<Element> listeners = DomUtils.getChildElementsByTagName(server, TAG_NAME_LISTENER);

    for (Element listener : listeners) {
        lastListener = listener; // We need to catch the last listener, so we can insert before its nextSibling.
        if (isAprLifecycleListener(listener)) {
            foundAprLifecycleXmlElementInServerXml = true;
            aprLifecycleListenerXmlElementInServerXml = listener;
            if (configuredAprLifecycleListener == null) {
                server.removeChild(aprLifecycleListenerXmlElementInServerXml);
            }
        }
    }

    if (configuredAprLifecycleListener != null) {
        if (!foundAprLifecycleXmlElementInServerXml) {
            aprLifecycleListenerXmlElementInServerXml = document.createElement(TAG_NAME_LISTENER);
        }
        aprLifecycleListenerXmlElementInServerXml.setAttribute(ATTRIBUTE_CLASS_NAME,
                CLASS_NAME_APR_LIFECYCLE_LISTENER);
        if (!foundAprLifecycleXmlElementInServerXml) {
            if (lastListener != null) {
                // Strangely, there doesn't appear to be any sort of insertAfter() call, so we have to fetch the
                // next sibling.
                server.insertBefore(aprLifecycleListenerXmlElementInServerXml, lastListener.getNextSibling());
            } else {
                Element globalNamingResources = DomUtils.getChildElementByTagName(server,
                        "GlobalNamingResources");
                server.insertBefore(aprLifecycleListenerXmlElementInServerXml, globalNamingResources);
            }

        }
    }
}

From source file:com.alfaariss.oa.util.configuration.ConfigurationManager.java

/**
 * Saves the configuration.//from w  ww  . j av a  2s .  com
 * @see IConfigurationManager#saveConfiguration()
 */
public synchronized void saveConfiguration() throws ConfigurationException {
    boolean bFound = false;
    Date dNow = null;
    StringBuffer sbComment = null;
    Element elRoot = null;
    Node nCurrent = null;
    Node nComment = null;
    String sValue = null;
    try {
        // add date to configuration
        dNow = new Date(System.currentTimeMillis());

        sbComment = new StringBuffer(" Configuration changes saved on ");
        sbComment.append(DateFormat.getDateInstance().format(dNow));
        sbComment.append(". ");

        elRoot = _oDomDocument.getDocumentElement();
        nCurrent = elRoot.getFirstChild();
        while (!bFound && nCurrent != null) // all elements
        {
            if (nCurrent.getNodeType() == Node.COMMENT_NODE) {
                // check if it's a "save changes" comment
                sValue = nCurrent.getNodeValue();
                if (sValue.trim().startsWith("Configuration changes saved on")) {
                    // overwrite message
                    nCurrent.setNodeValue(sbComment.toString());
                    bFound = true;
                }
            }
            nCurrent = nCurrent.getNextSibling();
        }
        if (!bFound) // no comment found: adding new
        {
            // create new comment node
            nComment = _oDomDocument.createComment(sbComment.toString());
            // insert comment before first node
            elRoot.insertBefore(nComment, elRoot.getFirstChild());
        }
        _oConfigHandler.saveConfiguration(_oDomDocument);
    } catch (ConfigurationException e) {
        throw e;
    } catch (Exception e) {
        _logger.fatal("Internal error", e);
        throw new ConfigurationException(SystemErrors.ERROR_INTERNAL);
    }
}