Example usage for org.w3c.dom Document createTextNode

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

Introduction

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

Prototype

public Text createTextNode(String data);

Source Link

Document

Creates a Text node given the specified string.

Usage

From source file:com.occamlab.te.web.TestServlet.java

public void processFormData(HttpServletRequest request, HttpServletResponse response) throws ServletException {
    try {/*from  w w  w  . ja  v  a2 s .c  o m*/
        FileItemFactory ffactory;
        ServletFileUpload upload;
        List /* FileItem */ items = null;
        HashMap<String, String> params = new HashMap<String, String>();
        boolean multipart = ServletFileUpload.isMultipartContent(request);
        if (multipart) {
            ffactory = new DiskFileItemFactory();
            upload = new ServletFileUpload(ffactory);
            items = upload.parseRequest(request);
            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (item.isFormField()) {
                    params.put(item.getFieldName(), item.getString());
                }
            }
        } else {
            Enumeration paramNames = request.getParameterNames();
            while (paramNames.hasMoreElements()) {
                String name = (String) paramNames.nextElement();
                params.put(name, request.getParameter(name));
            }
        }
        HttpSession session = request.getSession();
        ServletOutputStream out = response.getOutputStream();
        String operation = params.get("te-operation");
        if (operation.equals("Test")) {
            TestSession s = new TestSession();
            String user = request.getRemoteUser();
            File logdir = new File(conf.getUsersDir(), user);
            String mode = params.get("mode");
            RuntimeOptions opts = new RuntimeOptions();
            opts.setWorkDir(conf.getWorkDir());
            opts.setLogDir(logdir);
            if (mode.equals("retest")) {
                opts.setMode(Test.RETEST_MODE);
                String sessionid = params.get("session");
                String test = params.get("test");
                if (sessionid == null) {
                    int i = test.indexOf("/");
                    sessionid = i > 0 ? test.substring(0, i) : test;
                }
                opts.setSessionId(sessionid);
                if (test == null) {
                    opts.addTestPath(sessionid);
                } else {
                    opts.addTestPath(test);
                }
                for (Entry<String, String> entry : params.entrySet()) {
                    if (entry.getKey().startsWith("profile_")) {
                        String profileId = entry.getValue();
                        int i = profileId.indexOf("}");
                        opts.addTestPath(sessionid + "/" + profileId.substring(i + 1));
                    }
                }
                s.load(logdir, sessionid);
                opts.setSourcesName(s.getSourcesName());
            } else if (mode.equals("resume")) {
                opts.setMode(Test.RESUME_MODE);
                String sessionid = params.get("session");
                opts.setSessionId(sessionid);
                s.load(logdir, sessionid);
                opts.setSourcesName(s.getSourcesName());
            } else {
                opts.setMode(Test.TEST_MODE);
                String sessionid = LogUtils.generateSessionId(logdir);
                s.setSessionId(sessionid);
                String sources = params.get("sources");
                s.setSourcesName(sources);
                SuiteEntry suite = conf.getSuites().get(sources);
                s.setSuiteName(suite.getId());
                //                    String suite = params.get("suite");
                //                    s.setSuiteName(suite);
                String description = params.get("description");
                s.setDescription(description);
                opts.setSessionId(sessionid);
                opts.setSourcesName(sources);
                opts.setSuiteName(suite.getId());
                ArrayList<String> profiles = new ArrayList<String>();
                for (Entry<String, String> entry : params.entrySet()) {
                    if (entry.getKey().startsWith("profile_")) {
                        profiles.add(entry.getValue());
                        opts.addProfile(entry.getValue());
                    }
                }
                s.setProfiles(profiles);
                s.save(logdir);
            }
            String webdir = conf.getWebDirs().get(s.getSourcesName());
            //                String requestURI = request.getRequestURI();
            //                String contextPath = requestURI.substring(0, requestURI.indexOf(request.getServletPath()) + 1);
            //                URI contextURI = new URI(request.getScheme(), null, request.getServerName(), request.getServerPort(), contextPath, null, null);
            URI contextURI = new URI(request.getScheme(), null, request.getServerName(),
                    request.getServerPort(), request.getRequestURI(), null, null);
            opts.setBaseURI(new URL(contextURI.toURL(), webdir + "/").toString());
            //                URI baseURI = new URL(contextURI.toURL(), webdir).toURI();
            //                String base = baseURI.toString() + URLEncoder.encode(webdir, "UTF-8") + "/";
            //                opts.setBaseURI(base);
            //System.out.println(opts.getSourcesName());
            TECore core = new TECore(engine, indexes.get(opts.getSourcesName()), opts);
            //System.out.println(indexes.get(opts.getSourcesName()).toString());
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            PrintStream ps = new PrintStream(baos);
            core.setOut(ps);
            core.setWeb(true);
            Thread thread = new Thread(core);
            session.setAttribute("testsession", core);
            thread.start();
            response.setContentType("text/xml");
            out.println("<thread id=\"" + thread.getId() + "\" sessionId=\"" + s.getSessionId() + "\"/>");
        } else if (operation.equals("Stop")) {
            response.setContentType("text/xml");
            TECore core = (TECore) session.getAttribute("testsession");
            if (core != null) {
                core.stopThread();
                session.removeAttribute("testsession");
                out.println("<stopped/>");
            } else {
                out.println("<message>Could not retrieve core object</message>");
            }
        } else if (operation.equals("GetStatus")) {
            TECore core = (TECore) session.getAttribute("testsession");
            response.setContentType("text/xml");
            out.print("<status");
            if (core.getFormHtml() != null) {
                out.print(" form=\"true\"");
            }
            if (core.isThreadComplete()) {
                out.print(" complete=\"true\"");
                session.removeAttribute("testsession");
            }
            out.println(">");
            out.print("<![CDATA[");
            //                out.print(core.getOutput());
            out.print(URLEncoder.encode(core.getOutput(), "UTF-8").replace('+', ' '));
            out.println("]]>");
            out.println("</status>");
        } else if (operation.equals("GetForm")) {
            TECore core = (TECore) session.getAttribute("testsession");
            String html = core.getFormHtml();
            core.setFormHtml(null);
            response.setContentType("text/html");
            out.print(html);
        } else if (operation.equals("SubmitForm")) {
            TECore core = (TECore) session.getAttribute("testsession");
            Document doc = DB.newDocument();
            Element root = doc.createElement("values");
            doc.appendChild(root);
            for (String key : params.keySet()) {
                if (!key.startsWith("te-")) {
                    Element valueElement = doc.createElement("value");
                    valueElement.setAttribute("key", key);
                    valueElement.appendChild(doc.createTextNode(params.get(key)));
                    root.appendChild(valueElement);
                }
            }
            if (multipart) {
                Iterator iter = items.iterator();
                while (iter.hasNext()) {
                    FileItem item = (FileItem) iter.next();
                    if (!item.isFormField() && !item.getName().equals("")) {
                        File uploadedFile = new File(core.getLogDir(),
                                StringUtils.getFilenameFromString(item.getName()));
                        item.write(uploadedFile);
                        Element valueElement = doc.createElement("value");
                        String key = item.getFieldName();
                        valueElement.setAttribute("key", key);
                        if (core.getFormParsers().containsKey(key)) {
                            Element parser = core.getFormParsers().get(key);
                            URL url = uploadedFile.toURI().toURL();
                            Element resp = core.parse(url.openConnection(), parser, doc);
                            Element content = DomUtils.getElementByTagName(resp, "content");
                            if (content != null) {
                                Element child = DomUtils.getChildElement(content);
                                if (child != null) {
                                    valueElement.appendChild(child);
                                }
                            }
                        } else {
                            Element fileEntry = doc.createElementNS(CTL_NS, "file-entry");
                            fileEntry.setAttribute("full-path",
                                    uploadedFile.getAbsolutePath().replace('\\', '/'));
                            fileEntry.setAttribute("media-type", item.getContentType());
                            fileEntry.setAttribute("size", String.valueOf(item.getSize()));
                            valueElement.appendChild(fileEntry);
                        }
                        root.appendChild(valueElement);
                    }
                }
            }
            core.setFormResults(doc);
            response.setContentType("text/html");
            out.println("<html>");
            out.println("<head><title>Form Submitted</title></head>");
            out.print("<body onload=\"window.parent.update()\"></body>");
            out.println("</html>");
        }
    } catch (Throwable t) {
        throw new ServletException(t);
    }
}

From source file:Main.java

/**
 * Clone given Node into target Document. If targe is null, same Document will be used.
 * If deep is specified, all children below will also be cloned.
 *//*w  w  w.  j a  va  2 s .c om*/
public static Node cloneNode(Node node, Document target, boolean deep) throws DOMException {
    if (target == null || node.getOwnerDocument() == target)
        // same Document
        return node.cloneNode(deep);
    else {
        //DOM level 2 provides this in Document, so once xalan switches to that,
        //we can take out all the below and just call target.importNode(node, deep);
        //For now, we implement based on the javadocs for importNode
        Node newNode;
        int nodeType = node.getNodeType();

        switch (nodeType) {
        case Node.ATTRIBUTE_NODE:
            newNode = target.createAttribute(node.getNodeName());

            break;

        case Node.DOCUMENT_FRAGMENT_NODE:
            newNode = target.createDocumentFragment();

            break;

        case Node.ELEMENT_NODE:

            Element newElement = target.createElement(node.getNodeName());
            NamedNodeMap nodeAttr = node.getAttributes();

            if (nodeAttr != null)
                for (int i = 0; i < nodeAttr.getLength(); i++) {
                    Attr attr = (Attr) nodeAttr.item(i);

                    if (attr.getSpecified()) {
                        Attr newAttr = (Attr) cloneNode(attr, target, true);
                        newElement.setAttributeNode(newAttr);
                    }
                }

            newNode = newElement;

            break;

        case Node.ENTITY_REFERENCE_NODE:
            newNode = target.createEntityReference(node.getNodeName());

            break;

        case Node.PROCESSING_INSTRUCTION_NODE:
            newNode = target.createProcessingInstruction(node.getNodeName(), node.getNodeValue());

            break;

        case Node.TEXT_NODE:
            newNode = target.createTextNode(node.getNodeValue());

            break;

        case Node.CDATA_SECTION_NODE:
            newNode = target.createCDATASection(node.getNodeValue());

            break;

        case Node.COMMENT_NODE:
            newNode = target.createComment(node.getNodeValue());

            break;

        case Node.NOTATION_NODE:
        case Node.ENTITY_NODE:
        case Node.DOCUMENT_TYPE_NODE:
        case Node.DOCUMENT_NODE:
        default:
            throw new IllegalArgumentException("Importing of " + node + " not supported yet");
        }

        if (deep)
            for (Node child = node.getFirstChild(); child != null; child = child.getNextSibling())
                newNode.appendChild(cloneNode(child, target, true));

        return newNode;
    }
}

From source file:de.uzk.hki.da.metadata.MetadataStructure.java

private void addNewElementToParent(PreservationSystem preservationSystem, String id, String elementName,
        String elementValue, Element parent, Document edmDoc) {
    Element eName = edmDoc.createElement(elementName);
    if (elementName.equals(C.EDM_HAS_VIEW) || elementName.equals(C.EDM_IS_PART_OF)
            || elementName.equals(C.EDM_HAS_PART) || elementName.equals(C.EDM_IS_SHOWN_BY)
            || elementName.equals(C.EDM_OBJECT)) {
        if (elementName.equals(C.EDM_IS_PART_OF) || elementName.equals(C.EDM_HAS_PART)) {
            elementValue = preservationSystem.getUrisCho() + "/" + elementValue;
        }/* w  w w. j  av  a  2  s .c  o  m*/
        Attr rdfResource = edmDoc.createAttribute("rdf:resource");
        rdfResource.setValue(elementValue);
        eName.setAttributeNode(rdfResource);
    } else {
        eName.appendChild(edmDoc.createTextNode(elementValue));
    }
    parent.appendChild(eName);
}

From source file:uk.co.markfrimston.tasktree.TaskTree.java

protected void addChildElementsFromTasks(Document doc, Element parent, DefaultMutableTreeNode treeNode,
        int indent) {
    for (int i = 0; i < treeNode.getChildCount(); i++) {
        DefaultMutableTreeNode treeChild = (DefaultMutableTreeNode) treeNode.getChildAt(i);
        String indentText = "\n";
        for (int j = 0; j < indent + 1; j++) {
            indentText += "\t";
        }/*from  w  w  w .  ja  va  2 s  .  co m*/
        parent.appendChild(doc.createTextNode(indentText));
        Element childEl = doc.createElement("task");
        childEl.setAttribute("label", (String) treeChild.getUserObject());
        parent.appendChild(childEl);
        addChildElementsFromTasks(doc, childEl, treeChild, indent + 1);
    }
    if (treeNode.getChildCount() > 0) {
        String indentText = "\n";
        for (int i = 0; i < indent; i++) {
            indentText += "\t";
        }
        parent.appendChild(doc.createTextNode(indentText));
    }
}

From source file:com.twinsoft.convertigo.engine.translators.WebServiceTranslator.java

private void copyNode(Node sourceNode, Node destinationNode) {
    Document destinationDoc = destinationNode.getOwnerDocument();

    switch (sourceNode.getNodeType()) {
    case Node.TEXT_NODE:
        Text text = destinationDoc.createTextNode(sourceNode.getNodeValue());
        destinationNode.appendChild(text);
        break;/* w  ww .j  a  va 2 s.c  om*/
    case Node.ELEMENT_NODE:
        Element element = destinationDoc.createElement(sourceNode.getNodeName());
        destinationNode.appendChild(element);

        element.setTextContent(sourceNode.getNodeValue());

        // Copy attributes
        NamedNodeMap attributes = sourceNode.getAttributes();
        int nbAttributes = attributes.getLength();

        for (int i = 0; i < nbAttributes; i++) {
            Node attribute = attributes.item(i);
            element.setAttribute(attribute.getNodeName(), attribute.getNodeValue());
        }

        // Copy children nodes
        NodeList children = sourceNode.getChildNodes();
        int nbChildren = children.getLength();
        for (int i = 0; i < nbChildren; i++) {
            Node child = children.item(i);
            copyNode(child, element);
        }
    }
}

From source file:net.sourceforge.eclipsetrader.ats.Repository.java

public void save() {
    try {//from w  w  w.j a  va 2s  .  c o m
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        builder.setErrorHandler(errorHandler);
        Document document = builder.getDOMImplementation().createDocument(null, "data", null);

        Element root = document.getDocumentElement();
        root.setAttribute("nextId", String.valueOf(nextId));

        for (Iterator iter = systems.iterator(); iter.hasNext();) {
            TradingSystem system = (TradingSystem) iter.next();

            Element element = document.createElement("system");
            element.setAttribute("id", String.valueOf(system.getId()));

            Element node = document.createElement("name");
            node.appendChild(document.createTextNode(system.getName()));
            element.appendChild(node);

            if (system.getAccount().getId() != null) {
                node = document.createElement("account");
                node.appendChild(document.createTextNode(String.valueOf(system.getAccount().getId())));
                element.appendChild(node);
            }

            node = document.createElement("tradingProvider");
            node.appendChild(document.createTextNode(system.getTradingProviderId()));
            element.appendChild(node);

            if (system.getMoneyManager() != null) {
                node = document.createElement("moneyManager");
                saveComponent(system.getMoneyManager(), document, node);
                element.appendChild(node);
            }

            for (Iterator paramIter = system.getParams().keySet().iterator(); paramIter.hasNext();) {
                String key = (String) paramIter.next();
                node = document.createElement("param");
                node.setAttribute("key", key);
                node.setAttribute("value", (String) system.getParams().get(key));
                element.appendChild(node);
            }

            for (Iterator iter2 = system.getStrategies().iterator(); iter2.hasNext();)
                saveStrategy((Strategy) iter2.next(), document, element);

            root.appendChild(element);
        }

        saveDocument(document, "", "systems.xml");

    } catch (Exception e) {
        log.error(e.toString(), e);
    }
}

From source file:Main.java

/**
 * Clone given Node into target Document. If targe is null, same Document will be used.
 * If deep is specified, all children below will also be cloned.
 *///from  w ww. j  a v  a2  s. c  o  m
public final static Node cloneNode(Node node, Document target, boolean deep) throws DOMException {
    if ((target == null) || (node.getOwnerDocument() == target)) {
        // same Document
        return node.cloneNode(deep);
    } else {
        //DOM level 2 provides this in Document, so once xalan switches to that,
        //we can take out all the below and just call target.importNode(node, deep);
        //For now, we implement based on the javadocs for importNode
        Node newNode;
        int nodeType = node.getNodeType();

        switch (nodeType) {
        case Node.ATTRIBUTE_NODE:
            newNode = target.createAttribute(node.getNodeName());

            break;

        case Node.DOCUMENT_FRAGMENT_NODE:
            newNode = target.createDocumentFragment();

            break;

        case Node.ELEMENT_NODE:

            Element newElement = target.createElement(node.getNodeName());
            NamedNodeMap nodeAttr = node.getAttributes();

            if (nodeAttr != null) {
                for (int i = 0; i < nodeAttr.getLength(); i++) {
                    Attr attr = (Attr) nodeAttr.item(i);

                    if (attr.getSpecified()) {
                        Attr newAttr = (Attr) cloneNode(attr, target, true);
                        newElement.setAttributeNode(newAttr);
                    }
                }
            }

            newNode = newElement;

            break;

        case Node.ENTITY_REFERENCE_NODE:
            newNode = target.createEntityReference(node.getNodeName());

            break;

        case Node.PROCESSING_INSTRUCTION_NODE:
            newNode = target.createProcessingInstruction(node.getNodeName(), node.getNodeValue());

            break;

        case Node.TEXT_NODE:
            newNode = target.createTextNode(node.getNodeValue());

            break;

        case Node.CDATA_SECTION_NODE:
            newNode = target.createCDATASection(node.getNodeValue());

            break;

        case Node.COMMENT_NODE:
            newNode = target.createComment(node.getNodeValue());

            break;

        case Node.NOTATION_NODE:
        case Node.ENTITY_NODE:
        case Node.DOCUMENT_TYPE_NODE:
        case Node.DOCUMENT_NODE:
        default:
            throw new IllegalArgumentException("Importing of " + node + " not supported yet");
        }

        if (deep) {
            for (Node child = node.getFirstChild(); child != null; child = child.getNextSibling()) {
                newNode.appendChild(cloneNode(child, target, true));
            }
        }

        return newNode;
    }
}

From source file:Main.java

/**
 * Copies the source tree into the specified place in a destination
 * tree. The source node and its children are appended as children
 * of the destination node.// w w w  .  j  a  v a  2  s. c o m
 * <p>
 * <em>Note:</em> This is an iterative implementation.
 */
public static void copyInto(Node src, Node dest) throws DOMException {

    // get node factory
    Document factory = dest.getOwnerDocument();
    boolean domimpl = factory instanceof DocumentImpl;

    // placement variables
    Node start = src;
    Node parent = src;
    Node place = src;

    // traverse source tree
    while (place != null) {

        // copy this node
        Node node = null;
        int type = place.getNodeType();
        switch (type) {
        case Node.CDATA_SECTION_NODE: {
            node = factory.createCDATASection(place.getNodeValue());
            break;
        }
        case Node.COMMENT_NODE: {
            node = factory.createComment(place.getNodeValue());
            break;
        }
        case Node.ELEMENT_NODE: {
            Element element = factory.createElement(place.getNodeName());
            node = element;
            NamedNodeMap attrs = place.getAttributes();
            int attrCount = attrs.getLength();
            for (int i = 0; i < attrCount; i++) {
                Attr attr = (Attr) attrs.item(i);
                String attrName = attr.getNodeName();
                String attrValue = attr.getNodeValue();
                element.setAttribute(attrName, attrValue);
                if (domimpl && !attr.getSpecified()) {
                    ((AttrImpl) element.getAttributeNode(attrName)).setSpecified(false);
                }
            }
            break;
        }
        case Node.ENTITY_REFERENCE_NODE: {
            node = factory.createEntityReference(place.getNodeName());
            break;
        }
        case Node.PROCESSING_INSTRUCTION_NODE: {
            node = factory.createProcessingInstruction(place.getNodeName(), place.getNodeValue());
            break;
        }
        case Node.TEXT_NODE: {
            node = factory.createTextNode(place.getNodeValue());
            break;
        }
        default: {
            throw new IllegalArgumentException(
                    "can't copy node type, " + type + " (" + node.getNodeName() + ')');
        }
        }
        dest.appendChild(node);

        // iterate over children
        if (place.hasChildNodes()) {
            parent = place;
            place = place.getFirstChild();
            dest = node;
        }

        // advance
        else {
            place = place.getNextSibling();
            while (place == null && parent != start) {
                place = parent.getNextSibling();
                parent = parent.getParentNode();
                dest = dest.getParentNode();
            }
        }

    }

}

From source file:de.qucosa.webapi.v1.DocumentResource.java

private void addDocumentId(Document qucosaDocument, String id) {
    Element elDocumentId = qucosaDocument.createElement("DocumentId");
    Text elText = qucosaDocument.createTextNode(id);
    elDocumentId.appendChild(elText);//ww  w  .j a v  a  2 s.  c  om
    qucosaDocument.getElementsByTagName("Opus_Document").item(0).appendChild(elDocumentId);
}

From source file:fi.helsinki.lib.simplerest.CommunitiesResource.java

@Get("xml")
public Representation toXml() {
    Context c = null;/*from  www  . j  a v a 2  s  .  c o m*/
    Community community = null;
    DomRepresentation representation = null;
    Document d = null;
    try {
        c = new Context();
        community = Community.find(c, this.communityId);
        if (community == null) {
            return errorNotFound(c, "Could not find the community.");
        }

        representation = new DomRepresentation(MediaType.TEXT_HTML);
        d = representation.getDocument();
    } catch (Exception e) {
        return errorInternal(c, e.toString());
    }

    Element html = d.createElement("html");
    d.appendChild(html);

    Element head = d.createElement("head");
    html.appendChild(head);

    Element title = d.createElement("title");
    head.appendChild(title);
    title.appendChild(d.createTextNode("Community " + community.getName()));

    Element body = d.createElement("body");
    html.appendChild(body);

    Element ulSubCommunities = d.createElement("ul");
    body.appendChild(ulSubCommunities);
    Community[] subCommunities;
    try {
        subCommunities = community.getSubcommunities();
    } catch (SQLException e) {
        return errorInternal(c, e.toString());
    }

    String url = getRequest().getResourceRef().getIdentifier();
    url = url.substring(0, url.lastIndexOf('/', url.lastIndexOf('/') - 1) + 1);
    for (Community subCommunity : subCommunities) {
        Element li = d.createElement("li");
        Element a = d.createElement("a");
        String href = url + Integer.toString(subCommunity.getID());
        setAttribute(a, "href", href);
        a.appendChild(d.createTextNode(subCommunity.getName()));
        li.appendChild(a);
        ulSubCommunities.appendChild(li);
    }

    Element form = d.createElement("form");
    form.setAttribute("enctype", "multipart/form-data");
    form.setAttribute("method", "post");
    makeInputRow(d, form, "name", "Name");
    makeInputRow(d, form, "short_description", "Short description");
    makeInputRow(d, form, "introductory_text", "Introductory text");
    makeInputRow(d, form, "copyright_text", "Copyright text");
    makeInputRow(d, form, "side_bar_text", "Side bar text");
    makeInputRow(d, form, "logo", "Logo", "file");

    Element submitButton = d.createElement("input");
    submitButton.setAttribute("type", "submit");
    submitButton.setAttribute("value", "Create a new sub community");
    form.appendChild(submitButton);

    body.appendChild(form);

    c.abort(); // Same as c.complete() because we didn't modify the db.

    return representation;
}