Example usage for org.w3c.dom Node setTextContent

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

Introduction

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

Prototype

public void setTextContent(String textContent) throws DOMException;

Source Link

Document

This attribute returns the text content of this node and its descendants.

Usage

From source file:org.gvnix.service.roo.addon.addon.ws.WSConfigServiceImpl.java

/**
 * {@inheritDoc}/*from  w w w  . j  a va  2  s. c  om*/
 */
public void addToJava2wsPlugin(JavaType serviceClass, String serviceName, String addressName,
        String fullyQualifiedTypeName) {

    // Get pom
    String pomPath = getPomFilePath();
    Validate.isTrue(pomPath != null, "Cxf configuration file not found, export again the service.");
    MutableFile pomMutableFile = getFileManager().updateFile(pomPath);
    Document pom = getInputDocument(pomMutableFile.getInputStream());
    Element root = pom.getDocumentElement();

    // Gets java2ws plugin element
    Element jaxWsPlugin = XmlUtils.findFirstElement(
            "/project/build/plugins/plugin[groupId='org.apache.cxf' and artifactId='cxf-java2ws-plugin']",
            root);

    // Install it if it's missing
    if (jaxWsPlugin == null) {

        logger.log(Level.INFO, "Jax-Ws plugin is not defined in the pom.xml. Installing in project.");
        // Installs jax2ws plugin.
        addPlugin();
    }

    // Checks if already exists the execution.
    Element serviceExecution = XmlUtils
            .findFirstElement("/project/build/plugins/plugin/executions/execution/configuration[className='"
                    .concat(serviceClass.getFullyQualifiedTypeName()).concat("']"), root);

    if (serviceExecution != null) {
        logger.log(Level.FINE, "A previous Wsdl generation with CXF plugin for '".concat(serviceName)
                .concat("' service has been found."));
        return;
    }

    // Checks if name of java class has been changed comparing current
    // service class and name declared in annotation
    boolean classNameChanged = false;
    if (!serviceClass.getFullyQualifiedTypeName().contentEquals(fullyQualifiedTypeName)) {
        classNameChanged = true;
    }

    // if class has been changed (package or name) update execution
    if (classNameChanged) {
        serviceExecution = XmlUtils
                .findFirstElement("/project/build/plugins/plugin/executions/execution/configuration[className='"
                        .concat(fullyQualifiedTypeName).concat("']"), root);

        // Update with serviceClass.getFullyQualifiedTypeName().
        if (serviceExecution != null && serviceExecution.hasChildNodes()) {

            Node updateServiceExecution;
            updateServiceExecution = (serviceExecution.getFirstChild() != null)
                    ? serviceExecution.getFirstChild().getNextSibling()
                    : null;

            // Find node which contains old class name
            while (updateServiceExecution != null) {

                if (updateServiceExecution.getNodeName().contentEquals("className")) {
                    // Update node content with new value
                    updateServiceExecution.setTextContent(serviceClass.getFullyQualifiedTypeName());

                    // write pom
                    XmlUtils.writeXml(pomMutableFile.getOutputStream(), pom);
                    logger.log(Level.INFO,
                            "Wsdl generation with CXF plugin for '" + serviceName
                                    + " service, updated className attribute for '"
                                    + serviceClass.getFullyQualifiedTypeName() + "'.");
                    // That's all
                    return;
                }

                // Check next node.
                updateServiceExecution = updateServiceExecution.getNextSibling();

            }
        }
    }

    // Prepare Execution configuration
    String executionID = "${project.basedir}/src/test/resources/generated/wsdl/".concat(addressName)
            .concat(".wsdl");
    serviceExecution = createJava2wsExecutionElement(pom, serviceClass, addressName, executionID);

    // Checks if already exists the execution.

    // XXX ??? this is hard difficult because previously it's already
    // checked
    // using class name
    Element oldExecution = XmlUtils.findFirstElement(
            "/project/build/plugins/plugin/executions/execution[id='" + executionID + "']", root);

    if (oldExecution != null) {
        logger.log(Level.FINE, "Wsdl generation with CXF plugin for '" + serviceName
                + " service, has been configured before.");
        return;
    }

    // Checks if already exists the executions to update or create.
    Element oldExecutions = DomUtils.findFirstElementByName(EXECUTIONS, jaxWsPlugin);

    Element newExecutions;

    // To Update execution definitions It must be replaced in pom.xml to
    // maintain the format.
    if (oldExecutions != null) {
        newExecutions = oldExecutions;
        newExecutions.appendChild(serviceExecution);
        oldExecutions.getParentNode().replaceChild(oldExecutions, newExecutions);
    } else {
        newExecutions = pom.createElement(EXECUTIONS);
        newExecutions.appendChild(serviceExecution);

        jaxWsPlugin.appendChild(newExecutions);
    }

    XmlUtils.writeXml(pomMutableFile.getOutputStream(), pom);
}

From source file:it.imtech.metadata.MetaUtility.java

private void addContributorToMetadata(String panelname) {
    try {/*from w  w w .j a  va 2s .c  o  m*/
        DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc;

        XPathFactory factory = XPathFactory.newInstance();
        XPath xpath = factory.newXPath();
        File backupmetadata = new File(Globals.DUPLICATION_FOLDER_SEP + "session" + panelname);
        //File backupmetadata = new File(Globals.SESSION_METADATA);
        doc = dBuilder.parse(backupmetadata);

        String expression = "//*[@ID='11']";
        NodeList nodeList = (NodeList) xpath.evaluate(expression, doc, XPathConstants.NODESET);
        int maxseq = 0;
        int tmpseq = 0;

        for (int i = 0; i < nodeList.getLength(); i++) {
            NamedNodeMap attr = nodeList.item(i).getAttributes();
            Node nodeAttr = attr.getNamedItem("sequence");
            tmpseq = Integer.parseInt(nodeAttr.getNodeValue());

            if (tmpseq > maxseq) {
                maxseq = tmpseq;
            }
        }
        maxseq++;

        Node newNode = nodeList.item(0).cloneNode(true);
        Element nodetocopy = (Element) newNode;
        NamedNodeMap attr = nodeList.item(0).getAttributes();
        Node nodeAttr = attr.getNamedItem("sequence");
        nodeAttr.setTextContent(Integer.toString(maxseq));

        Node copyOfn = doc.importNode(nodetocopy, true);
        nodeList.item(0).getParentNode().appendChild(copyOfn);

        XMLUtil.xmlWriter(doc, Globals.DUPLICATION_FOLDER_SEP + "session" + panelname);
    } catch (ParserConfigurationException ex) {
        logger.error(ex.getMessage());
    } catch (SAXException ex) {
        logger.error(ex.getMessage());
    } catch (IOException ex) {
        logger.error(ex.getMessage());
    } catch (XPathExpressionException ex) {
        logger.error(ex.getMessage());
    }
}

From source file:it.imtech.metadata.MetaUtility.java

private void addClassificationToMetadata(String panelname) {
    try {/*from  w  w w .  jav a 2s  .  c o m*/
        DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc;

        XPathFactory factory = XPathFactory.newInstance();
        XPath xpath = factory.newXPath();

        //File backupmetadata = new File(Globals.SESSION_METADATA);
        File backupmetadata = new File(Globals.DUPLICATION_FOLDER_SEP + "session" + panelname);
        doc = dBuilder.parse(backupmetadata);

        String expression = "//*[@ID='22']";
        NodeList nodeList = (NodeList) xpath.evaluate(expression, doc, XPathConstants.NODESET);
        int maxseq = 0;
        int tmpseq;

        for (int i = 0; i < nodeList.getLength(); i++) {
            NamedNodeMap attr = nodeList.item(i).getAttributes();
            Node nodeAttr = attr.getNamedItem("sequence");
            tmpseq = Integer.parseInt(nodeAttr.getNodeValue());

            if (tmpseq > maxseq) {
                maxseq = tmpseq;
            }
        }
        maxseq++;

        Node newNode = nodeList.item(0).cloneNode(true);
        Element nodetocopy = (Element) newNode;
        NamedNodeMap attr = nodeList.item(0).getAttributes();
        Node nodeAttr = attr.getNamedItem("sequence");
        nodeAttr.setTextContent(Integer.toString(maxseq));

        Node copyOfn = doc.importNode(nodetocopy, true);
        nodeList.item(0).getParentNode().appendChild(copyOfn);

        Element root = doc.getDocumentElement();
        NodeList firstlevelnodes = root.getChildNodes();

        for (int i = 0; i < firstlevelnodes.getLength(); i++) {
            if (firstlevelnodes.item(i).getNodeType() == Node.ELEMENT_NODE) {
                Element node = (Element) firstlevelnodes.item(i);
                Integer sequence = Integer.parseInt(node.getAttribute("sequence"));
                if (!node.getAttribute("ID").equals("22") && sequence >= maxseq) {
                    node.setAttribute("sequence", Integer.toString(sequence + 1));
                }
            }
        }

        XMLUtil.xmlWriter(doc, Globals.DUPLICATION_FOLDER_SEP + "session" + panelname);
    } catch (ParserConfigurationException ex) {
        logger.error(ex.getMessage());
    } catch (SAXException ex) {
        logger.error(ex.getMessage());
    } catch (IOException ex) {
        logger.error(ex.getMessage());
    } catch (XPathExpressionException ex) {
        logger.error(ex.getMessage());
    }
}

From source file:com.occamlab.te.parsers.ImageParser.java

private static void processBufferedImage(BufferedImage buffimage, String formatName, NodeList nodes)
        throws Exception {
    HashMap<Object, Object> bandMap = new HashMap<Object, Object>();

    for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            if (node.getLocalName().equals("subimage")) {
                Element e = (Element) node;
                int x = Integer.parseInt(e.getAttribute("x"));
                int y = Integer.parseInt(e.getAttribute("y"));
                int w = Integer.parseInt(e.getAttribute("width"));
                int h = Integer.parseInt(e.getAttribute("height"));
                processBufferedImage(buffimage.getSubimage(x, y, w, h), formatName, e.getChildNodes());
            } else if (node.getLocalName().equals("checksum")) {
                CRC32 checksum = new CRC32();
                Raster raster = buffimage.getRaster();
                DataBufferByte buffer;
                if (node.getParentNode().getLocalName().equals("subimage")) {
                    WritableRaster outRaster = raster.createCompatibleWritableRaster();
                    buffimage.copyData(outRaster);
                    buffer = (DataBufferByte) outRaster.getDataBuffer();
                } else {
                    buffer = (DataBufferByte) raster.getDataBuffer();
                }/*www .  jav a  2  s. co m*/
                int numbanks = buffer.getNumBanks();
                for (int j = 0; j < numbanks; j++) {
                    checksum.update(buffer.getData(j));
                }
                Document doc = node.getOwnerDocument();
                node.appendChild(doc.createTextNode(Long.toString(checksum.getValue())));
            } else if (node.getLocalName().equals("count")) {
                String band = ((Element) node).getAttribute("bands");
                String sample = ((Element) node).getAttribute("sample");
                if (sample.equals("all")) {
                    bandMap.put(band, null);
                } else {
                    HashMap<Object, Object> sampleMap = (HashMap<Object, Object>) bandMap.get(band);
                    if (sampleMap == null) {
                        if (!bandMap.containsKey(band)) {
                            sampleMap = new HashMap<Object, Object>();
                            bandMap.put(band, sampleMap);
                        }
                    }
                    sampleMap.put(Integer.decode(sample), new Integer(0));
                }
            } else if (node.getLocalName().equals("transparentNodata")) { // 2011-08-24
                                                                          // PwD
                String transparentNodata = checkTransparentNodata(buffimage, node);
                node.setTextContent(transparentNodata);
            }
        }
    }

    Iterator bandIt = bandMap.keySet().iterator();
    while (bandIt.hasNext()) {
        String band_str = (String) bandIt.next();
        int band_indexes[];
        if (buffimage.getType() == BufferedImage.TYPE_BYTE_BINARY
                || buffimage.getType() == BufferedImage.TYPE_BYTE_GRAY) {
            band_indexes = new int[1];
            band_indexes[0] = 0;
        } else {
            band_indexes = new int[band_str.length()];
            for (int i = 0; i < band_str.length(); i++) {
                if (band_str.charAt(i) == 'A')
                    band_indexes[i] = 3;
                if (band_str.charAt(i) == 'B')
                    band_indexes[i] = 2;
                if (band_str.charAt(i) == 'G')
                    band_indexes[i] = 1;
                if (band_str.charAt(i) == 'R')
                    band_indexes[i] = 0;
            }
        }

        Raster raster = buffimage.getRaster();
        java.util.HashMap sampleMap = (java.util.HashMap) bandMap.get(band_str);
        boolean addall = (sampleMap == null);
        if (sampleMap == null) {
            sampleMap = new java.util.HashMap();
            bandMap.put(band_str, sampleMap);
        }

        int minx = raster.getMinX();
        int maxx = minx + raster.getWidth();
        int miny = raster.getMinY();
        int maxy = miny + raster.getHeight();
        int bands[][] = new int[band_indexes.length][raster.getWidth()];

        for (int y = miny; y < maxy; y++) {
            for (int i = 0; i < band_indexes.length; i++) {
                raster.getSamples(minx, y, maxx, 1, band_indexes[i], bands[i]);
            }
            for (int x = minx; x < maxx; x++) {
                int sample = 0;
                for (int i = 0; i < band_indexes.length; i++) {
                    sample |= bands[i][x] << ((band_indexes.length - i - 1) * 8);
                }

                Integer sampleObj = new Integer(sample);

                boolean add = addall;
                if (!addall) {
                    add = sampleMap.containsKey(sampleObj);
                }
                if (add) {
                    Integer count = (Integer) sampleMap.get(sampleObj);
                    if (count == null) {
                        count = new Integer(0);
                    }
                    count = new Integer(count.intValue() + 1);
                    sampleMap.put(sampleObj, count);
                }
            }
        }
    }

    Node node = nodes.item(0);
    while (node != null) {
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            if (node.getLocalName().equals("count")) {
                String band = ((Element) node).getAttribute("bands");
                String sample = ((Element) node).getAttribute("sample");
                HashMap sampleMap = (HashMap) bandMap.get(band);
                Document doc = node.getOwnerDocument();
                if (sample.equals("all")) {
                    Node parent = node.getParentNode();
                    Node prevSibling = node.getPreviousSibling();
                    Iterator sampleIt = sampleMap.keySet().iterator();
                    Element countnode = null;
                    int digits;
                    String prefix;
                    switch (buffimage.getType()) {
                    case BufferedImage.TYPE_BYTE_BINARY:
                        digits = 1;
                        prefix = "";
                        break;
                    case BufferedImage.TYPE_BYTE_GRAY:
                        digits = 2;
                        prefix = "0x";
                        break;
                    default:
                        prefix = "0x";
                        digits = band.length() * 2;
                    }
                    while (sampleIt.hasNext()) {
                        countnode = doc.createElementNS(node.getNamespaceURI(), "count");
                        Integer sampleInt = (Integer) sampleIt.next();
                        Integer count = (Integer) sampleMap.get(sampleInt);
                        if (band.length() > 0) {
                            countnode.setAttribute("bands", band);
                        }
                        countnode.setAttribute("sample", prefix + HexString(sampleInt.intValue(), digits));
                        Node textnode = doc.createTextNode(count.toString());
                        countnode.appendChild(textnode);
                        parent.insertBefore(countnode, node);
                        if (sampleIt.hasNext()) {
                            if (prevSibling != null && prevSibling.getNodeType() == Node.TEXT_NODE) {
                                parent.insertBefore(prevSibling.cloneNode(false), node);
                            }
                        }
                    }
                    parent.removeChild(node);
                    node = countnode;
                } else {
                    Integer count = (Integer) sampleMap.get(Integer.decode(sample));
                    if (count == null)
                        count = new Integer(0);
                    Node textnode = doc.createTextNode(count.toString());
                    node.appendChild(textnode);
                }
            }
        }
        node = node.getNextSibling();
    }
}

From source file:com.rapid.core.Page.java

public static Page load(ServletContext servletContext, File file)
        throws JAXBException, ParserConfigurationException, SAXException, IOException,
        TransformerFactoryConfigurationError, TransformerException {

    // get the logger
    Logger logger = (Logger) servletContext.getAttribute("logger");

    // trace log that we're about to load a page
    logger.trace("Loading page from " + file);

    // open the xml file into a document
    Document pageDocument = XML.openDocument(file);

    // specify the xmlVersion as -1
    int xmlVersion = -1;

    // look for a version node
    Node xmlVersionNode = XML.getChildElement(pageDocument.getFirstChild(), "XMLVersion");

    // if we got one update the version
    if (xmlVersionNode != null)
        xmlVersion = Integer.parseInt(xmlVersionNode.getTextContent());

    // if the version of this xml isn't the same as this class we have some work to do!
    if (xmlVersion != XML_VERSION) {

        // get the page name
        String name = XML.getChildElementValue(pageDocument.getFirstChild(), "name");

        // log the difference
        logger.debug("Page " + name + " with version " + xmlVersion + ", current version is " + XML_VERSION);

        ///*from  w  w w . j a v  a 2 s .com*/
        // Here we would have code to update from known versions of the file to the current version
        //

        // check whether there was a version node in the file to start with
        if (xmlVersionNode == null) {
            // create the version node
            xmlVersionNode = pageDocument.createElement("XMLVersion");
            // add it to the root of the document
            pageDocument.getFirstChild().appendChild(xmlVersionNode);
        }

        // set the xml to the latest version
        xmlVersionNode.setTextContent(Integer.toString(XML_VERSION));

        //
        // Here we would use xpath to find all controls and run the Control.upgrade method
        //

        //
        // Here we would use xpath to find all actions, each class has it's own upgrade method so
        // we need to identify the class, instantiate it and call it's upgrade method
        // it's probably worthwhile maintaining a map of instantiated classes to avoid unnecessary re-instantiation   
        //

        // save it
        XML.saveDocument(pageDocument, file);

        logger.debug("Updated " + name + " page version to " + XML_VERSION);

    }

    // get the unmarshaller from the context
    Unmarshaller unmarshaller = RapidHttpServlet.getUnmarshaller();

    // get a buffered reader for our page with UTF-8 file format
    BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));

    // try the unmarshalling
    try {

        // unmarshall the page
        Page page = (Page) unmarshaller.unmarshal(br);

        // log that the page was loaded
        logger.debug("Loaded page " + page.getId() + " - " + page.getName() + " from " + file);

        // close the buffered reader
        br.close();

        // return the page      
        return page;

    } catch (JAXBException ex) {

        // close the buffered reader
        br.close();

        // log that the page had an error
        logger.error("Error loading page from " + file);

        // re-throw
        throw ex;

    }

}

From source file:com.hygenics.parser.ManualReplacement.java

private void transform() {
    log.info("Transforming");

    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    for (String fpath : fpaths) {
        log.info("FILE: " + fpath);
        try {//from   ww  w. j  a  va2s . c o m
            // TRANSFORM
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
            Document doc = docBuilder.parse(new File(fpath));
            Node root = doc.getFirstChild();
            XPathFactory xfactory = XPathFactory.newInstance();
            XPath xpath = xfactory.newXPath();
            String database = null;
            String path = "//transformation/connection";

            log.info("Removing");
            for (String dbname : remove) {
                log.info("XPATH:" + path + "[descendant::name[contains(text(),'" + dbname.trim() + "')]]");
                XPathExpression xepr = xpath
                        .compile(path + "[descendant::name[contains(text(),'" + dbname.trim() + "')]]");
                Node conn = (Node) xepr.evaluate(doc, XPathConstants.NODE);
                if (conn != null) {
                    root.removeChild(conn);
                }
            }

            log.info("Transforming");
            for (String key : databaseAttributes.keySet()) {
                database = key;
                log.info("XPATH:" + path + "[descendant::name[contains(text(),'" + database.trim() + "')]]");
                XPathExpression xepr = xpath
                        .compile(path + "[descendant::name[contains(text(),'" + database.trim() + "')]]");
                Node conn = (Node) xepr.evaluate(doc, XPathConstants.NODE);

                if (conn != null) {
                    if (remove.contains(key)) {
                        root.removeChild(conn);
                    } else {
                        Map<String, String> attrs = databaseAttributes.get(database);
                        NodeList nl = conn.getChildNodes();
                        Set<String> keys = databaseAttributes.get(key).keySet();

                        for (int i = 0; i < nl.getLength(); i++) {
                            org.w3c.dom.Node n = nl.item(i);

                            if (keys.contains(n.getNodeName().trim())) {
                                n.setNodeValue(attrs.get(n.getNodeName()));
                            }
                        }
                    }
                }

                if (!this.log_to_table || (this.log_to_table && this.loggingTables != null)) {
                    log.info("Logging Manipulation");
                    log.info("PERFORMING LOGGING MANIPULATION: " + (!this.log_to_table) != null
                            ? "Removing Logging Data"
                            : "Adding Logging data");
                    String[] sections = new String[] { "trans-log-table", "perf-log-table", "channel-log-table",
                            "step-log-table", "metrics-log-table" };
                    for (String section : sections) {
                        log.info("Changing Settings for " + section);
                        xepr = xpath.compile("//" + section + "/field/enabled");
                        NodeList nodes = (NodeList) xepr.evaluate(doc, XPathConstants.NODESET);
                        log.info("Nodes Found: " + Integer.toString(nodes.getLength()));
                        for (int i = 0; i < nodes.getLength(); i++) {
                            if (!this.log_to_table) {
                                nodes.item(i).setNodeValue("N");
                            } else {
                                nodes.item(i).setNodeValue("Y");
                            }
                        }

                        for (String nodeName : new String[] { "schema", "connection", "table",
                                "size_limit_lines", "interval", "timeout_days" }) {
                            if (!this.log_to_table) {
                                log.info("Changing Settings for Node: " + nodeName);
                                xepr = xpath.compile("//" + section + "/" + nodeName);
                                Node node = (Node) xepr.evaluate(doc, XPathConstants.NODE);
                                if (node != null) {
                                    if (!this.log_to_table) {
                                        node.setNodeValue(null);
                                    } else if (this.loggingTables.containsKey(section)
                                            && this.loggingTables.get(section).containsKey(nodeName)) {
                                        node.setNodeValue(this.loggingTables.get(section).get(nodeName));
                                    }
                                }
                            }
                        }
                    }
                }
            }

            // SET MAIN CONNECTION
            if (mainConnection != null) {
                XPathExpression xepr = xpath.compile(path);
                NodeList conns = (NodeList) xepr.evaluate(doc, XPathConstants.NODESET); // NodeSet is not a part of
                // org.w3c it is
                // actually a NodeList
                for (int i = 0; i < conns.getLength(); i++) {
                    if (!conns.item(i).hasChildNodes()) {// only connection
                        // elements
                        // without child
                        // nodes have
                        // text content
                        conns.item(i).setNodeValue(mainConnection);
                    }
                }
            }

            if (this.replacements != null) {
                for (String key : this.replacements.keySet()) {
                    XPathExpression xepr = xpath.compile(key);
                    Node node = (Node) xepr.evaluate(doc, XPathConstants.NODE);
                    if (node != null) {
                        for (String attrVal : this.replacements.get(key).keySet()) {
                            log.info("Replacing Information at " + key + "at " + attrVal);
                            log.info("Replacement Will Be: "
                                    + StringEscapeUtils.escapeXml11(this.replacements.get(key).get(attrVal)));

                            if (attrVal.toLowerCase().trim().equals("text")) {
                                node.setNodeValue(
                                        StringEscapeUtils.escapeXml11(this.replacements.get(key).get(attrVal)));
                                if (node.getNodeValue() == null) {
                                    node.setTextContent(StringEscapeUtils
                                            .escapeXml11(this.replacements.get(key).get(attrVal)));
                                }

                            } else {
                                NamedNodeMap nattrs = node.getAttributes();
                                Node n = nattrs.getNamedItem(attrVal);
                                if (n != null) {
                                    n.setNodeValue(StringEscapeUtils
                                            .escapeXml11(this.replacements.get(key).get(attrVal)));
                                } else {
                                    log.warn("Attribute Not Found " + attrVal);
                                }
                            }
                        }
                    } else {
                        log.warn("Node not found for " + key);
                    }
                }
            }

            // WRITE TO FILE
            log.info("Writing to File");
            TransformerFactory tfact = TransformerFactory.newInstance();
            Transformer transformer = tfact.newTransformer();
            DOMSource source = new DOMSource(doc);
            try (FileOutputStream stream = new FileOutputStream(new File(fpath))) {
                StreamResult result = new StreamResult(stream);
                transformer.transform(source, result);
                stream.flush();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (TransformerException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }

        } catch (IOException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (XPathExpressionException e) {
            e.printStackTrace();
        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.mirth.connect.model.util.ImportConverter.java

/** Convert http connector and destination settings */
private static void convertHttpConnectorFor2_0(Document document, Element connectorRoot) throws Exception {

    // convert HTTP Listener and HTTP writer to the new formats
    Node transportNode = getConnectorTransportNode(connectorRoot);
    String transportNameText = transportNode.getTextContent();
    String attribute = "";
    String value = "";
    Element propertiesElement = getPropertiesElement(connectorRoot);

    // Default Properties
    Map<String, String> propertyDefaults = new HashMap<String, String>();

    // Properties to be added if missing, or reset if present
    Map<String, String> propertyChanges = new HashMap<String, String>();

    // logic to deal with HTTP listener settings
    if (transportNameText.equals("HTTP Listener") || transportNameText.equals("HTTPS Listener")) {
        NodeList properties = connectorRoot.getElementsByTagName("property");

        // set defaults
        propertyDefaults.put("DataType", "HTTP Listener");
        propertyDefaults.put("host", "0.0.0.0");
        propertyDefaults.put("port", "80");
        propertyDefaults.put("receiverResponse", "None");
        propertyDefaults.put("receiverBodyOnly", "1");
        propertyDefaults.put("HTTP_RESPONSE_CONTENT_TYPE", "text/plain");

        // rename properties
        for (int i = 0; i < properties.getLength(); i++) {
            // get the current attribute and current value
            attribute = properties.item(i).getAttributes().item(0).getTextContent();
            value = properties.item(i).getTextContent();

            // Now rename attributes
            if (attribute.equals("responseValue")) {
                propertyChanges.put("receiverResponse", value);
            }//from   w  ww.jav a  2  s. co m

            if (attribute.equals("appendPayload")) {
                // The old property value needs to be flipped
                // If appendPayload was 1, set bodyOnly to 0
                // If appendPayload was 0 or null, set bodyOnly to 1
                propertyChanges.put("receiverBodyOnly", ("1".equals(value) ? "0" : "1"));
            }
        }

        // set changes
        propertyChanges.put("host", "0.0.0.0");
        propertyChanges.put("DataType", "HTTP Listener");

        // set new name of transport node
        transportNode.setTextContent("HTTP Listener");

        // update properties
        updateProperties(document, propertiesElement, propertyDefaults, propertyChanges);

    } else if (transportNameText.equals("HTTP Sender") || transportNameText.equals("HTTPS Sender")) {
        // get properties
        NodeList properties = connectorRoot.getElementsByTagName("property");

        // disable connector
        // document.getElementsByTagName("enabled").item(0).setTextContent("false");

        // set defaults
        ObjectXMLSerializer serializer = ObjectXMLSerializer.getInstance();

        propertyDefaults.put("DataType", "HTTP Sender");
        propertyDefaults.put("host", "");

        propertyDefaults.put("dispatcherMethod", "POST");
        propertyDefaults.put("dispatcherHeaders", serializer.serialize(new Properties()));
        propertyDefaults.put("dispatcherParameters", serializer.serialize(new Properties()));
        propertyDefaults.put("dispatcherReplyChannelId", "sink");
        propertyDefaults.put("dispatcherIncludeHeadersInResponse", "0");
        propertyDefaults.put("dispatcherMultipart", "0");
        propertyDefaults.put("dispatcherUseAuthentication", "0");
        propertyDefaults.put("dispatcherAuthenticationType", "Basic");
        propertyDefaults.put("dispatcherUsername", "");
        propertyDefaults.put("dispatcherPassword", "");
        propertyDefaults.put("dispatcherContent", "");
        propertyDefaults.put("dispatcherContentType", "text/plain");
        propertyDefaults.put("dispatcherCharset", "UTF-8");
        propertyDefaults.put("dispatcherSocketTimeout", "30000");

        // Add new queue property
        propertyDefaults.put("queuePollInterval", "200");

        for (int i = 0; i < properties.getLength(); i++) {
            // get the current attribute and current value
            attribute = properties.item(i).getAttributes().item(0).getTextContent();
            value = properties.item(i).getTextContent();

            // Now rename attributes
            if (attribute.equals("method")) {
                propertyChanges.put("dispatcherMethod", value);
            }

            if (attribute.equals("requestVariables")) {
                // get the properties object for the variables
                Properties tempProps = serializer.deserialize(value, Properties.class);

                // set the content of 2.0 to be $payload of 1.8.2
                propertyChanges.put("dispatcherContent", tempProps.getProperty("$payload", ""));

                // remove $payload as we dont need it
                tempProps.remove("$payload");

                // set the params
                propertyChanges.put("dispatcherParameters", serializer.serialize(tempProps));
            }

            if (attribute.equals("replyChannelId")) {
                propertyChanges.put("dispatcherReplyChannelId", value);
            }

            if (attribute.equals("headerVariables")) {
                propertyChanges.put("dispatcherHeaders", value);
            }

            if (attribute.equals("excludeHeaders")) {
                if (value.equals("0")) {
                    propertyChanges.put("dispatcherIncludeHeadersInResponse", "1");
                } else {
                    propertyChanges.put("dispatcherIncludeHeadersInResponse", "0");
                }
            }

            if (attribute.equals("multipart")) {
                propertyChanges.put("dispatcherMultipart", value);
            }
        }

        // If we have a post/put message and blank content, then disable
        String requestMethod = propertyChanges.get("dispatcherMethod") == null
                ? propertyDefaults.get("dispatcherMethod")
                : propertyChanges.get("dispatcherMethod");
        String requestContent = propertyChanges.get("dispatcherContent") == null
                ? propertyDefaults.get("dispatcherContent")
                : propertyChanges.get("dispatcherContent");

        if (requestContent.length() == 0
                && (requestMethod.equalsIgnoreCase("POST") || requestMethod.equalsIgnoreCase("PUT"))) {
            document.getElementsByTagName("enabled").item(0).setTextContent("false");
        }

        propertyChanges.put("DataType", "HTTP Sender");

        // set new name of transport node
        transportNode.setTextContent("HTTP Sender");

        updateProperties(document, propertiesElement, propertyDefaults, propertyChanges);
    }
}

From source file:com.rapid.core.Application.java

public static Application load(ServletContext servletContext, File file, boolean initialise)
        throws JAXBException, JSONException, InstantiationException, IllegalAccessException,
        ClassNotFoundException, IllegalArgumentException, SecurityException, InvocationTargetException,
        NoSuchMethodException, IOException, ParserConfigurationException, SAXException,
        TransformerFactoryConfigurationError, TransformerException, RapidLoadingException,
        XPathExpressionException {

    // get the logger
    Logger logger = (Logger) servletContext.getAttribute("logger");

    // trace log that we're about to load a page
    logger.trace("Loading application from " + file);

    // open the xml file into a document
    Document appDocument = XML.openDocument(file);

    // specify the version as -1
    int xmlVersion = -1;

    // look for a version node
    Node xmlVersionNode = XML.getChildElement(appDocument.getFirstChild(), "XMLVersion");

    // if we got one update the version
    if (xmlVersionNode != null)
        xmlVersion = Integer.parseInt(xmlVersionNode.getTextContent());

    // if the version of this xml isn't the same as this class we have some work to do!
    if (xmlVersion != XML_VERSION) {

        // get the page name
        String name = XML.getChildElementValue(appDocument.getFirstChild(), "name");

        // log the difference
        logger.debug("Application " + name + " with xml version " + xmlVersion + ", current xml version is "
                + XML_VERSION);/*from  w ww  .j  a  va 2s .  co m*/

        //
        // Here we would have code to update from known versions of the file to the current version
        //

        // check whether there was a version node in the file to start with
        if (xmlVersionNode == null) {
            // create the version node
            xmlVersionNode = appDocument.createElement("XMLVersion");
            // add it to the root of the document
            appDocument.getFirstChild().appendChild(xmlVersionNode);
        }

        // set the xml to the latest version
        xmlVersionNode.setTextContent(Integer.toString(XML_VERSION));

        // save it
        XML.saveDocument(appDocument, file);

        logger.debug("Updated " + name + " application xml version to " + XML_VERSION);

    }

    // get the unmarshaller 
    Unmarshaller unmarshaller = RapidHttpServlet.getUnmarshaller();

    try {

        // unmarshall the application
        Application application = (Application) unmarshaller.unmarshal(file);

        // if we don't want pages loaded or resource generation skip this
        if (initialise) {

            // load the pages (actually clears down the pages collection and reloads the headers)
            application.getPages().loadpages(servletContext);

            // initialise the application and create the resources
            application.initialise(servletContext, true);

        }

        // log that the application was loaded
        logger.info("Loaded application " + application.getName() + "/" + application.getVersion()
                + (initialise ? "" : " (no initialisation)"));

        return application;

    } catch (JAXBException ex) {

        throw new RapidLoadingException("Error loading application file at " + file, ex);

    }

}

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

public static void changeNode(Document dom, XPath xpath, String path, String nodeName, String value) {
    try {//w w w . j  a  v  a 2 s . co  m
        XPathExpression salRO = xpath.compile(path + "/" + nodeName);
        NodeList salRONodes = (NodeList) salRO.evaluate(dom, XPathConstants.NODESET);
        if (salRONodes.getLength() > 0) {
            for (int t = 0; t < salRONodes.getLength(); t++) {
                Node AddrNode = salRONodes.item(t);
                if (AddrNode.getNodeName().equals("name")) {
                    AddrNode.setTextContent(value);
                }
            }
        }
    } catch (Exception e) {
        _log.error("Error fixing node ...");
    }
}

From source file:com.mirth.connect.model.util.ImportConverter.java

/** Convert soap connector and destination settings */
private static void convertSoapConnectorFor2_0(Document document, Element connectorRoot) throws Exception {

    // convert SOAP reader and SOAP writer to the new formats
    Node transportNode = getConnectorTransportNode(connectorRoot);
    String transportNameText = transportNode.getTextContent();
    String attribute = "";
    String value = "";
    Element propertiesElement = getPropertiesElement(connectorRoot);

    // Default Properties
    Map<String, String> propertyDefaults = new HashMap<String, String>();

    // Properties to be added if missing, or reset if present
    Map<String, String> propertyChanges = new HashMap<String, String>();

    // logic to deal with SOAP listener settings
    if (transportNameText.equals("SOAP Listener")) {
        NodeList properties = connectorRoot.getElementsByTagName("property");

        // set defaults
        propertyDefaults.put("DataType", "Web Service Listener");
        propertyDefaults.put("host", "0.0.0.0");
        propertyDefaults.put("port", "8081");
        propertyDefaults.put("receiverClassName", "com.mirth.connect.connectors.ws.DefaultAcceptMessage");
        propertyDefaults.put("receiverServiceName", "Mirth");
        propertyDefaults.put("receiverResponseValue", "None");
        ObjectXMLSerializer serializer = ObjectXMLSerializer.getInstance();
        propertyDefaults.put("receiverUsernames", serializer.serialize(new ArrayList<String>()));
        propertyDefaults.put("receiverPasswords", serializer.serialize(new ArrayList<String>()));

        // rename properties
        for (int i = 0; i < properties.getLength(); i++) {
            // get the current attribute and current value
            attribute = properties.item(i).getAttributes().item(0).getTextContent();
            value = properties.item(i).getTextContent();

            // Now rename attributes
            if (attribute.equals("externalAddress")) {
                propertyChanges.put("host", value);
            }/*  w ww  . j a v  a 2  s . com*/

            if (attribute.equals("responseValue")) {
                propertyChanges.put("receiverResponseValue", value);
            }

            if (attribute.equals("serviceName")) {
                propertyChanges.put("receiverServiceName", value);
            }
        }

        // set changes
        propertyChanges.put("DataType", "Web Service Listener");

        // set new name of transport node
        transportNode.setTextContent("Web Service Listener");

        // update properties
        updateProperties(document, propertiesElement, propertyDefaults, propertyChanges);

    } else if (transportNameText.equals("SOAP Sender")) {
        // get properties
        NodeList properties = connectorRoot.getElementsByTagName("property");

        // disable connector
        document.getElementsByTagName("enabled").item(0).setTextContent("false");

        // set defaults
        propertyDefaults.put("DataType", "Web Service Sender");
        propertyDefaults.put("host", "");
        propertyDefaults.put("dispatcherWsdlCacheId", "");
        propertyDefaults.put("dispatcherWsdlUrl", "");
        propertyDefaults.put("dispatcherService", "");
        propertyDefaults.put("dispatcherPort", "");
        propertyDefaults.put("dispatcherOperation", "Press Get Operations");
        propertyDefaults.put("dispatcherUseAuthentication", "0");
        propertyDefaults.put("dispatcherUsername", "");
        propertyDefaults.put("dispatcherPassword", "");
        propertyDefaults.put("dispatcherEnvelope", "");
        propertyDefaults.put("dispatcherOneWay", "0");
        propertyDefaults.put("dispatcherUseMtom", "0");
        propertyDefaults.put("dispatcherReplyChannelId", "sink");

        ObjectXMLSerializer serializer = ObjectXMLSerializer.getInstance();

        ArrayList<String> defaultOperations = new ArrayList<String>();
        defaultOperations.add("Press Get Operations");
        propertyDefaults.put("dispatcherWsdlOperations", serializer.serialize(defaultOperations));

        propertyDefaults.put("dispatcherAttachmentNames", serializer.serialize(new ArrayList<String>()));
        propertyDefaults.put("dispatcherAttachmentContents", serializer.serialize(new ArrayList<String>()));
        propertyDefaults.put("dispatcherAttachmentTypes", serializer.serialize(new ArrayList<String>()));

        // Add new queue property
        propertyDefaults.put("queuePollInterval", "200");

        for (int i = 0; i < properties.getLength(); i++) {
            // get the current attribute and current value
            attribute = properties.item(i).getAttributes().item(0).getTextContent();
            value = properties.item(i).getTextContent();

            // Now rename attributes
            if (attribute.equals("attachmentNames")) {
                propertyChanges.put("dispatcherAttachmentNames", value);

                if (StringUtils.isNotBlank(value) && !value.trim().equals("<list/>")) {
                    propertyChanges.put("dispatcherUseMtom", "1");
                }
            }

            if (attribute.equals("wsdlUrl")) {
                propertyChanges.put("dispatcherWsdlUrl", value);
            }

            if (attribute.equals("soapActionURI")) {
                propertyChanges.put("dispatcherSoapAction", value);
            }

            if (attribute.equals("method")) {
                propertyChanges.put("dispatcherOperation", value);

                if (StringUtils.isNotBlank(value)) {
                    defaultOperations.clear();
                    defaultOperations.add(value);
                    propertyChanges.put("dispatcherWsdlOperations", serializer.serialize(defaultOperations));
                }
            }

            if (attribute.equals("replyChannelId")) {
                propertyChanges.put("dispatcherReplyChannelId", value);
            }

            if (attribute.equals("attachmentContents")) {
                propertyChanges.put("dispatcherAttachmentContents", value);
            }

            if (attribute.equals("soapEnvelope")) {
                propertyChanges.put("dispatcherEnvelope", value);
            }

            if (attribute.equals("attachmentTypes")) {
                propertyChanges.put("dispatcherAttachmentTypes", value);
            }
        }

        propertyChanges.put("DataType", "Web Service Sender");

        // set new name of transport node
        transportNode.setTextContent("Web Service Sender");
        updateProperties(document, propertiesElement, propertyDefaults, propertyChanges);
    }
}