Example usage for org.w3c.dom Document createCDATASection

List of usage examples for org.w3c.dom Document createCDATASection

Introduction

In this page you can find the example usage for org.w3c.dom Document createCDATASection.

Prototype

public CDATASection createCDATASection(String data) throws DOMException;

Source Link

Document

Creates a CDATASection node whose value is the specified string.

Usage

From source file:net.sourceforge.pmd.util.designer.Designer.java

private void saveSettings() {
    try {//from w  w w  .j a  v  a  2s .  c o m
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.newDocument();

        Element settingsElement = document.createElement("settings");
        document.appendChild(settingsElement);

        Element codeElement = document.createElement("code");
        settingsElement.appendChild(codeElement);
        codeElement.setAttribute("language-version", getLanguageVersion().getTerseName());
        codeElement.appendChild(document.createCDATASection(codeEditorPane.getText()));

        Element xpathElement = document.createElement("xpath");
        settingsElement.appendChild(xpathElement);
        xpathElement.setAttribute("version", xpathVersionButtonGroup.getSelection().getActionCommand());
        xpathElement.appendChild(document.createCDATASection(xpathQueryArea.getText()));

        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        // This is as close to pretty printing as we'll get using standard
        // Java APIs.
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "3");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

        Source source = new DOMSource(document);
        Result result = new StreamResult(
                Files.newBufferedWriter(new File(SETTINGS_FILE_NAME).toPath(), StandardCharsets.UTF_8));
        transformer.transform(source, result);
    } catch (ParserConfigurationException | IOException | TransformerException e) {
        e.printStackTrace();
    }
}

From source file:nl.b3p.kaartenbalie.service.servlet.CallWMSServlet.java

private void handleRequestExceptionAsXML(Exception ex, DataWrapper data) throws IOException {
    ByteArrayOutputStream output = null;
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(false);/* w  ww . j  a  v a2  s .c  o  m*/
    dbf.setNamespaceAware(true);
    DocumentBuilder db = null;
    try {
        db = dbf.newDocumentBuilder();
    } catch (Exception e) {
        log.error("error: ", e);
        throw new IOException("Exception occured during creation of error message: " + e);
    }

    DOMImplementation di = db.getDOMImplementation();

    // <!DOCTYPE ServiceExceptionReport SYSTEM "http://schemas.opengeospatial.net/wms/1.1.1/exception_1_1_1.dtd"
    // <!-- end of DOCTYPE declaration -->
    DocumentType dt = di.createDocumentType("ServiceExceptionReport", null, CallWMSServlet.EXCEPTION_DTD);
    Document dom = di.createDocument(null, "ServiceExceptionReport", dt);
    Element rootElement = dom.getDocumentElement();
    rootElement.setAttribute("version", "1.1.1");

    Element serviceExceptionElement = dom.createElement("ServiceException");

    String exceptionName = ex.getClass().getName();
    String message = ex.getMessage();
    Throwable cause = ex.getCause();

    serviceExceptionElement.setAttribute("code", exceptionName);
    CDATASection cdata = null;
    if (cause != null) {
        cdata = dom.createCDATASection(message + " - " + cause);
    } else {
        cdata = dom.createCDATASection(message);
    }

    serviceExceptionElement.appendChild(cdata);
    rootElement.appendChild(serviceExceptionElement);

    OutputFormat format = new OutputFormat(dom);
    format.setIndenting(true);
    output = new ByteArrayOutputStream();
    XMLSerializer serializer = new XMLSerializer(output, format);
    serializer.serialize(dom);

    DOMValidator dv = new DOMValidator();
    try {
        dv.parseAndValidate(new ByteArrayInputStream(output.toString().getBytes(KBConfiguration.CHARSET)));
    } catch (Exception e) {
        log.error("error: ", e);
        throw new IOException("Exception occured during validation of error message: " + e);
    }

    data.setHeader("Content-Disposition", "inline; filename=\"ServiceException.xml\";");
    data.write(output);
}

From source file:org.ajax4jsf.webapp.tidy.TidyParser.java

private org.w3c.dom.Node importNode(Document document, org.w3c.dom.Node node, boolean recursive) {

    switch (node.getNodeType()) {
    case org.w3c.dom.Node.ELEMENT_NODE:
        Element element = document.createElement(node.getNodeName());

        NamedNodeMap attributes = node.getAttributes();
        if (attributes != null) {
            int length = attributes.getLength();
            for (int i = 0; i < length; i++) {
                element.setAttributeNode((Attr) importNode(document, attributes.item(i), recursive));
            }/*w w w .  j a  v  a  2  s .c  o  m*/
        }

        if (recursive) {
            NodeList childNodes = node.getChildNodes();
            if (childNodes != null) {
                int length = childNodes.getLength();
                for (int i = 0; i < length; i++) {
                    element.appendChild(importNode(document, childNodes.item(i), recursive));
                }
            }
        }

        return element;

    case org.w3c.dom.Node.ATTRIBUTE_NODE:
        Attr attr = document.createAttribute(node.getNodeName());
        attr.setNodeValue(node.getNodeValue());

        return attr;

    case org.w3c.dom.Node.TEXT_NODE:
        String charData = ((CharacterData) node).getData();

        return document.createTextNode(charData);

    case org.w3c.dom.Node.CDATA_SECTION_NODE:
        charData = ((CharacterData) node).getData();

        return document.createCDATASection(charData);
    case org.w3c.dom.Node.COMMENT_NODE:
        charData = ((CharacterData) node).getData();

        return document.createComment(charData);
    case org.w3c.dom.Node.DOCUMENT_FRAGMENT_NODE:
    case org.w3c.dom.Node.DOCUMENT_NODE:
    case org.w3c.dom.Node.ENTITY_NODE:
    case org.w3c.dom.Node.ENTITY_REFERENCE_NODE:
    case org.w3c.dom.Node.NOTATION_NODE:
    case org.w3c.dom.Node.PROCESSING_INSTRUCTION_NODE:
    default:
        throw new IllegalArgumentException("Unsupported node type: " + node.getNodeType());
    }
}

From source file:org.ajax4jsf.webapp.tidy.TidyParser.java

public Document parseHtmlByTidy(Object input, Writer output) throws IOException {
    Document document = tidy.parseDOM(input, null);
    if (null != document) {
        Element documentElement = document.getDocumentElement();
        if (null != documentElement) {
            NodeVisitor nodeVisitor = new NodeVisitor();
            nodeVisitor.traverse(documentElement);
            // Replace state elements with real stored.

            List<org.w3c.dom.Node> viewStateSpans = nodeVisitor.viewStateSpans;
            for (org.w3c.dom.Node node : viewStateSpans) {
                // State marker - replace with real.
                org.w3c.dom.Node parentNode = node.getParentNode();
                if (null != _viewState) {
                    parentNode.replaceChild(document.createCDATASection(_viewState), node);
                } else {
                    // Remove marker element, but keep it content.
                    if (node.hasChildNodes()) {
                        org.w3c.dom.Node nextSibling = node.getNextSibling();
                        NodeList childNodes = node.getChildNodes();
                        // Copy all nodes by temporary array ( since
                        // moving nodes in iteration
                        // modify NodeList with side effects.
                        org.w3c.dom.Node[] childArray = new org.w3c.dom.Node[childNodes.getLength()];
                        for (int j = 0; j < childArray.length; j++) {
                            childArray[j] = childNodes.item(j);
                        }//  ww w.ja va  2  s  .c om
                        for (int j = 0; j < childArray.length; j++) {
                            parentNode.insertBefore(childArray[j], nextSibling);
                        }
                    }
                    parentNode.removeChild(node);
                }
            }

            // Inserts scripts and styles to head.
            if ((null != headEvents && headEvents.length > 0) || null != _viewState) {
                // find head
                org.w3c.dom.Node head = nodeVisitor.head;
                // Insert empty if not found
                if (null == head) {
                    head = document.createElement("head");
                    documentElement.insertBefore(head, documentElement.getFirstChild());
                }
                org.w3c.dom.Node child = head.getFirstChild();
                while (child != null) {
                    if (child instanceof Element) {
                        String nodeName = ((Element) child).getNodeName();
                        if (!("title".equalsIgnoreCase(nodeName) || "base".equalsIgnoreCase(nodeName))) {
                            break;
                        }
                    }

                    child = child.getNextSibling();
                }

                if (headEvents != null) {
                    for (org.w3c.dom.Node node : headEvents) {
                        head.insertBefore(importNode(document, node, true), child);
                    }
                }
            }
        }

        if (null != output) {
            tidy.pprint(document, output);
        }
    }
    return document;
}

From source file:org.apache.ode.il.OMUtils.java

@SuppressWarnings("unchecked")
public static Element toDOM(OMElement element, Document doc, boolean deepNS) {
    ////from   ww w .j  a v  a2  s  . co  m
    //  Fix regarding lost qnames on response of invoke activity:
    //    * copy an element including its prefix.
    //    * add all namespase attributes.
    //
    String domElementNsUri = element.getQName().getNamespaceURI();
    String domElementQName;
    if (element.getQName().getPrefix() == null || element.getQName().getPrefix().trim().length() == 0) {
        domElementQName = element.getQName().getLocalPart();
    } else {
        domElementQName = element.getQName().getPrefix() + ":" + element.getQName().getLocalPart();
    }
    if (__log.isTraceEnabled())
        __log.trace("toDOM: creating element with nsUri=" + domElementNsUri + " qname=" + domElementQName
                + " from omElement, name=" + element.getLocalName());

    final Element domElement = doc.createElementNS(domElementNsUri, domElementQName);

    if (deepNS) {
        NSContext nscontext = new NSContext();
        buildNScontext(nscontext, element);
        DOMUtils.injectNamespacesWithAllPrefixes(domElement, nscontext);
    } else {
        if (element.getAllDeclaredNamespaces() != null) {
            for (Iterator<OMNamespace> i = element.getAllDeclaredNamespaces(); i.hasNext();) {
                OMNamespace omns = i.next();
                if (omns.getPrefix().equals(""))
                    domElement.setAttributeNS(DOMUtils.NS_URI_XMLNS, "xmlns",
                            omns.getNamespaceURI() == null ? "" : omns.getNamespaceURI());
                else
                    domElement.setAttributeNS(DOMUtils.NS_URI_XMLNS, "xmlns:" + omns.getPrefix(),
                            omns.getNamespaceURI());
            }

        }
    }
    if (__log.isTraceEnabled())
        __log.trace("toDOM: created root element (deepNS=" + deepNS + "): " + DOMUtils.domToString(domElement));

    for (Iterator i = element.getAllAttributes(); i.hasNext();) {
        final OMAttribute attr = (OMAttribute) i.next();
        Attr newAttr;
        if (attr.getNamespace() != null)
            newAttr = doc.createAttributeNS(attr.getNamespace().getNamespaceURI(), attr.getLocalName());
        else
            newAttr = doc.createAttributeNS(null, attr.getLocalName());

        newAttr.appendChild(doc.createTextNode(attr.getAttributeValue()));
        domElement.setAttributeNodeNS(newAttr);

        // Case of qualified attribute values, we're forced to add corresponding namespace declaration manually...
        int colonIdx = attr.getAttributeValue().indexOf(":");
        if (colonIdx > 0) {
            OMNamespace attrValNs = element.findNamespaceURI(attr.getAttributeValue().substring(0, colonIdx));
            if (attrValNs != null)
                domElement.setAttributeNS(DOMUtils.NS_URI_XMLNS, "xmlns:" + attrValNs.getPrefix(),
                        attrValNs.getNamespaceURI());
        }
    }

    for (Iterator<OMNode> i = element.getChildren(); i.hasNext();) {
        OMNode omn = i.next();

        switch (omn.getType()) {
        case OMNode.CDATA_SECTION_NODE:
            domElement.appendChild(doc.createCDATASection(((OMText) omn).getText()));
            break;
        case OMNode.TEXT_NODE:
            domElement.appendChild(doc.createTextNode(((OMText) omn).getText()));
            break;
        case OMNode.ELEMENT_NODE:
            domElement.appendChild(toDOM((OMElement) omn, doc, false));
            break;
        }

    }

    return domElement;

}

From source file:org.apache.ode.utils.DOMUtils.java

private static void parse(XMLStreamReader reader, Document doc, Node parent) throws XMLStreamException {
    int event = reader.getEventType();

    while (reader.hasNext()) {
        switch (event) {
        case XMLStreamConstants.START_ELEMENT:
            // create element
            Element e = doc.createElementNS(reader.getNamespaceURI(), reader.getLocalName());
            if (reader.getPrefix() != null && reader.getPrefix() != "") {
                e.setPrefix(reader.getPrefix());
            }//from   w w w  .j  a va 2  s.  c  om
            parent.appendChild(e);

            // copy namespaces
            for (int ns = 0; ns < reader.getNamespaceCount(); ns++) {
                String uri = reader.getNamespaceURI(ns);
                String prefix = reader.getNamespacePrefix(ns);
                declare(e, uri, prefix);
            }

            // copy attributes
            for (int att = 0; att < reader.getAttributeCount(); att++) {
                String name = reader.getAttributeLocalName(att);
                String prefix = reader.getAttributePrefix(att);
                if (prefix != null && prefix.length() > 0) {
                    name = prefix + ":" + name;
                }
                Attr attr = doc.createAttributeNS(reader.getAttributeNamespace(att), name);
                attr.setValue(reader.getAttributeValue(att));
                e.setAttributeNode(attr);
            }
            // sub-nodes
            if (reader.hasNext()) {
                reader.next();
                parse(reader, doc, e);
            }
            if (parent instanceof Document) {
                while (reader.hasNext())
                    reader.next();
                return;
            }
            break;
        case XMLStreamConstants.END_ELEMENT:
            return;
        case XMLStreamConstants.CHARACTERS:
            if (parent != null) {
                parent.appendChild(doc.createTextNode(reader.getText()));
            }
            break;
        case XMLStreamConstants.COMMENT:
            if (parent != null) {
                parent.appendChild(doc.createComment(reader.getText()));
            }
            break;
        case XMLStreamConstants.CDATA:
            parent.appendChild(doc.createCDATASection(reader.getText()));
            break;
        case XMLStreamConstants.PROCESSING_INSTRUCTION:
            parent.appendChild(doc.createProcessingInstruction(reader.getPITarget(), reader.getPIData()));
            break;
        case XMLStreamConstants.ENTITY_REFERENCE:
            parent.appendChild(doc.createProcessingInstruction(reader.getPITarget(), reader.getPIData()));
            break;
        case XMLStreamConstants.NAMESPACE:
        case XMLStreamConstants.ATTRIBUTE:
            break;
        default:
            break;
        }

        if (reader.hasNext()) {
            event = reader.next();
        }
    }
}

From source file:org.apache.ode.utils.DOMUtils.java

/**
 * Deep clone, but don't fry, the given node in the context of the given document.
 * For all intents and purposes, the clone is the exact same copy of the node,
 * except that it might have a different owner document.
 *
 * This method is fool-proof, unlike the <code>adoptNode</code> or <code>adoptNode</code> methods,
 * in that it doesn't assume that the given node has a parent or a owner document.
 *
 * @param document/*from  w  w  w . j a  va  2s .  c o m*/
 * @param sourceNode
 * @return a clone of node
 */
public static Node cloneNode(Document document, Node sourceNode) {
    Node clonedNode = null;

    // what is my name?
    QName sourceQName = getNodeQName(sourceNode);
    String nodeName = sourceQName.getLocalPart();
    String namespaceURI = sourceQName.getNamespaceURI();

    // if the node is unqualified, don't assume that it inherits the WS-BPEL target namespace
    if (Namespaces.WSBPEL2_0_FINAL_EXEC.equals(namespaceURI)) {
        namespaceURI = null;
    }

    switch (sourceNode.getNodeType()) {
    case Node.ATTRIBUTE_NODE:
        if (namespaceURI == null) {
            clonedNode = document.createAttribute(nodeName);
        } else {
            String prefix = ((Attr) sourceNode).lookupPrefix(namespaceURI);
            // the prefix for the XML namespace can't be looked up, hence this...
            if (prefix == null && namespaceURI.equals(NS_URI_XMLNS)) {
                prefix = "xmlns";
            }
            // if a prefix exists, qualify the name with it
            if (prefix != null && !"".equals(prefix)) {
                nodeName = prefix + ":" + nodeName;
            }
            // create the appropriate type of attribute
            if (prefix != null) {
                clonedNode = document.createAttributeNS(namespaceURI, nodeName);
            } else {
                clonedNode = document.createAttribute(nodeName);
            }
        }
        break;
    case Node.CDATA_SECTION_NODE:
        clonedNode = document.createCDATASection(((CDATASection) sourceNode).getData());
        break;
    case Node.COMMENT_NODE:
        clonedNode = document.createComment(((Comment) sourceNode).getData());
        break;
    case Node.DOCUMENT_FRAGMENT_NODE:
        clonedNode = document.createDocumentFragment();
        break;
    case Node.DOCUMENT_NODE:
        clonedNode = document;
        break;
    case Node.ELEMENT_NODE:
        // create the appropriate type of element
        if (namespaceURI == null) {
            clonedNode = document.createElement(nodeName);
        } else {
            String prefix = namespaceURI.equals(Namespaces.XMLNS_URI) ? "xmlns"
                    : ((Element) sourceNode).lookupPrefix(namespaceURI);
            if (prefix != null && !"".equals(prefix)) {
                nodeName = prefix + ":" + nodeName;
                clonedNode = document.createElementNS(namespaceURI, nodeName);
            } else {
                clonedNode = document.createElement(nodeName);
            }
        }
        // attributes are not treated as child nodes, so copy them explicitly
        NamedNodeMap attributes = ((Element) sourceNode).getAttributes();
        for (int i = 0; i < attributes.getLength(); i++) {
            Attr attributeClone = (Attr) cloneNode(document, attributes.item(i));
            if (attributeClone.getNamespaceURI() == null) {
                ((Element) clonedNode).setAttributeNode(attributeClone);
            } else {
                ((Element) clonedNode).setAttributeNodeNS(attributeClone);
            }
        }
        break;
    case Node.ENTITY_NODE:
        // TODO
        break;
    case Node.ENTITY_REFERENCE_NODE:
        clonedNode = document.createEntityReference(nodeName);
        // TODO
        break;
    case Node.NOTATION_NODE:
        // TODO
        break;
    case Node.PROCESSING_INSTRUCTION_NODE:
        clonedNode = document.createProcessingInstruction(((ProcessingInstruction) sourceNode).getData(),
                nodeName);
        break;
    case Node.TEXT_NODE:
        clonedNode = document.createTextNode(((Text) sourceNode).getData());
        break;
    default:
        break;
    }

    // clone children of element and attribute nodes
    NodeList sourceChildren = sourceNode.getChildNodes();
    if (sourceChildren != null) {
        for (int i = 0; i < sourceChildren.getLength(); i++) {
            Node sourceChild = sourceChildren.item(i);
            Node clonedChild = cloneNode(document, sourceChild);
            clonedNode.appendChild(clonedChild);
            // if the child has a textual value, parse it for any embedded prefixes
            if (clonedChild.getNodeType() == Node.TEXT_NODE
                    || clonedChild.getNodeType() == Node.CDATA_SECTION_NODE) {
                parseEmbeddedPrefixes(sourceNode, clonedNode, clonedChild);
            }
        }
    }
    return clonedNode;
}

From source file:org.chiba.xml.xforms.constraints.RelevanceSelector.java

private static void addChildren(Element relevantElement, NodeImpl instanceNode) {
    Document ownerDocument = relevantElement.getOwnerDocument();
    NodeList instanceChildren = instanceNode.getChildNodes();

    for (int index = 0; index < instanceChildren.getLength(); index++) {
        NodeImpl instanceChild = (NodeImpl) instanceChildren.item(index);

        if (isEnabled(instanceChild)) {
            switch (instanceChild.getNodeType()) {
            case Node.TEXT_NODE:
                /* rather not, otherwise we cannot follow specs when
                 * serializing to multipart/form-data for example
                 *//from  w w  w .j  av  a  2s . co m
                // denormalize text for better whitespace handling during serialization
                List list = DOMWhitespace.denormalizeText(instanceChild.getNodeValue());
                for (int item = 0; item < list.size(); item++) {
                    relevantElement.appendChild(ownerDocument.createTextNode(list.get(item).toString()));
                }
                */
                relevantElement.appendChild(ownerDocument.createTextNode(instanceChild.getNodeValue()));
                break;
            case Node.CDATA_SECTION_NODE:
                relevantElement.appendChild(ownerDocument.createCDATASection(instanceChild.getNodeValue()));
                break;
            case Node.ELEMENT_NODE:
                addElement(relevantElement, instanceChild);
                break;
            default:
                // ignore
                break;
            }
        }
    }
}

From source file:org.company.processmaker.TreeFilesTopComponent.java

public TreeFilesTopComponent() {
    initComponents();/*  w w w . j  a  v a  2 s. c o  m*/

    setName(Bundle.CTL_TreeFilesTopComponent());
    setToolTipText(Bundle.HINT_TreeFilesTopComponent());
    // new codes
    instance = this;

    MouseListener ml = new MouseAdapter() {
        public void mousePressed(MouseEvent e) {
            int selRow = jTree1.getRowForLocation(e.getX(), e.getY());
            TreePath selPath = jTree1.getPathForLocation(e.getX(), e.getY());

            if (selRow != -1) {
                if (e.getClickCount() == 1) {
                    //mySingleClick(selRow, selPath);
                } else if (e.getClickCount() == 2) {

                    DefaultMutableTreeNode node = (DefaultMutableTreeNode) jTree1
                            .getLastSelectedPathComponent();
                    if (node == null) {
                        return;
                    }
                    Object nodeInfo = node.getUserObject();
                    int node_level = node.getLevel();

                    if (node_level < 2) {
                        return;
                    }

                    // for each dyna form
                    if (node_level == 2) {

                        Global gl_obj = Global.getInstance();

                        //myDoubleClick(selRow, selPath);
                        conf = Config.getInstance();

                        DefaultMutableTreeNode parent = (DefaultMutableTreeNode) node.getParent();
                        String parentName = (String) parent.getUserObject();

                        // handle triggers
                        if (parentName.equals("Triggers")) {

                            String filePath = "";
                            for (String[] s : res_trigger) {

                                if (s[0].equals(nodeInfo.toString())) {
                                    // get path of dyna in xml forms
                                    filePath = conf.tmp + "triggers/" + s[3] + "/" + s[2] + ".php";
                                    break;
                                }

                            }

                            File toAdd = new File(filePath);

                            try {
                                DataObject dObject = DataObject.find(FileUtil.toFileObject(toAdd));

                                dObject.getLookup().lookup(OpenCookie.class).open();
                                // dont listen for exist listen files
                                if (existFile(filePath)) {
                                    return;
                                }
                                dObject.addPropertyChangeListener(new PropertyChangeListener() {
                                    @Override
                                    public void propertyChange(PropertyChangeEvent evt) {
                                        if (DataObject.PROP_MODIFIED.equals(evt.getPropertyName())) {
                                            //fire a dummy event
                                            if (!Boolean.TRUE.equals(evt.getNewValue())) {

                                                /*String msg = "Saved to" + evt.toString();
                                                NotifyDescriptor nd = new NotifyDescriptor.Message(msg, NotifyDescriptor.INFORMATION_MESSAGE);
                                                DialogDisplayer.getDefault().notify(nd);*/
                                                TopComponent activeTC = TopComponent.getRegistry()
                                                        .getActivated();
                                                DataObject dataLookup = activeTC.getLookup()
                                                        .lookup(DataObject.class);
                                                String filePath = FileUtil.toFile(dataLookup.getPrimaryFile())
                                                        .getAbsolutePath();

                                                File userFile = new File(filePath);
                                                String fileName = userFile.getName();
                                                fileName = fileName.substring(0, fileName.lastIndexOf("."));

                                                try {
                                                    String content = new String(
                                                            Files.readAllBytes(Paths.get(filePath)));
                                                    // remote php tag and info "<?php //don't remove this tag! \n"
                                                    content = content.substring(6, content.length());

                                                    String query = "update triggers set TRI_WEBBOT = '"
                                                            + StringEscapeUtils.escapeSql(content)
                                                            + "' where TRI_UID = '" + fileName + "'";
                                                    GooglePanel.updateQuery(query);

                                                } catch (Exception e) {
                                                    //Exceptions.printStackTrace(e);
                                                    String msg = "Can not update trigger";
                                                    NotifyDescriptor nd = new NotifyDescriptor.Message(msg,
                                                            NotifyDescriptor.INFORMATION_MESSAGE);
                                                    DialogDisplayer.getDefault().notify(nd);
                                                }

                                            }

                                        }

                                    }
                                });

                            } catch (DataObjectNotFoundException ex) {
                                //Exceptions.printStackTrace(ex);
                                String msg = "Trigger not found";
                                NotifyDescriptor nd = new NotifyDescriptor.Message(msg,
                                        NotifyDescriptor.INFORMATION_MESSAGE);
                                DialogDisplayer.getDefault().notify(nd);
                            }

                            return;
                        }

                        List<String[]> res_dyna = gl_obj.getDyna();
                        String FileDir = "";
                        for (String[] s : res_dyna) {

                            if (s[1].equals(nodeInfo.toString())) {
                                // get path of dyna in xml forms
                                FileDir = s[3];
                                break;
                            }

                        }

                        //String msg = "selRow" + nodeInfo.toString() + "|" + conf.getXmlForms() + FileDir;
                        String filePath = conf.getXmlForms() + FileDir + ".xml";
                        if (conf.isRemote()) {
                            String[] res = FileDir.split("/");
                            filePath = conf.get("local_tmp_for_remote") + "/" + FileDir + "/" + res[1] + ".xml";
                        }

                        File toAdd = new File(filePath);

                        //Result will be null if the user clicked cancel or closed the dialog w/o OK
                        if (toAdd != null) {
                            try {
                                DataObject dObject = DataObject.find(FileUtil.toFileObject(toAdd));

                                dObject.getLookup().lookup(OpenCookie.class).open();
                                // dont listen for exist listen files
                                if (existFile(filePath)) {
                                    return;
                                }
                                dObject.addPropertyChangeListener(new PropertyChangeListener() {
                                    @Override
                                    public void propertyChange(PropertyChangeEvent evt) {
                                        if (DataObject.PROP_MODIFIED.equals(evt.getPropertyName())) {
                                            //fire a dummy event
                                            if (!Boolean.TRUE.equals(evt.getNewValue())) {

                                                /*String msg = "Saved to" + evt.toString();
                                                NotifyDescriptor nd = new NotifyDescriptor.Message(msg, NotifyDescriptor.INFORMATION_MESSAGE);
                                                DialogDisplayer.getDefault().notify(nd);*/
                                                TopComponent activeTC = TopComponent.getRegistry()
                                                        .getActivated();
                                                DataObject dataLookup = activeTC.getLookup()
                                                        .lookup(DataObject.class);
                                                String filePath = FileUtil.toFile(dataLookup.getPrimaryFile())
                                                        .getAbsolutePath();

                                                File userFile = new File(filePath);
                                                String fileName = userFile.getName();
                                                fileName = fileName.substring(0, fileName.lastIndexOf("."));

                                                Global gl_obj = Global.getInstance();

                                                List<String[]> res_dyna = gl_obj.getDyna();
                                                String FileDir = "";
                                                for (String[] s : res_dyna) {

                                                    if (filePath.contains(s[0])) {

                                                        FileDir = s[3];
                                                        break;

                                                    }

                                                }

                                                if (conf.isRemote()) {
                                                    boolean res_Upload = SSH.getInstance().uplaodFile(FileDir);
                                                    if (res_Upload) {
                                                        String msg = "file upload Successfully!";
                                                        NotifyDescriptor nd = new NotifyDescriptor.Message(msg,
                                                                NotifyDescriptor.INFORMATION_MESSAGE);
                                                        DialogDisplayer.getDefault().notify(nd);
                                                    } else {
                                                        String msg = "error in uploading file!";
                                                        NotifyDescriptor nd = new NotifyDescriptor.Message(msg,
                                                                NotifyDescriptor.INFORMATION_MESSAGE);
                                                        DialogDisplayer.getDefault().notify(nd);
                                                    }
                                                }

                                            }

                                        }

                                    }
                                });

                            } catch (DataObjectNotFoundException ex) {
                                //Exceptions.printStackTrace(ex);
                                String msg = "Can not find xml file";
                                NotifyDescriptor nd = new NotifyDescriptor.Message(msg,
                                        NotifyDescriptor.INFORMATION_MESSAGE);
                                DialogDisplayer.getDefault().notify(nd);
                            }
                        }
                    }

                    // for each js file
                    if (node_level == 3) {

                        TreeNode parentInfo = node.getParent();

                        Global gl_obj = Global.getInstance();

                        List<String[]> res_dyna = gl_obj.getDyna();
                        String FileDir = "";
                        for (String[] s : res_dyna) {

                            if (s[1].equals(parentInfo.toString())) {
                                // get path of dyna in xml forms
                                FileDir = s[3];
                                break;
                            }

                        }

                        //myDoubleClick(selRow, selPath);
                        conf = Config.getInstance();
                        String filePath = conf.tmp + "xmlForms/" + FileDir + "/" + nodeInfo.toString() + ".js";
                        if (conf.isRemote()) {
                            filePath = conf.get("local_tmp_for_remote") + FileDir + "/" + nodeInfo.toString()
                                    + ".js";
                        }

                        File toAdd = new File(filePath);

                        //Result will be null if the user clicked cancel or closed the dialog w/o OK
                        if (toAdd != null) {
                            try {
                                DataObject dObject = DataObject.find(FileUtil.toFileObject(toAdd));

                                dObject.getLookup().lookup(OpenCookie.class).open();
                                // dont listen for exist listen files
                                if (existFile(filePath)) {
                                    return;
                                }
                                dObject.addPropertyChangeListener(new PropertyChangeListener() {
                                    @Override
                                    public void propertyChange(PropertyChangeEvent evt) {
                                        if (DataObject.PROP_MODIFIED.equals(evt.getPropertyName())) {
                                            //fire a dummy event
                                            if (!Boolean.TRUE.equals(evt.getNewValue())) {

                                                JTextComponent ed = EditorRegistry.lastFocusedComponent();
                                                String jsDoc = "";
                                                try {
                                                    jsDoc = ed.getText();
                                                } catch (Exception ex) {
                                                    //Exceptions.printStackTrace(ex);
                                                    String msg = "Can not get text from editor";
                                                    NotifyDescriptor nd = new NotifyDescriptor.Message(msg,
                                                            NotifyDescriptor.INFORMATION_MESSAGE);
                                                    DialogDisplayer.getDefault().notify(nd);
                                                }

                                                TopComponent activeTC = TopComponent.getRegistry()
                                                        .getActivated();
                                                DataObject dataLookup = activeTC.getLookup()
                                                        .lookup(DataObject.class);
                                                String filePath = FileUtil.toFile(dataLookup.getPrimaryFile())
                                                        .getAbsolutePath();

                                                File userFile = new File(filePath);
                                                String fileName = userFile.getName();
                                                fileName = fileName.substring(0, fileName.lastIndexOf("."));

                                                Global gl_obj = Global.getInstance();

                                                List<String[]> res_dyna = gl_obj.getDyna();
                                                String FileDir = "";
                                                for (String[] s : res_dyna) {

                                                    if (filePath.contains(s[0])) {

                                                        FileDir = s[3];
                                                        break;

                                                    }

                                                }

                                                String fullPath = conf.getXmlForms() + FileDir + ".xml";
                                                if (conf.isRemote()) {
                                                    String[] res = FileDir.split("/");
                                                    fullPath = conf.get("local_tmp_for_remote") + FileDir + "/"
                                                            + res[1] + ".xml";
                                                }
                                                try {
                                                    DocumentBuilderFactory factory = DocumentBuilderFactory
                                                            .newInstance();
                                                    DocumentBuilder builder = factory.newDocumentBuilder();
                                                    Document mainDoc = builder.parse(fullPath);

                                                    XPath xPath = XPathFactory.newInstance().newXPath();
                                                    Node startDateNode = (Node) xPath
                                                            .compile("//dynaForm/" + fileName)
                                                            .evaluate(mainDoc, XPathConstants.NODE);
                                                    Node cdata = mainDoc.createCDATASection(jsDoc);
                                                    startDateNode.setTextContent("");
                                                    startDateNode.appendChild(cdata);

                                                    /*String msg = evt.getPropertyName() + "-" + fileName;
                                                    NotifyDescriptor nd = new NotifyDescriptor.Message(msg, NotifyDescriptor.INFORMATION_MESSAGE);
                                                    DialogDisplayer.getDefault().notify(nd);*/
                                                    // write the content into xml file
                                                    TransformerFactory transformerFactory = TransformerFactory
                                                            .newInstance();
                                                    Transformer transformer = transformerFactory
                                                            .newTransformer();
                                                    DOMSource source = new DOMSource(mainDoc);
                                                    StreamResult result = new StreamResult(new File(fullPath));
                                                    transformer.transform(source, result);

                                                    if (conf.isRemote()) {
                                                        boolean res_Upload = SSH.getInstance()
                                                                .uplaodFile(FileDir);
                                                        if (res_Upload) {
                                                            String msg = "file upload Successfully!";
                                                            NotifyDescriptor nd = new NotifyDescriptor.Message(
                                                                    msg, NotifyDescriptor.INFORMATION_MESSAGE);
                                                            DialogDisplayer.getDefault().notify(nd);
                                                        } else {
                                                            String msg = "error in uploading file!";
                                                            NotifyDescriptor nd = new NotifyDescriptor.Message(
                                                                    msg, NotifyDescriptor.INFORMATION_MESSAGE);
                                                            DialogDisplayer.getDefault().notify(nd);
                                                        }
                                                    }

                                                } catch (Exception ex) {
                                                    //Exceptions.printStackTrace(ex);
                                                    String msg = "Can not save to xml form";
                                                    NotifyDescriptor nd = new NotifyDescriptor.Message(msg,
                                                            NotifyDescriptor.INFORMATION_MESSAGE);
                                                    DialogDisplayer.getDefault().notify(nd);
                                                }

                                            }

                                        }

                                    }
                                });

                            } catch (DataObjectNotFoundException ex) {
                                //Exceptions.printStackTrace(ex);
                                String msg = "Can not save to xml form";
                                NotifyDescriptor nd = new NotifyDescriptor.Message(msg,
                                        NotifyDescriptor.INFORMATION_MESSAGE);
                                DialogDisplayer.getDefault().notify(nd);
                            }
                        }
                    }
                }
            }
        }
    };
    jTree1.addMouseListener(ml);
    jTree1.setModel(null);
}

From source file:org.devgateway.eudevfin.reports.core.utils.ReportTemplate.java

private void appendReportSumRows(HashMap<String, Node> matchingRows, HashMap<String, Node> matchingColumns,
        RowReport row, Document doc, boolean swapAxis) {
    Node rowNode = matchingRows.get("r_" + row.getName());

    if (rowNode == null)
        return;//from w  ww.  j a  va 2  s .  c  om
    HashMap<String, String> columns = new HashMap<String, String>();
    HashMap<String, String> emptyColumns = new HashMap<String, String>();

    XPath xPath = XPathFactory.newInstance().newXPath();

    for (String rowCode : row.getRowCodes()) {
        try {
            NodeList nodes = (NodeList) xPath
                    .evaluate("/jasperReport/detail/band/textField/reportElement[starts-with(@key, 'r_"
                            + rowCode + "_c_')]", doc.getDocumentElement(), XPathConstants.NODESET);
            for (int i = 0; i < nodes.getLength(); ++i) {
                Element e = (Element) nodes.item(i);
                String columnKey = e.getAttribute("key");
                String columnCode = columnKey.replaceFirst("r_" + rowCode + "_c_", "");
                String expression = columns.get(columnCode) != null ? columns.get(columnCode) : "";
                if (!e.getParentNode().getTextContent().equals("")) {
                    expression += e.getParentNode().getTextContent();
                    expression += "+";
                }
                columns.put(columnCode, expression);
            }
            NodeList nodesEmpty = (NodeList) xPath
                    .evaluate("/jasperReport/detail/band/staticText/reportElement[starts-with(@key, 'r_"
                            + rowCode + "_c_')]", doc.getDocumentElement(), XPathConstants.NODESET);
            for (int i = 0; i < nodesEmpty.getLength(); ++i) {
                Element e = (Element) nodesEmpty.item(i);
                String columnKey = e.getAttribute("key");
                String columnCode = columnKey.replaceFirst("r_" + rowCode + "_c_", "");
                String expression = columns.get(columnCode) != null ? columns.get(columnCode) : "";
                if (!e.getParentNode().getTextContent().equals("")) {
                    expression += e.getParentNode().getTextContent();
                    expression += "+";
                }
                emptyColumns.put(columnCode, expression);
            }
        } catch (XPathExpressionException e) {
            e.printStackTrace();
        }
    }

    Integer yCoord, xCoord, width, height;
    xCoord = yCoord = 0;
    //Set default height
    height = 15;
    //Set default width
    width = 55;
    if (swapAxis) {
        xCoord = rowNode.getAttributes().getNamedItem("x") != null
                ? Integer.parseInt(rowNode.getAttributes().getNamedItem("x").getNodeValue())
                : 0;
    } else {
        yCoord = rowNode.getAttributes().getNamedItem("y") != null
                ? Integer.parseInt(rowNode.getAttributes().getNamedItem("y").getNodeValue())
                : 0;
    }

    for (Map.Entry<String, String> column : columns.entrySet()) {
        String cellStyle = (rowNode.getAttributes().getNamedItem("style") != null)
                ? rowNode.getAttributes().getNamedItem("style").getNodeValue()
                : "";
        Element textField = doc.createElement("textField");
        textField.setAttribute("pattern", "#,##0.00");
        Node columnNode = matchingColumns.get("c_" + column.getKey());
        if (columnNode == null)
            continue;
        Node parentNode;
        if (swapAxis) {
            parentNode = columnNode.getParentNode().getParentNode();
            yCoord = columnNode.getAttributes().getNamedItem("y") != null
                    ? Integer.parseInt(columnNode.getAttributes().getNamedItem("y").getNodeValue())
                    : 0;
        } else {
            parentNode = rowNode.getParentNode().getParentNode();
            xCoord = columnNode.getAttributes().getNamedItem("x") != null
                    ? Integer.parseInt(columnNode.getAttributes().getNamedItem("x").getNodeValue())
                    : 0;
            width = columnNode.getAttributes().getNamedItem("width") != null
                    ? Integer.parseInt(columnNode.getAttributes().getNamedItem("width").getNodeValue())
                    : 0;
            height = rowNode.getAttributes().getNamedItem("height") != null
                    ? Integer.parseInt(rowNode.getAttributes().getNamedItem("height").getNodeValue())
                    : 0;
            if (cellStyle.equals("") && (columnNode.getAttributes().getNamedItem("style") != null)) {
                cellStyle = columnNode.getAttributes().getNamedItem("style").getNodeValue();
            }

        }
        Element reportElement = doc.createElement("reportElement");
        reportElement.setAttribute("key", "r_" + row.getName() + "_c_" + column.getKey());
        reportElement.setAttribute("x", xCoord.toString());
        reportElement.setAttribute("y", yCoord.toString());
        reportElement.setAttribute("width", width.toString());
        reportElement.setAttribute("height", height.toString());

        if (!cellStyle.equals("")) {
            reportElement.setAttribute("style", cellStyle);
        }

        Element textElement = doc.createElement("textElement");
        textElement.setAttribute("textAlignment", "Right");

        Element textFieldExpression = doc.createElement("textFieldExpression");
        String columnValue = column.getValue();
        if (columnValue.endsWith("+")) {
            columnValue = columnValue.substring(0, columnValue.length() - 1);
        }
        CDATASection cdata = doc.createCDATASection(columnValue);

        textFieldExpression.appendChild(cdata);
        textField.appendChild(reportElement);
        textField.appendChild(textElement);
        textField.appendChild(textFieldExpression);
        parentNode.appendChild(textField);

    }

    for (Map.Entry<String, String> column : emptyColumns.entrySet()) {
        if (columns.containsKey(column.getKey())) {
            continue;
        }
        String cellStyle = (rowNode.getAttributes().getNamedItem("style") != null)
                ? rowNode.getAttributes().getNamedItem("style").getNodeValue()
                : "";
        Element staticText = doc.createElement("staticText");
        Node columnNode = matchingColumns.get("c_" + column.getKey());
        if (columnNode == null)
            continue;
        Node parentNode;
        if (swapAxis) {
            parentNode = columnNode.getParentNode().getParentNode();
            yCoord = columnNode.getAttributes().getNamedItem("y") != null
                    ? Integer.parseInt(columnNode.getAttributes().getNamedItem("y").getNodeValue())
                    : 0;
        } else {
            parentNode = rowNode.getParentNode().getParentNode();
            xCoord = columnNode.getAttributes().getNamedItem("x") != null
                    ? Integer.parseInt(columnNode.getAttributes().getNamedItem("x").getNodeValue())
                    : 0;
            width = columnNode.getAttributes().getNamedItem("width") != null
                    ? Integer.parseInt(columnNode.getAttributes().getNamedItem("width").getNodeValue())
                    : 0;
            height = rowNode.getAttributes().getNamedItem("height") != null
                    ? Integer.parseInt(rowNode.getAttributes().getNamedItem("height").getNodeValue())
                    : 0;
            if (cellStyle.equals("") && (columnNode.getAttributes().getNamedItem("style") != null)) {
                cellStyle = columnNode.getAttributes().getNamedItem("style").getNodeValue();
            }

        }
        Element reportElement = doc.createElement("reportElement");
        reportElement.setAttribute("key", "r_" + row.getName() + "_c_" + column.getKey());
        reportElement.setAttribute("x", xCoord.toString());
        reportElement.setAttribute("y", yCoord.toString());
        reportElement.setAttribute("width", width.toString());
        reportElement.setAttribute("height", height.toString());

        if (!cellStyle.equals("")) {
            reportElement.setAttribute("style", cellStyle);
        }

        Element textElement = doc.createElement("textElement");
        textElement.setAttribute("textAlignment", "Right");

        Element textFieldExpression = doc.createElement("text");
        CDATASection cdata = doc.createCDATASection("////////");

        textFieldExpression.appendChild(cdata);
        staticText.appendChild(reportElement);
        staticText.appendChild(textElement);
        staticText.appendChild(textFieldExpression);
        parentNode.appendChild(staticText);

    }
}