Example usage for org.jdom2 Document Document

List of usage examples for org.jdom2 Document Document

Introduction

In this page you can find the example usage for org.jdom2 Document Document.

Prototype

public Document() 

Source Link

Document

Creates a new empty document.

Usage

From source file:ca.nrc.cadc.tap.writer.RssTableWriter.java

License:Open Source License

@Override
public void write(ResultSet resultSet, Writer out, Long maxrec) throws IOException {
    if (selectList == null)
        throw new IllegalStateException("SelectList cannot be null, set using setSelectList()");

    List<Format<Object>> formats = formatFactory.getFormats(selectList);

    if (resultSet != null)
        try {/*from w  ww .ja va2 s . c o m*/
            log.debug("resultSet column count: " + resultSet.getMetaData().getColumnCount());
        } catch (Exception oops) {
            log.error("failed to check resultset column count", oops);
        }

    // JDOM document.
    Document document = new Document();

    // Root element.
    Element rss = new Element("rss");
    rss.setAttribute("version", "2.0");
    document.setRootElement(rss);

    // channel element.
    Element channel = new Element("channel");
    rss.addContent(channel);

    // channel title.
    Element channelTitle = new Element("title");
    channelTitle.setText(info);
    channel.addContent(channelTitle);

    StringBuilder qp = new StringBuilder();
    qp.append("http://");
    qp.append(NetUtil.getServerName(null));
    qp.append(job.getRequestPath());
    qp.append("?");
    for (Parameter parameter : job.getParameterList()) {
        qp.append(parameter.getName());
        qp.append("=");
        qp.append(parameter.getValue());
        qp.append("&");
    }
    String queryString = qp.substring(0, qp.length() - 1); // strip trailing &
    Element link = new Element("link");
    link.setText(queryString);
    channel.addContent(link);

    // items.
    int itemCount = 0;
    try {
        while (resultSet.next()) {
            // item element.
            Element item = new Element("item");

            // item description.
            Element itemDescription = new Element("description");
            StringBuilder sb = new StringBuilder();
            sb.append("<table>");

            // Loop through the ResultSet adding the table data elements.
            for (int columnIndex = 1; columnIndex <= resultSet.getMetaData().getColumnCount(); columnIndex++) {
                String columnLabel = resultSet.getMetaData().getColumnLabel(columnIndex);

                if (columnLabel.equalsIgnoreCase("rss_title")) {
                    String titleStr = resultSet.getString("rss_title");
                    log.debug("item title: " + titleStr);
                    Element itemTitle = new Element("title");
                    itemTitle.setText(titleStr);
                    item.addContent(itemTitle);
                } else if (columnLabel.equalsIgnoreCase("rss_link")) {
                    String linkStr = resultSet.getString("rss_link");
                    log.debug("item link: " + linkStr);
                    Element itemLink = new Element("link");
                    itemLink.setText(linkStr);
                    item.addContent(itemLink);
                } else if (columnLabel.equalsIgnoreCase("rss_pubDate")) {
                    Timestamp ts = resultSet.getTimestamp("rss_pubDate");
                    String pubDateStr = dateFormat.format(ts);
                    log.debug("item pubDate: " + pubDateStr);
                    Element itemPubDate = new Element("pubDate");
                    itemPubDate.setText(pubDateStr);
                    item.addContent(itemPubDate);
                } else {
                    ParamDesc paramDesc = selectList.get(columnIndex - 1);
                    sb.append("<tr><td align=\"right\">");
                    sb.append(paramDesc.name);
                    sb.append("</td><td align=\"left\">");
                    Format<Object> format = formats.get(columnIndex - 1);
                    Object obj = null;
                    if (format instanceof ResultSetFormat)
                        obj = ((ResultSetFormat) format).extract(resultSet, columnIndex);
                    else
                        obj = resultSet.getObject(columnIndex);
                    sb.append(format.format(obj));
                    sb.append("</td></tr>");
                }
            }
            sb.append("</table>");
            itemDescription.setText(sb.toString());
            item.addContent(itemDescription);
            channel.addContent(item);
            itemCount++;

            // Write MaxRows
            if (itemCount == maxrec)
                break;
        }
    } catch (SQLException e) {
        throw new RuntimeException(e.getMessage());
    }

    // channel description.
    Element channelDescription = new Element("description");
    channelDescription.setText("The " + itemCount + " most recent from " + info);
    channel.addContent(channelDescription);

    // Write out the VOTABLE.
    XMLOutputter outputter = new XMLOutputter(org.jdom2.output.Format.getPrettyFormat());
    outputter.output(document, out);

}

From source file:ca.nrc.cadc.uws.web.restlet.resources.UWSResource.java

License:Open Source License

/**
 * Obtain the XML Representation of this Request.
 *
 * @return      The XML Representation, fully populated.
 *//*from   w ww  . jav a  2s. co m*/
@Get
public Representation represent() {
    try {
        Document document = new Document();
        buildXML(document);
        return new JDOMRepresentation(MediaType.TEXT_XML, document);
    } catch (final IOException e) {
        setExisting(false);
        LOGGER.error("Unable to create XML Document.");
        throw new WebRepresentationException("Unable to create XML Document.", e);
    }

}

From source file:ca.nrc.cadc.vos.server.RssView.java

License:Open Source License

/**
 * Write to root Element to a writer.//ww w  .j ava 2s .  com
 *
 * @param root Root Element to write.
 * @param writer Writer to write to.
 * @throws IOException if the writer fails to write.
 */
protected void write(Element root, Writer writer) throws IOException {
    XMLOutputter outputter = new XMLOutputter();
    outputter.setFormat(Format.getPrettyFormat());
    Document document = new Document();
    root.detach();
    document.setRootElement(root);
    outputter.output(document, writer);
}

From source file:ca.nrc.cadc.vosi.Availability.java

License:Open Source License

public Document toXmlDocument() {
    DateFormat df = DateUtil.getDateFormat(DateUtil.IVOA_DATE_FORMAT, DateUtil.UTC);
    Namespace vosi = Namespace.getNamespace("vosi", VOSI.AVAILABILITY_NS_URI);

    Element eleAvailability = new Element("availability", vosi);

    Util.addChild(eleAvailability, vosi, "available", Boolean.toString(_status.isAvailable()));
    if (_status.getUpSince() != null)
        Util.addChild(eleAvailability, vosi, "upSince", df.format(_status.getUpSince()));
    if (_status.getDownAt() != null)
        Util.addChild(eleAvailability, vosi, "downAt", df.format(_status.getDownAt()));
    if (_status.getBackAt() != null)
        Util.addChild(eleAvailability, vosi, "backAt", df.format(_status.getBackAt()));
    if (_status.getNote() != null)
        Util.addChild(eleAvailability, vosi, "note", _status.getNote());

    Document document = new Document();
    document.addContent(eleAvailability);

    return document;
}

From source file:ca.nrc.cadc.vosi.Capabilities.java

License:Open Source License

public Document toXmlDocument() {
    Namespace xsi = Namespace.getNamespace("xsi", VOSI.XSI_NS_URI);
    Namespace cap = Namespace.getNamespace("vosi", VOSI.CAPABILITIES_NS_URI);
    Namespace vod = Namespace.getNamespace("vod", VOSI.VODATASERVICE_NS_URI);

    Element eleCapabilities = new Element("capabilities", cap);
    eleCapabilities.addNamespaceDeclaration(xsi);
    eleCapabilities.addNamespaceDeclaration(cap);
    eleCapabilities.addNamespaceDeclaration(vod);

    //Attribute attSchemaLocation = new Attribute("schemaLocation", XSI_LOC, xsi);
    //eleCapabilities.setAttribute(attSchemaLocation);

    Document document = new Document();
    document.addContent(eleCapabilities);

    for (Capability capability : this._caps) {
        eleCapabilities.addContent(capability.toXmlElement(xsi, cap, vod));
    }//from  w ww . ja  va  2  s.co m
    return document;
}

From source file:ca.nrc.cadc.vosi.TableSet.java

License:Open Source License

/**
 * Get a single Table document.//from w ww  . j a  v a  2  s.c om
 * 
 * @param root root element for document
 * @return the TapSchema as a document to be rendered as XML
 */
protected Document getDocument(Element root) {
    root.addNamespaceDeclaration(xsi);
    root.addNamespaceDeclaration(vod);

    // ivoa convention but not allowed by the VODataService schema
    //root.setAttribute("version", "1.1");

    Document document = new Document();
    document.addContent(root);
    return document;
}

From source file:ca.nrc.cadc.xml.JsonInputter.java

License:Open Source License

public Document input(final String json) throws JSONException {
    JSONObject rootJson = new JSONObject(json);
    List<String> keys = Arrays.asList(JSONObject.getNames(rootJson));
    List<Namespace> namespaces = new ArrayList<Namespace>();
    Namespace namespace = getNamespace(namespaces, rootJson, keys);

    String rootKey = null;//from  w  ww.jav  a2  s  . com
    List<Attribute> attributes = new ArrayList<Attribute>();
    for (String key : keys) {
        if (!key.startsWith("@xmlns")) {
            if (key.startsWith("@")) {
                String value;
                if (rootJson.isNull(key)) {
                    value = "";
                } else {
                    value = getStringValue(rootJson.get(key));
                }
                attributes.add(new Attribute(key.substring(1), value));
            } else {
                // DOM can only have one root element.
                if (rootKey != null) {
                    throw new IllegalStateException("Found multiple root entries");
                }
                rootKey = key;
            }
        }
    }

    Element rootElement = new Element(rootKey, namespace);
    for (Attribute attribute : attributes) {
        rootElement.setAttribute(attribute);
    }

    Object value = rootJson.get(rootKey);
    processObject(rootKey, value, rootElement, namespace, namespaces);

    Document document = new Document();
    document.setRootElement(rootElement);
    return document;
}

From source file:cager.parser.test.SimpleTest2.java

License:Open Source License

private String elementoToString(Element segmento) {

    Document documentJDOM = new Document();
    documentJDOM.addContent(segmento);/*from ww w  . j  ava2  s  . com*/
    // Vamos a serializar el XML  
    // Lo primero es obtener el formato de salida  
    // Partimos del "Formato bonito", aunque tambin existe el plano y el compacto  
    Format format = Format.getPrettyFormat();
    // Creamos el serializador con el formato deseado  
    XMLOutputter xmloutputter = new XMLOutputter(format);
    // Serializamos el document parseado  
    String docStr = xmloutputter.outputString(documentJDOM);

    FileOutputStream fout;
    try {
        fout = new FileOutputStream(ruta + "VBParser\\ejemplosKDM\\archivo.kdm");
        //fout = new FileOutputStream("E:\\WorkspaceParser\\VBParser\\ejemplosKDM\\archivo.kdm");
        xmloutputter.output(documentJDOM, fout);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return docStr;
}

From source file:cager.parser.test.SimpleTest3.java

License:Open Source License

private String elementoToString(Element segmento) {

    Document documentJDOM = new Document();
    documentJDOM.addContent(segmento);/* w w w. j  av a 2s  . c  o  m*/
    // Vamos a serializar el XML  
    // Lo primero es obtener el formato de salida  
    // Partimos del "Formato bonito", aunque tambin existe el plano y el compacto  
    Format format = Format.getPrettyFormat();
    // Creamos el serializador con el formato deseado  
    XMLOutputter xmloutputter = new XMLOutputter(format);
    // Serializamos el document parseado  
    String docStr = xmloutputter.outputString(documentJDOM);

    FileOutputStream fout;
    try {
        fout = new FileOutputStream(ruta + "VBParser\\ejemplosKDM\\archivo.kdm");
        //fout = new FileOutputStream("E:\\WorkspaceParser\\VBParser\\ejemplosKDM\\archivo.kdm");
        xmloutputter.output(documentJDOM, fout);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return docStr;
}

From source file:com.archimatetool.canvas.templates.wizard.SaveCanvasAsTemplateWizard.java

License:Open Source License

private String createManifest() throws IOException {
    Document doc = new Document();
    Element root = new Element(ITemplateXMLTags.XML_TEMPLATE_ELEMENT_MANIFEST);
    doc.setRootElement(root);//from w  ww .  j a  v  a 2 s.com

    // Type
    root.setAttribute(ITemplateXMLTags.XML_TEMPLATE_ATTRIBUTE_TYPE,
            CanvasModelTemplate.XML_CANVAS_TEMPLATE_ATTRIBUTE_TYPE_MODEL);

    // Timestamp
    root.setAttribute(ITemplateXMLTags.XML_TEMPLATE_ATTRIBUTE_TIMESTAMP,
            Long.toString(System.currentTimeMillis()));

    // Name
    Element elementName = new Element(ITemplateXMLTags.XML_TEMPLATE_ELEMENT_NAME);
    elementName.setText(fTemplateName);
    root.addContent(elementName);

    // Description
    Element elementDescription = new Element(ITemplateXMLTags.XML_TEMPLATE_ELEMENT_DESCRIPTION);
    elementDescription.setText(fTemplateDescription);
    root.addContent(elementDescription);

    // Thumbnail
    if (fIncludeThumbnail) {
        String keyThumb = TemplateManager.ZIP_ENTRY_THUMBNAILS + "1.png"; //$NON-NLS-1$
        Element elementKeyThumb = new Element(ITemplateXMLTags.XML_TEMPLATE_ELEMENT_KEY_THUMBNAIL);
        elementKeyThumb.setText(keyThumb);
        root.addContent(elementKeyThumb);
    }

    return JDOMUtils.write2XMLString(doc);
}