Example usage for org.w3c.dom Document appendChild

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

Introduction

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

Prototype

public Node appendChild(Node newChild) throws DOMException;

Source Link

Document

Adds the node newChild to the end of the list of children of this node.

Usage

From source file:com.adaptris.core.services.jdbc.SplittingXmlPayloadTranslator.java

private DocumentWrapper toDocument(AdaptrisMessage msg, JdbcResultSet rSet)
        throws ParserConfigurationException, SQLException {
    DocumentBuilderFactoryBuilder factoryBuilder = documentFactoryBuilder(msg);
    DocumentBuilderFactory factory = factoryBuilder.configure(DocumentBuilderFactory.newInstance());
    DocumentBuilder builder = factoryBuilder.configure(factory.newDocumentBuilder());
    Document doc = builder.newDocument();
    DocumentWrapper result = new DocumentWrapper(doc, 0);
    ColumnStyle elementNameStyle = getColumnNameStyle();

    Element results = doc.createElement(elementNameStyle.format(ELEMENT_NAME_RESULTS));
    doc.appendChild(results);

    List<Element> elements = createListFromResultSet(builder, doc, rSet);
    for (Element element : elements) {
        results.appendChild(element);/*from  w w  w .j av  a  2s.c  om*/
    }
    result.resultSetCount += elements.size();
    return result;
}

From source file:scott.barleydb.test.TestBase.java

protected void printEntityContext(EntityContext entityContext) throws Exception {
    Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    Element el = entityContext.toXml(doc);
    doc.appendChild(el);
    Transformer transformer = TransformerFactory.newInstance()
            .newTransformer(new StreamSource(new ByteArrayInputStream(transformXml.getBytes("UTF-8"))));
    transformer.transform(new DOMSource(doc), new StreamResult(System.out));
    System.out.flush();//w w  w .  j  a v  a 2s  . co  m
}

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

@Get("html|xhtml|xml")
public Representation toXml() {
    DomRepresentation representation = null;
    Document d = null;
    try {/*from w  w  w.j  ava  2 s. c o  m*/
        representation = new DomRepresentation(MediaType.ALL);
        d = representation.getDocument();
    } catch (IOException ex) {
        log.log(Priority.INFO, ex, ex);
    }

    representation.setIndenting(true);

    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("Root communities"));

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

    Element ul = d.createElement("ul");
    setId(ul, "rootcommunities");
    body.appendChild(ul);

    String url = "";
    try {
        url = getRequest().getResourceRef().getIdentifier();
    } catch (NullPointerException e) {
        log.log(Priority.INFO, e, e);
    }
    url = url.substring(0, url.lastIndexOf('/') + 1);
    url += "community/";
    for (Community community : communities) {

        Element li = d.createElement("li");
        Element a = d.createElement("a");

        a.setAttribute("href", url + Integer.toString(community.getID()));
        a.appendChild(d.createTextNode(community.getName()));
        li.appendChild(a);
        ul.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 root community.");

    form.appendChild(submitButton);
    body.appendChild(form);

    try {
        if (context != null) {
            context.abort();
        }
    } catch (NullPointerException e) {
        log.log(Priority.INFO, e, e);
    }
    return representation;
}

From source file:com.ibm.dbwkl.request.internal.LoggingHandler.java

/**
 * @return xml output//from   www . ja va  2  s .  co m
 */
@Override
public Document getXML() {
    if (hasRequestOption(Options.LOG_LIST)) {
        try {
            List<LoggerEntry> logEntries = Logger.getLogEntries();

            int entriesToShow = Integer.parseInt(getRequestOption(Options.LOG_LIST));

            if (entriesToShow < logEntries.size())
                logEntries = logEntries.subList(logEntries.size() - entriesToShow, logEntries.size());
            // create the document
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.newDocument();

            // create the document root node
            Element root = document.createElement("db2wklresult");
            document.appendChild(root);

            // create the result information
            Element rc = document.createElement("rc");
            rc.setTextContent(Integer.toString(this.getResult().rc));
            root.appendChild(rc);

            Element object = document.createElement("resultObject");
            object.setTextContent(
                    this.getResult().resultObj == null ? "" : this.getResult().resultObj.toString());

            Element entries = null;

            for (LoggerEntry logEntry : logEntries) {
                entries = document.createElement("logEntry");
                entries.setAttribute("formattedTime", logEntry.getFormatedTime());
                entries.setAttribute("requestName", logEntry.getRequestName());
                entries.setAttribute("loglevel", logEntry.getLevel());
                entries.setAttribute("message", logEntry.getMessage().replaceAll(String.valueOf('"'), "'"));
                entries.setAttribute("class", logEntry.getClasse());
                entries.setAttribute("method", logEntry.getMethod());
                entries.setAttribute("line", String.valueOf(logEntry.getLineNumber()));
                entries.setAttribute("thread", logEntry.getThread());
                entries.setAttribute("threadGroup", logEntry.getThreadGroup());
                object.appendChild(entries);
            }

            root.appendChild(object);

            // return the resulting document
            return document;
        } catch (ParserConfigurationException e) {
            Logger.log(e.getMessage(), LogLevel.Error);
        }
    }

    return null;
}

From source file:edu.duke.cabig.c3pr.webservice.studyimportexport.impl.StudyImportExportImpl.java

/**
 * Convert to oai./*from   w w  w  .j a  va2  s  .c o m*/
 *
 * @param studyId the study id
 * @return the organization assigned identifier
 * @throws XMLUtilityException the xML utility exception
 * @throws ParserConfigurationException the parser configuration exception
 */
private OrganizationAssignedIdentifier convertToOAI(Element studyId)
        throws XMLUtilityException, ParserConfigurationException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.newDocument();
    doc.appendChild(doc.importNode(studyId, true));

    DOMBuilder jdomBuilder = new DOMBuilder();
    org.jdom.Document jdomDoc = jdomBuilder.build(doc);
    String xmlRep = new XMLOutputter().outputString(jdomDoc);
    OrganizationAssignedIdentifier oai = (OrganizationAssignedIdentifier) marshaller
            .fromXML(new StringReader(xmlRep));
    return oai;
}

From source file:edu.duke.cabig.c3pr.webservice.studyimportexport.impl.StudyImportExportImpl.java

/**
 * Process study import request./*www.  jav  a 2s  .  c  om*/
 *
 * @param body the body
 * @return the sOAP message
 * @throws DOMException the dOM exception
 * @throws RuntimeException the runtime exception
 * @throws ParserConfigurationException the parser configuration exception
 * @throws C3PRCodedException the c3 pr coded exception
 * @throws SOAPException the sOAP exception
 */
private SOAPMessage processStudyImportRequest(SOAPBody body)
        throws DOMException, RuntimeException, ParserConfigurationException, C3PRCodedException, SOAPException {
    NodeList nodes = body.getElementsByTagNameNS(SERVICE_NS, IMPORT_STUDY_REQUEST);
    Node importStudyRequestNode = nodes.item(0);
    NodeList studyNodes = ((Element) importStudyRequestNode).getElementsByTagNameNS(C3PR_NS, STUDY_ELEMENT);
    if (studyNodes.getLength() != 1) {
        throw new RuntimeException("Malformed SOAP request. Please check the WSDL.");
    }
    Element study = (Element) studyNodes.item(0);

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.newDocument();
    doc.appendChild(doc.importNode(study, true));
    List<Study> studies = studyXMLImporterService.importStudies(doc, new ErrorsImpl());
    if (CollectionUtils.isEmpty(studies)) {
        throw new RuntimeException("No studies have been imported.");
    }
    return createImportStudyResponse();

}

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

public void processFormData(HttpServletRequest request, HttpServletResponse response) throws ServletException {
    try {//w ww  .java 2  s  .  co  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:Interface.MainJFrame.java

private void btnXMLActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnXMLActionPerformed
    // TODO add your handling code here:
    try {// w ww.  j av  a2 s  .c o  m

        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

        // root elements
        Document doc = docBuilder.newDocument();
        Element rootElement = doc.createElement("Employees");
        doc.appendChild(rootElement);

        // staff elements
        String empTitle = txtEmployeeType.getText().trim();
        empTitle = empTitle.replace(" ", "");
        Element staff = doc.createElement(empTitle);
        rootElement.appendChild(staff);

        // set attribute to staff element
        Attr attr = doc.createAttribute("ID");
        attr.setValue(txtEmployeeID.getText().trim());
        staff.setAttributeNode(attr);

        // shorten way
        // staff.setAttribute("id", "1");

        // FullName elements
        Element FulllName = doc.createElement("FulllName");
        FulllName.appendChild(doc.createTextNode(txtFullName.getText().trim()));
        staff.appendChild(FulllName);

        // Phone elements
        Element Phone = doc.createElement("PhoneNumber");
        Phone.appendChild(doc.createTextNode(txtPhoneNumber.getText().trim()));
        staff.appendChild(Phone);

        // Address elements
        Element Address = doc.createElement("Address");
        Address.appendChild(doc.createTextNode(txtAddress.getText().trim()));
        staff.appendChild(Address);

        // Title elements
        Element Title = doc.createElement("Tile");
        Title.appendChild(doc.createTextNode(txtEmployeeType.getText().trim()));
        staff.appendChild(Title);

        // PayCategory elements
        Element PayCategory = doc.createElement("PayCategory");
        PayCategory.appendChild(doc.createTextNode(txtPayCategory.getText().trim()));
        staff.appendChild(PayCategory);

        // Salary elements
        Element Salary = doc.createElement("Salary");
        Salary.appendChild(doc.createTextNode(txtSalary.getText().trim()));
        staff.appendChild(Salary);

        // Hours elements

        String hours = txtHours.getText().trim();
        if (txtHours.getText().equalsIgnoreCase("") || hours == null) {
            hours = "null";
        }
        Element Hours = doc.createElement("Hours");
        Hours.appendChild(doc.createTextNode(hours));
        staff.appendChild(Hours);

        // Bonus elements
        Element Bonus = doc.createElement("Bonus");
        Bonus.appendChild(doc.createTextNode(txtBonuses.getText().trim()));
        staff.appendChild(Bonus);

        // Total elements
        Element Total = doc.createElement("Total");
        Total.appendChild(doc.createTextNode(txtTotal.getText().trim()));
        staff.appendChild(Total);

        // write the content into xml file
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(new File("XMLOutput"));

        // Output to console for testing
        // StreamResult result = new StreamResult(System.out);

        transformer.transform(source, result);

    } catch (ParserConfigurationException pce) {
        pce.printStackTrace();
    } catch (TransformerException tfe) {
        tfe.printStackTrace();
    }

}

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

protected Document saveToDocument() throws Exception {
    DocumentBuilder builder = builderFact.newDocumentBuilder();
    Document doc = builder.newDocument();
    Element taskList = doc.createElement("tasklist");
    doc.appendChild(taskList);
    taskList.appendChild(doc.createTextNode("\n\t"));
    Element tasks = doc.createElement("tasks");
    taskList.appendChild(tasks);//from ww  w  .ja  v  a 2s .  co m
    taskList.appendChild(doc.createTextNode("\n"));
    addChildElementsFromTasks(doc, tasks, root, 1);

    return doc;
}

From source file:Exporters.SaveFileExporter.java

public void save(File outfile, DefaultMutableTreeNode root) throws Exception {
    System.out.println("===SaveFileExporter==save:" + outfile.getAbsolutePath());

    // Create new XML document
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

    // Create the root element
    Document doc = docBuilder.newDocument();
    Element rootElement = doc.createElement("reportCompiler");
    rootElement.setAttribute("date", getNow()); // Debugging to say when saved
    // TODO - figure out a universal means to get the current version of the generating tool
    // Initial thoughts would be to create a convenience class in Utils package with some
    // final variables that can be updated when issuing a release.
    doc.appendChild(rootElement);

    Element vulnerabilitiesElement = doc.createElement("vulnerabilities");

    Enumeration enums = root.children();
    while (enums.hasMoreElements()) {
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) enums.nextElement();
        Object obj = node.getUserObject();
        if (obj instanceof Vulnerability) {
            Vulnerability vuln = (Vulnerability) obj;
            Element vulnElement = getVulnAsElement(vuln, doc);
            if (vulnElement != null) {
                vulnerabilitiesElement.appendChild(vulnElement);
            }/*from ww w . j  a  v  a 2  s  . com*/
        }
    }

    rootElement.appendChild(vulnerabilitiesElement);

    // now write the XML file
    // write the content into xml file
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();

    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(outfile);

    // Output to console for testing
    //StreamResult result = new StreamResult(System.out);
    transformer.transform(source, result);

    System.out.println("File saved!");

}