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.jaspersoft.studio.data.querydesigner.xpath.XPathQueryDesigner.java

private void createContextualMenu() {
    Menu contextMenu = new Menu(treeViewer.getTree());
    final MenuItem setRecordNodeItem = new MenuItem(contextMenu, SWT.PUSH);
    setRecordNodeItem.setText(Messages.XPathQueryDesigner_SetRecordItem);
    setRecordNodeItem.addSelectionListener(new SelectionAdapter() {
        @Override//from   w w w. j  a  va  2s. c om
        public void widgetSelected(SelectionEvent e) {
            Object sel = ((IStructuredSelection) treeViewer.getSelection()).getFirstElement();
            if (sel instanceof XMLNode) {
                String xPathExpression = documentManager.getXPathExpression(null, (XMLNode) sel);
                queryTextArea.setText((xPathExpression != null) ? xPathExpression : ""); //$NON-NLS-1$
            }
        }
    });
    final MenuItem setDocumentRootItem = new MenuItem(contextMenu, SWT.PUSH);
    setDocumentRootItem.setText(Messages.XPathQueryDesigner_SetDocRootItem);
    setDocumentRootItem.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            Object sel = ((IStructuredSelection) treeViewer.getSelection()).getFirstElement();
            try {
                Document newDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
                Node originalNode = documentManager.getDocumentNodesMap().get(sel);
                Node importedNode = newDocument.importNode(originalNode, true);
                newDocument.appendChild(importedNode);
                documentManager.setDocument(newDocument);
                treeViewer.setInput(documentManager.getXMLDocumentModel());
            } catch (Exception e1) {
                UIUtils.showError(e1);
            }
        }
    });
    new MenuItem(contextMenu, SWT.SEPARATOR);
    final MenuItem addNodeAsFieldItem1 = new MenuItem(contextMenu, SWT.PUSH);
    addNodeAsFieldItem1.setText(Messages.XPathQueryDesigner_AddAsFieldItem);
    addNodeAsFieldItem1.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            Object sel = ((IStructuredSelection) treeViewer.getSelection()).getFirstElement();
            if (sel instanceof XMLNode) {
                String xPathExpression = documentManager.getXPathExpression(queryTextArea.getText(),
                        (XMLNode) sel);
                ((XMLNode) sel).setXPathExpression(xPathExpression);
                createField((XMLNode) sel);
            }
        }
    });
    final MenuItem addNodeAsFieldItem2 = new MenuItem(contextMenu, SWT.PUSH);
    addNodeAsFieldItem2.setText(Messages.XPathQueryDesigner_AddAsFieldAbsoluteItem);
    addNodeAsFieldItem2.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            Object sel = ((IStructuredSelection) treeViewer.getSelection()).getFirstElement();
            if (sel instanceof XMLNode) {
                String xPathExpression = documentManager.getXPathExpression(null, (XMLNode) sel);
                ((XMLNode) sel).setXPathExpression(xPathExpression);
                createField((XMLNode) sel);
            }
        }
    });
    new MenuItem(contextMenu, SWT.SEPARATOR);
    final MenuItem expandAllItem = new MenuItem(contextMenu, SWT.PUSH);
    expandAllItem.setText(Messages.XPathQueryDesigner_ExpandAllItem);
    expandAllItem.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            treeViewer.expandAll();
        }
    });
    final MenuItem collapseAllItem = new MenuItem(contextMenu, SWT.PUSH);
    collapseAllItem.setText(Messages.XPathQueryDesigner_CollapseAllItem);
    collapseAllItem.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            treeViewer.collapseAll();
        }
    });
    final MenuItem resetRefreshDocItem = new MenuItem(contextMenu, SWT.PUSH);
    resetRefreshDocItem.setText(Messages.XPathQueryDesigner_RefreshItem);
    resetRefreshDocItem.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            refreshTreeViewerContent(container.getDataAdapter());
        }
    });
    treeViewer.getTree().setMenu(contextMenu);

    contextMenu.addMenuListener(new MenuListener() {
        @Override
        public void menuShown(MenuEvent e) {
            Object selEl = ((IStructuredSelection) treeViewer.getSelection()).getFirstElement();
            if (selEl instanceof XMLNode) {
                addNodeAsFieldItem1.setEnabled(true);
                addNodeAsFieldItem2.setEnabled(true);
                if (selEl instanceof XMLAttributeNode) {
                    setRecordNodeItem.setEnabled(false);
                    setDocumentRootItem.setEnabled(false);
                } else {
                    setRecordNodeItem.setEnabled(true);
                    setDocumentRootItem.setEnabled(true);
                }
            } else {
                setRecordNodeItem.setEnabled(false);
                setDocumentRootItem.setEnabled(false);
                addNodeAsFieldItem1.setEnabled(false);
                addNodeAsFieldItem2.setEnabled(false);
            }
        }

        @Override
        public void menuHidden(MenuEvent e) {

        }
    });
}

From source file:net.sf.jabref.logic.mods.MODSDatabase.java

public Document getDOMrepresentation() {
    Document result = null;
    try {/*from  ww  w .j  a v a 2 s  .  c  o m*/
        DocumentBuilder dbuild = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        result = dbuild.newDocument();
        Element modsCollection = result.createElement("modsCollection");
        modsCollection.setAttribute("xmlns", "http://www.loc.gov/mods/v3");
        modsCollection.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
        modsCollection.setAttribute("xsi:schemaLocation",
                "http://www.loc.gov/mods/v3 http://www.loc.gov/standards/mods/v3/mods-3-0.xsd");

        for (MODSEntry entry : entries) {
            Node node = entry.getDOMrepresentation(result);
            modsCollection.appendChild(node);
        }

        result.appendChild(modsCollection);
    } catch (Exception e) {
        LOGGER.info("Could not get DOM representation", e);
    }
    return result;
}

From source file:main.java.vasolsim.common.file.ExamBuilder.java

/**
 * writes an editable, unlocked exam to a file
 *
 * @param exam      the exam to be written
 * @param examFile  the target file/*from  ww  w.  j  av  a  2 s  . c om*/
 * @param overwrite if an existing file can be overwritten
 *
 * @return if the file write was successful
 *
 * @throws VaSolSimException
 */
public static boolean writeRaw(@Nonnull Exam exam, @Nonnull File examFile, boolean overwrite)
        throws VaSolSimException {
    /*
     * check the file creation status and handle it
     */
    //if it exists
    if (examFile.isFile()) {
        //can't overwrite
        if (!overwrite) {
            throw new VaSolSimException(ERROR_MESSAGE_FILE_ALREADY_EXISTS);
        }
        //can overwrite, clear the existing file
        else {
            PrintWriter printWriter;
            try {
                printWriter = new PrintWriter(examFile);
            } catch (FileNotFoundException e) {
                throw new VaSolSimException(ERROR_MESSAGE_FILE_NOT_FOUND_AFTER_INTERNAL_CHECK);
            }

            printWriter.print("");
            printWriter.close();
        }
    }
    //no file, create one
    else {
        if (!examFile.getParentFile().isDirectory() && !examFile.getParentFile().mkdirs()) {
            throw new VaSolSimException(ERROR_MESSAGE_COULD_NOT_CREATE_DIRS);
        }

        try {
            if (!examFile.createNewFile()) {
                throw new VaSolSimException(ERROR_MESSAGE_COULD_NOT_CREATE_FILE);
            }
        } catch (IOException e) {
            throw new VaSolSimException(ERROR_MESSAGE_CREATE_FILE_EXCEPTION);
        }
    }

    /*
     * initialize the document
     */
    Document examDoc;
    Transformer examTransformer;
    try {
        examDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();

        examTransformer = TransformerFactory.newInstance().newTransformer();
        examTransformer.setOutputProperty(OutputKeys.INDENT, "yes");
        examTransformer.setOutputProperty(OutputKeys.METHOD, "xml");
        examTransformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        examTransformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "roles.dtd");
        examTransformer.setOutputProperty(INDENTATION_KEY, "4");
    } catch (ParserConfigurationException e) {
        throw new VaSolSimException(ERROR_MESSAGE_INTERNAL_XML_PARSER_INITIALIZATION_EXCEPTION, e);
    } catch (TransformerConfigurationException e) {
        throw new VaSolSimException(ERROR_MESSAGE_INTERNAL_TRANSFORMER_CONFIGURATION, e);
    }

    /*
     * build exam info
     */
    Element root = examDoc.createElement(XML_ROOT_ELEMENT_NAME);
    examDoc.appendChild(root);

    Element info = examDoc.createElement(XML_INFO_ELEMENT_NAME);
    root.appendChild(info);

    //exam info
    GenericUtils.appendSubNode(XML_TEST_NAME_ELEMENT_NAME, exam.getTestName(), info, examDoc);
    GenericUtils.appendSubNode(XML_AUTHOR_NAME_ELEMENT_NAME, exam.getAuthorName(), info, examDoc);
    GenericUtils.appendSubNode(XML_SCHOOL_NAME_ELEMENT_NAME, exam.getSchoolName(), info, examDoc);
    GenericUtils.appendSubNode(XML_PERIOD_NAME_ELEMENT_NAME, exam.getPeriodName(), info, examDoc);

    //start security xml section
    Element security = examDoc.createElement(XML_SECURITY_ELEMENT_NAME);
    root.appendChild(security);

    GenericUtils.appendSubNode(XML_IS_REPORTING_STATISTICS_ELEMENT_NAME,
            Boolean.toString(exam.isReportingStats()), security, examDoc);
    GenericUtils.appendSubNode(XML_IS_REPORTING_STATISTICS_STANDALONE_ELEMENT_NAME,
            Boolean.toString(exam.isReportingStatsStandalone()), security, examDoc);
    GenericUtils.appendSubNode(XML_STATISTICS_DESTINATION_EMAIL_ADDRESS_ELEMENT_NAME,
            exam.getStatsDestinationEmail(), security, examDoc);
    GenericUtils.appendSubNode(XML_STATISTICS_SENDER_EMAIL_ADDRESS_ELEMENT_NAME, exam.getStatsSenderEmail(),
            security, examDoc);
    GenericUtils.appendSubNode(XML_STATISTICS_SENDER_SMTP_ADDRESS_ELEMENT_NAME,
            exam.getStatsSenderSMTPAddress(), security, examDoc);
    GenericUtils.appendSubNode(XML_STATISTICS_SENDER_SMTP_PORT_ELEMENT_NAME,
            Integer.toString(exam.getStatsSenderSMTPPort()), security, examDoc);

    ArrayList<QuestionSet> questionSets = exam.getQuestionSets();
    if (GenericUtils.verifyQuestionSetsIntegrity(questionSets)) {
        for (int setsIndex = 0; setsIndex < questionSets.size(); setsIndex++) {
            QuestionSet qSet = questionSets.get(setsIndex);

            Element qSetElement = examDoc.createElement(XML_QUESTION_SET_ELEMENT_NAME);
            root.appendChild(qSetElement);

            GenericUtils.appendSubNode(XML_QUESTION_SET_ID_ELEMENT_NAME, Integer.toString(setsIndex + 1),
                    qSetElement, examDoc);
            GenericUtils.appendSubNode(XML_QUESTION_SET_NAME_ELEMENT_NAME,
                    (qSet.getName() == null || qSet.getName().equals("")) ? "Question Set " + (setsIndex + 1)
                            : qSet.getName(),
                    qSetElement, examDoc);
            GenericUtils.appendSubNode(XML_QUESTION_SET_RESOURCE_TYPE_ELEMENT_NAME,
                    qSet.getResourceType().toString(), qSetElement, examDoc);

            if (qSet.getResources() != null) {
                for (BufferedImage img : qSet.getResources()) {
                    try {
                        ByteArrayOutputStream out = new ByteArrayOutputStream();
                        ImageIO.write(img, "png", out);
                        out.flush();
                        GenericUtils.appendSubNode(XML_QUESTION_SET_RESOURCE_DATA_ELEMENT_NAME,
                                convertBytesToHexString(out.toByteArray()), qSetElement, examDoc);
                    } catch (IOException e) {
                        throw new VaSolSimException("Error: cannot write images to byte array for transport");
                    }
                }
            }

            for (int setIndex = 0; setIndex < qSet.getQuestions().size(); setIndex++) {
                Question question = qSet.getQuestions().get(setIndex);

                Element qElement = examDoc.createElement(XML_QUESTION_ELEMENT_NAME);
                qSetElement.appendChild(qElement);

                GenericUtils.appendSubNode(XML_QUESTION_ID_ELEMENT_NAME, Integer.toString(setIndex + 1),
                        qElement, examDoc);
                GenericUtils.appendSubNode(XML_QUESTION_NAME_ELEMENT_NAME,
                        (question.getName() == null || question.getName().equals(""))
                                ? "Question " + (setIndex + 1)
                                : question.getName(),
                        qElement, examDoc);
                GenericUtils.appendSubNode(XML_QUESTION_TEXT_ELEMENT_NAME, question.getQuestion(), qElement,
                        examDoc);
                GenericUtils.appendSubNode(XML_QUESTION_SCRAMBLE_ANSWERS_ELEMENT_NAME,
                        Boolean.toString(question.getScrambleAnswers()), qElement, examDoc);
                GenericUtils.appendSubNode(XML_QUESTION_REATIAN_ANSWER_ORDER_ELEMENT_NAME,
                        Boolean.toString(question.getAnswerOrderMatters()), qElement, examDoc);

                for (AnswerChoice answer : question.getCorrectAnswerChoices()) {
                    GenericUtils.appendSubNode(XML_QUESTION_ENCRYPTED_ANSWER_HASH, answer.getAnswerText(),
                            qElement, examDoc);
                }

                for (int questionIndex = 0; questionIndex < question.getAnswerChoices()
                        .size(); questionIndex++) {
                    AnswerChoice ac = question.getAnswerChoices().get(questionIndex);

                    Element acElement = examDoc.createElement(XML_ANSWER_CHOICE_ELEMENT_NAME);
                    qElement.appendChild(acElement);

                    GenericUtils.appendSubNode(XML_ANSWER_CHOICE_ID_ELEMENT_NAME,
                            Integer.toString(questionIndex + 1), acElement, examDoc);
                    GenericUtils.appendSubNode(XML_ANSWER_CHOICE_VISIBLE_ID_ELEMENT_NAME,
                            ac.getVisibleChoiceID(), acElement, examDoc);
                    GenericUtils.appendSubNode(XML_ANSWER_TEXT_ELEMENT_NAME, ac.getAnswerText(), acElement,
                            examDoc);
                }
            }
        }
    }

    return true;
}

From source file:de.betterform.xml.xforms.model.Instance.java

/**
 * returns the initial instance/*from   www.ja  va2 s .  co  m*/
 * @return the initial instance
 */
public Document getInitialInstance() {
    if (this.initialInstance != null) {
        Document doc = DOMUtil.newDocument(true, false);
        doc.appendChild(doc.importNode(this.initialInstance, true));
        return doc;
    } else {
        return null;
    }
}

From source file:ru.itdsystems.alfresco.persistence.CrudPost.java

@Override
public void execute(WebScriptRequest req, WebScriptResponse res) throws WebScriptException {
    // construct path elements array from request parameters
    List<String> pathElements = new ArrayList<String>();
    Map<String, String> templateVars = req.getServiceMatch().getTemplateVars();
    pathElements.add(templateVars.get("application_name"));
    pathElements.add(templateVars.get("form_name"));
    doBefore(pathElements, null);//from  ww  w  . j  a  va 2 s  .  c o  m
    // parse xml from request and perform a search
    Document searchXML;
    DocumentBuilder xmlBuilder;
    DocumentBuilderFactory xmlFact;
    try {
        xmlFact = DocumentBuilderFactory.newInstance();
        xmlFact.setNamespaceAware(true);
        xmlBuilder = xmlFact.newDocumentBuilder();
        searchXML = xmlBuilder.parse(req.getContent().getInputStream());
    } catch (Exception e) {
        throw new WebScriptException(500, "Error occured while parsing XML from request.", e);
    }
    XPath xpath = XPathFactory.newInstance().newXPath();
    Integer pageSize;
    Integer pageNumber;
    String lang;
    // String applicationName;
    // String formName;
    NodeList queries;
    // extract search details
    try {
        pageSize = new Integer(
                ((Node) xpath.evaluate("/search/page-size/text()", searchXML, XPathConstants.NODE))
                        .getNodeValue());
        pageNumber = new Integer(
                ((Node) xpath.evaluate("/search/page-number/text()", searchXML, XPathConstants.NODE))
                        .getNodeValue());
        lang = ((Node) xpath.evaluate("/search/lang/text()", searchXML, XPathConstants.NODE)).getNodeValue();
        // applicationName = ((Node) xpath.evaluate("/search/app/text()",
        // searchXML, XPathConstants.NODE)).getNodeValue();
        // formName = ((Node) xpath.evaluate("/search/form/text()",
        // searchXML,
        // XPathConstants.NODE)).getNodeValue();
        queries = (NodeList) xpath.evaluate("/search/query", searchXML, XPathConstants.NODESET);
        if (queries.getLength() == 0)
            throw new Exception("No queries found.");
    } catch (Exception e) {
        throw new WebScriptException(500, "XML in request is malformed.", e);
    }
    // check if requested query is supported
    if (!"".equals(queries.item(0).getTextContent()))
        throw new WebScriptException(500, "Freetext queries are not supported at the moment.");
    // resolve path to root data
    pathElements.add("data");
    NodeRef nodeRef = getRootNodeRef();
    // resolve path to file
    FileInfo fileInfo = null;
    Integer totalForms = 0;
    try {
        //         fileInfo = fileFolderService.resolveNamePath(nodeRef, pathElements, false);
        fileInfo = fileFolderService.resolveNamePath(nodeRef, pathElements);
    } catch (FileNotFoundException e) {
        // do nothing here
    }
    if (fileInfo != null) {
        // iterate through all forms
        List<ChildAssociationRef> assocs = nodeService.getChildAssocs(fileInfo.getNodeRef());
        List<String> details = new ArrayList<String>();
        Document resultXML;
        try {
            resultXML = xmlBuilder.newDocument();
        } catch (Exception e) {
            throw new WebScriptException(500, "Smth really strange happened o.O", e);
        }
        Element rootElement = resultXML.createElement("documents");
        rootElement.setAttribute("page-size", pageSize.toString());
        rootElement.setAttribute("page-number", pageNumber.toString());
        rootElement.setAttribute("query", "");
        resultXML.appendChild(rootElement);
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZZZZ");
        int skip = pageSize * (pageNumber - 1);
        Integer found = 0;
        Integer searchTotal = 0;
        for (ChildAssociationRef assoc : assocs) {
            if ((nodeRef = nodeService.getChildByName(assoc.getChildRef(), ContentModel.ASSOC_CONTAINS,
                    "data.xml")) != null) {
                // parse file
                Document dataXML;
                try {
                    dataXML = xmlBuilder.parse(fileFolderService.getReader(nodeRef).getContentInputStream());
                } catch (Exception e) {
                    throw new WebScriptException(500, "Form file is malformed.", e);
                }
                totalForms++;
                details.clear();
                xpath.setNamespaceContext(new OrbeonNamespaceContext());
                // execute search queries
                for (int i = 1; i < queries.getLength(); i++) {
                    Node query = queries.item(i);
                    String path = query.getAttributes().getNamedItem("path").getNodeValue();
                    String match = query.getAttributes().getNamedItem("match").getNodeValue();
                    String queryString = query.getTextContent();
                    if (path == null || match == null || queryString == null)
                        throw new WebScriptException(500, "Search query XML is malformed.");
                    path = path.replace("$fb-lang", "'" + lang + "'");
                    boolean exactMatch = "exact".equals(match);
                    Node queryResult;
                    try {
                        queryResult = (Node) xpath.evaluate(path, dataXML.getDocumentElement(),
                                XPathConstants.NODE);
                    } catch (Exception e) {
                        throw new WebScriptException(500, "Error in query xpath expression.", e);
                    }
                    if (queryResult == null)
                        break;
                    String textContent = queryResult.getTextContent();
                    // TODO
                    // check type while comparing values
                    if (exactMatch && queryString.equals(textContent)
                            || !exactMatch && textContent != null && textContent.contains(queryString)
                            || queryString.isEmpty())
                        details.add(textContent);
                    else
                        break;
                }
                // add document to response xml
                if (details.size() == queries.getLength() - 1) {
                    searchTotal++;
                    if (skip > 0)
                        skip--;
                    else if (++found <= pageSize) {
                        Element item = resultXML.createElement("document");
                        String createdText = dateFormat
                                .format(fileFolderService.getFileInfo(nodeRef).getCreatedDate());
                        item.setAttribute("created",
                                createdText.substring(0, 26) + ":" + createdText.substring(26));
                        String modifiedText = dateFormat
                                .format(fileFolderService.getFileInfo(nodeRef).getModifiedDate());
                        item.setAttribute("last-modified",
                                modifiedText.substring(0, 26) + ":" + modifiedText.substring(26));
                        item.setAttribute("name", fileFolderService.getFileInfo(assoc.getChildRef()).getName());
                        resultXML.getDocumentElement().appendChild(item);
                        Element detailsElement = resultXML.createElement("details");
                        item.appendChild(detailsElement);
                        for (String detail : details) {
                            Element detailElement = resultXML.createElement("detail");
                            detailElement.appendChild(resultXML.createTextNode(detail));
                            detailsElement.appendChild(detailElement);
                        }
                    } /*
                      * else break;
                      */

                }
            }
        }
        rootElement.setAttribute("total", totalForms.toString());
        rootElement.setAttribute("search-total", searchTotal.toString());
        // stream output to client
        try {
            TransformerFactory.newInstance().newTransformer().transform(new DOMSource(resultXML),
                    new StreamResult(res.getOutputStream()));
        } catch (Exception e) {
            throw new WebScriptException(500, "Error occured while streaming output to client.", e);
        }
    }

}

From source file:net.ion.radon.impl.let.webdav.FCKConnectorRestlet.java

protected Node createCommonXML(final Document doc, final String commandStr, final String typeStr,
        final String currentPath, final String currentUrl) {

    final Element root = doc.createElement("Connector");
    root.setAttribute("command", commandStr);
    root.setAttribute("resourceType", typeStr);

    final Element myEl = doc.createElement("CurrentFolder");
    myEl.setAttribute("path", currentPath);
    myEl.setAttribute("url", currentUrl);

    root.appendChild(myEl);/*from  w ww .  j  a v  a2  s. co m*/
    doc.appendChild(root);

    return root;
}

From source file:edu.mit.csail.sls.wami.relay.WamiRelay.java

private void sendErrorMessage(String type, String message, String details) {
    Document doc = XmlUtils.newXMLDocument();
    Element root = doc.createElement("reply");
    root.setAttribute("type", "error");
    root.setAttribute("error_type", type);
    root.setAttribute("message", message);
    root.setAttribute("details", details);
    doc.appendChild(root);
    sendMessage(doc);//from   w w  w. j  av  a2 s.  c o  m
}

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

@Get("xml")
public Representation toXml() {
    Context c = null;/*from www  .ja va 2 s  .  c om*/
    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;
}

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

@Get("xml")
public Representation get() {
    Context c = null;//from   www.  ja v  a  2 s  . c  om
    Bundle bundle = null;
    DomRepresentation representation = null;
    Document d = null;
    try {
        c = new Context();
        bundle = Bundle.find(c, this.bundleId);
        if (bundle == null) {
            return errorNotFound(c, "Could not find the bundle.");
        }

        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("Bundle " + bundle.getName()));

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

    Element dl = d.createElement("dl");
    setId(dl, "attributes");
    body.appendChild(dl);

    addDtDd(d, dl, "primarybitstreamid", Integer.toString(bundle.getPrimaryBitstreamID()));
    addDtDd(d, dl, "name", bundle.getName());

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

    String base = baseUrl();
    for (Bitstream bitstream : bundle.getBitstreams()) {
        Element li = d.createElement("li");
        Element a = d.createElement("a");
        String href = base + BitstreamResource.relativeUrl(bitstream.getID());
        setAttribute(a, "href", href);
        a.appendChild(d.createTextNode(bitstream.getName()));
        li.appendChild(a);
        ulBitstreams.appendChild(li);
    }

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

From source file:com.msopentech.odatajclient.engine.performance.BasicPerfTest.java

@Test
public void writeAtomViaLowerlevelLibs() throws ParserConfigurationException, ClassNotFoundException,
        InstantiationException, IllegalAccessException {

    final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    final DocumentBuilder builder = factory.newDocumentBuilder();
    final Document doc = builder.newDocument();

    final Element entry = doc.createElement("entry");
    entry.setAttribute("xmlns", "http://www.w3.org/2005/Atom");
    entry.setAttribute("xmlns:m", "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata");
    entry.setAttribute("xmlns:d", "http://schemas.microsoft.com/ado/2007/08/dataservices");
    entry.setAttribute("xmlns:gml", "http://www.opengis.net/gml");
    entry.setAttribute("xmlns:georss", "http://www.georss.org/georss");
    doc.appendChild(entry);/*from  ww  w  .j  av  a2 s .  co m*/

    final Element category = doc.createElement("category");
    category.setAttribute("term", "Microsoft.Test.OData.Services.AstoriaDefaultService.Customer");
    category.setAttribute("scheme", "http://schemas.microsoft.com/ado/2007/08/dataservices/scheme");
    entry.appendChild(category);

    final Element properties = doc.createElement("m:properties");
    entry.appendChild(properties);

    final Element name = doc.createElement("d:Name");
    name.setAttribute("m:type", "Edm.String");
    name.appendChild(doc.createTextNode("A name"));
    properties.appendChild(name);

    final Element customerId = doc.createElement("d:CustomerId");
    customerId.setAttribute("m:type", "Edm.Int32");
    customerId.appendChild(doc.createTextNode("0"));
    properties.appendChild(customerId);

    final Element bci = doc.createElement("d:BackupContactInfo");
    bci.setAttribute("m:type",
            "Collection(Microsoft.Test.OData.Services.AstoriaDefaultService.ContactDetails)");
    properties.appendChild(bci);

    final Element topelement = doc.createElement("d:element");
    topelement.setAttribute("m:type", "Microsoft.Test.OData.Services.AstoriaDefaultService.ContactDetails");
    bci.appendChild(topelement);

    final Element altNames = doc.createElement("d:AlternativeNames");
    altNames.setAttribute("m:type", "Collection(Edm.String)");
    topelement.appendChild(altNames);

    final Element element1 = doc.createElement("d:element");
    element1.setAttribute("m:type", "Edm.String");
    element1.appendChild(doc.createTextNode("myname"));
    altNames.appendChild(element1);

    final Element emailBag = doc.createElement("d:EmailBag");
    emailBag.setAttribute("m:type", "Collection(Edm.String)");
    topelement.appendChild(emailBag);

    final Element element2 = doc.createElement("d:element");
    element2.setAttribute("m:type", "Edm.String");
    element2.appendChild(doc.createTextNode("myname@mydomain.com"));
    emailBag.appendChild(element2);

    final Element contactAlias = doc.createElement("d:ContactAlias");
    contactAlias.setAttribute("m:type", "Microsoft.Test.OData.Services.AstoriaDefaultService.Aliases");
    topelement.appendChild(contactAlias);

    final Element altNames2 = doc.createElement("d:AlternativeNames");
    altNames2.setAttribute("m:type", "Collection(Edm.String)");
    contactAlias.appendChild(altNames2);

    final Element element3 = doc.createElement("d:element");
    element3.setAttribute("m:type", "Edm.String");
    element3.appendChild(doc.createTextNode("myAlternativeName"));
    altNames2.appendChild(element3);

    final StringWriter writer = new StringWriter();

    final DOMImplementationRegistry reg = DOMImplementationRegistry.newInstance();
    final DOMImplementationLS impl = (DOMImplementationLS) reg.getDOMImplementation("LS");
    final LSSerializer serializer = impl.createLSSerializer();
    final LSOutput lso = impl.createLSOutput();
    lso.setCharacterStream(writer);
    serializer.write(doc, lso);

    assertFalse(writer.toString().isEmpty());
}