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:com.github.cat.yum.store.util.YumUtil.java

private static RepoModule createPrimary(RpmData[] rpmdatas, String rootPath)
        throws IOException, NoSuchAlgorithmException {
    RepoModule repo = new RepoModule(rootPath, "primary");
    Document doc = new Document();
    Element root = new Element("metadata", COMMONNAMESPACE);
    doc.addContent(root);//from  w  w w.  j a va2  s.  c om
    root.addNamespaceDeclaration(RPMNAMESPACE);
    root.setAttribute("packages", rpmdatas.length + "");

    for (RpmData rpmdata : rpmdatas) {
        RpmMetadata rpmMetadata = rpmdata.rpmMetadata;

        Element packAge = new Element("package", COMMONNAMESPACE);
        packAge.setAttribute("type", "rpm");
        root.addContent(packAge);

        Element name = new Element("name", COMMONNAMESPACE);
        name.setText(rpmMetadata.name);
        packAge.addContent(name);

        Element arch = new Element("arch", COMMONNAMESPACE);
        arch.setText(rpmMetadata.architecture);
        packAge.addContent(arch);

        Element version = new Element("version", COMMONNAMESPACE);
        version.setAttribute("epoch", rpmMetadata.epoch + "");
        version.setAttribute("ver", rpmMetadata.version);
        version.setAttribute("rel", rpmMetadata.release);
        packAge.addContent(version);

        Element checksum = new Element("checksum", COMMONNAMESPACE);
        checksum.setAttribute("type", ALGORITHM);
        checksum.setAttribute("pkgid", "YES");
        checksum.setText(HashFile.getsum(rpmdata.rpm, ALGORITHM));
        packAge.addContent(checksum);

        Element summary = new Element("summary", COMMONNAMESPACE);
        summary.setText(rpmMetadata.summary);
        packAge.addContent(summary);

        Element description = new Element("description", COMMONNAMESPACE);
        description.setText(rpmMetadata.description);
        packAge.addContent(description);

        Element packager = new Element("packager", COMMONNAMESPACE);
        packager.setText(rpmMetadata.packager);
        packAge.addContent(packager);

        Element url = new Element("url", COMMONNAMESPACE);
        url.setText(rpmMetadata.url);
        packAge.addContent(url);

        Element time = new Element("time", COMMONNAMESPACE);
        time.setAttribute("file", rpmdata.rpm.lastModified() / 1000 + "");
        time.setAttribute("build", rpmMetadata.buildTime + "");
        packAge.addContent(time);

        Element size = new Element("size", COMMONNAMESPACE);
        size.setAttribute("package", rpmdata.rpm.length() + "");
        size.setAttribute("installed", rpmMetadata.installedSize + "");
        size.setAttribute("archive", rpmMetadata.archiveSize + "");
        packAge.addContent(size);

        Element location = new Element("location", COMMONNAMESPACE);
        location.setAttribute("href", replacePath(FileUtils.getFileRelativePath(rootPath, rpmdata.rpm)));
        packAge.addContent(location);

        Element format = new Element("format", COMMONNAMESPACE);
        packAge.addContent(format);

        Element license = new Element("license", RPMNAMESPACE);
        license.setText(rpmMetadata.license);
        format.addContent(license);

        Element vendor = new Element("vendor", RPMNAMESPACE);
        vendor.setText(rpmMetadata.vendor);
        format.addContent(vendor);

        Element group = new Element("group", RPMNAMESPACE);
        group.setText(rpmMetadata.group);
        format.addContent(group);

        Element buildhost = new Element("buildhost", RPMNAMESPACE);
        buildhost.setText(rpmMetadata.buildHost);
        format.addContent(buildhost);

        Element sourcerpm = new Element("sourcerpm", RPMNAMESPACE);
        sourcerpm.setText(rpmMetadata.sourceRpm);
        format.addContent(sourcerpm);

        Element headerRange = new Element("header-range", RPMNAMESPACE);
        headerRange.setAttribute("start", rpmMetadata.headerStart + "");
        headerRange.setAttribute("end", rpmMetadata.headerEnd + "");
        format.addContent(headerRange);

        Element provides = new Element("provides", RPMNAMESPACE);
        format.addContent(provides);
        addEntry(provides, rpmMetadata.provide, null);

        Element requires = new Element("requires", RPMNAMESPACE);
        format.addContent(requires);
        addEntry(requires, rpmMetadata.require, new PrivateRequireFilter());

        Element conflicts = new Element("conflicts", RPMNAMESPACE);
        format.addContent(conflicts);
        addEntry(conflicts, rpmMetadata.conflict, null);

        Element obsoletes = new Element("obsoletes", RPMNAMESPACE);
        format.addContent(obsoletes);
        addEntry(obsoletes, rpmMetadata.obsolete, null);

        YumFileter fileflter = new PrivateFileFilter();
        YumFileter fileDirflter = new PrivateFileDirFilter();
        for (com.github.cat.yum.store.model.File file : rpmMetadata.files) {
            if (StringUtils.isBlank(file.type)) {
                if (fileflter.filter(file.path)) {
                    continue;
                }
            } else if ("dir".equals(file.type)) {
                if (fileDirflter.filter(file.path)) {
                    continue;
                }
            }

            Element fileElemenrt = new Element("file", COMMONNAMESPACE);
            fileElemenrt.setText(file.path);
            if (!StringUtils.isBlank(file.type)) {
                fileElemenrt.setAttribute("type", file.type);
            }
            format.addContent(fileElemenrt);
        }
    }
    yumXmlSave(doc, repo);
    return repo;
}

From source file:com.github.cat.yum.store.util.YumUtil.java

private static RepoModule createFilelitsts(RpmData[] rpmdatas, String rootPath)
        throws IOException, NoSuchAlgorithmException {
    RepoModule repo = new RepoModule(rootPath, "filelists");
    Document doc = new Document();
    Element root = new Element("filelists", FILELISTSNAMESPACE);
    doc.addContent(root);/*from   ww  w .ja va  2  s.c  o m*/
    root.setAttribute("packages", rpmdatas.length + "");

    for (RpmData rpmdata : rpmdatas) {
        RpmMetadata rpmMetadata = rpmdata.rpmMetadata;

        Element packAge = new Element("package", FILELISTSNAMESPACE);
        packAge.setAttribute("pkgid", HashFile.getsum(rpmdata.rpm, ALGORITHM));
        packAge.setAttribute("name", rpmMetadata.name);
        packAge.setAttribute("arch", rpmMetadata.architecture);
        root.addContent(packAge);

        Element version = new Element("version", FILELISTSNAMESPACE);
        version.setAttribute("epoch", rpmMetadata.epoch + "");
        version.setAttribute("ver", rpmMetadata.version);
        version.setAttribute("rel", rpmMetadata.release);
        packAge.setContent(version);

        for (com.github.cat.yum.store.model.File file : rpmMetadata.files) {
            Element fileElement = new Element("file", FILELISTSNAMESPACE);
            fileElement.setText(file.path);
            if (file.type != null) {
                fileElement.setAttribute("type", file.type);
            }
            packAge.addContent(fileElement);
        }
    }
    yumXmlSave(doc, repo);
    return repo;
}

From source file:com.init.octo.schema.XSDSchema.java

License:Open Source License

public void initDoc() {
    buildDocument = new Document();

    if (schemaDefined == false) {
        root = null;/*from w  w  w  .  j a  va  2s.c o  m*/
    }

    if (root != null) {
        buildDocument.setRootElement(new Element(schemaRoot != null ? schemaRoot : root.getName()));
    } else {
        /* else no proper root element was defined in the schema and we make a duff one to stop */
        /* a future exception...                                                                */
        buildDocument.setRootElement(new Element(schemaRoot != null ? schemaRoot : "root"));
    }

    elementPath = new Element[100];
    schemaPath = new XSDElement[100];
    // newTrigger     = new String[100];
    newTrigger = new HashMap<String, Boolean>();

    firstCall = true;
}

From source file:com.izforge.izpack.util.xmlmerge.merge.DefaultXmlMerge.java

License:Open Source License

/**
 * Performs the actual merge./*  w  w  w. ja va2  s. com*/
 *
 * @param docs The documents to merge. The first doc is assumed to be the original one to apply patches against.
 * @return The merged result document
 * @throws AbstractXmlMergeException If an error occurred during the merge
 */
private Document doMerge(Document[] docs) throws AbstractXmlMergeException {
    Document originalDoc = docs[0];
    Element origRootElement = originalDoc.getRootElement();

    for (int i = 1; i < docs.length; i++) {
        Element comparedRootElement = docs[i].getRootElement();

        Document output = new Document();
        if (originalDoc.getDocType() != null) {
            output.setDocType((DocType) originalDoc.getDocType().clone());
        }
        output.setRootElement(new Element("root"));
        Element outputRootElement = output.getRootElement();

        m_rootMergeAction.perform(origRootElement, comparedRootElement, outputRootElement);

        Element root = (Element) outputRootElement.getChildren().get(0);
        root.detach();

        sortRootChildrenRecursive(root);

        originalDoc.setRootElement(root);
    }

    return originalDoc;
}

From source file:com.js.quickestquail.server.ViewAllMoviesHandler.java

private void buildXML() {
    Element rootElement = new Element("movies");

    for (Entry<File, String> en : DriveManager.get().getSelected().entrySet()) {
        Movie mov = CachedMovieProvider.get().getMovieByID(en.getValue());

        Element movieElement = new Element("movie");

        movieElement.addContent(makeElement("imdbid", mov.getImdbID()));
        movieElement.addContent(makeElement("imdbrating", mov.getImdbRating() + ""));
        movieElement.addContent(makeElement("imdbvotes", mov.getImdbVotes() + ""));

        movieElement.addContent(makeElement("title", mov.getTitle()));
        movieElement.addContent(makeElement("year", mov.getYear() + ""));
        movieElement.addContent(makeElement("countries", "country", mov.getCountry()));
        movieElement.addContent(makeElement("genres", "genre", mov.getGenre()));

        movieElement.addContent(makeElement("writers", "writer", mov.getWriter()));
        movieElement.addContent(makeElement("directors", "director", mov.getDirector()));
        movieElement.addContent(makeElement("actors", "actor", mov.getActors()));

        movieElement.addContent(makeElement("poster", mov.getPoster()));

        movieElement.addContent(makeElement("plot", mov.getPlot()));

        movieElement.addContent(makeElement("file", en.getKey().getAbsolutePath()));

        rootElement.addContent(movieElement);
    }//from  ww w  .j ava 2s .  c  om

    Document doc = new Document();
    doc.setRootElement(rootElement);

    XMLOutputter xmlOutput = new XMLOutputter();
    xmlOutput.setFormat(Format.getPrettyFormat());

    try {
        if (!rootDir.exists())
            rootDir.mkdirs();
        xmlOutput.output(doc, new FileWriter(xmlSourceFile));
    } catch (IOException ex) {
        Logger.getLogger(ViewAllMoviesHandler.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.js.quickestquail.ui.actions.io.ExportToXMLAction.java

private void writeAll(File outputFile) {

    // progress dialog
    JProgressDialog dialog = new JProgressDialog(UI.get(), false);
    dialog.setMaximum(DriveManager.get().getSelected().size());
    dialog.setTitle(java.util.ResourceBundle.getBundle("i18n/i18n").getString("export.xml"));
    dialog.setVisible(true);/*  ww  w . j  a  v  a  2  s.  c  o  m*/

    // process in new thread
    new Thread() {
        @Override
        public void run() {
            try {
                Element rootElement = new Element("movies");

                List<Entry<File, String>> entries = new ArrayList<>(
                        DriveManager.get().getSelected().entrySet());
                java.util.Collections.sort(entries, new Comparator<Entry<File, String>>() {
                    @Override
                    public int compare(Entry<File, String> o1, Entry<File, String> o2) {
                        Movie mov1 = CachedMovieProvider.get().getMovieByID(o1.getValue());
                        Movie mov2 = CachedMovieProvider.get().getMovieByID(o2.getValue());
                        return mov1.getTitle().compareTo(mov2.getTitle());
                    }
                });

                int nofMovies = 0;
                for (Entry<File, String> en : entries) {
                    Movie mov = CachedMovieProvider.get().getMovieByID(en.getValue());

                    // update progress dialog
                    dialog.setText(mov.getTitle());
                    dialog.setProgress(nofMovies);

                    Element movieElement = new Element("movie");

                    movieElement.addContent(makeElement("imdbid", mov.getImdbID()));
                    movieElement.addContent(makeElement("imdbrating", mov.getImdbRating() + ""));
                    movieElement.addContent(makeElement("imdbvotes", mov.getImdbVotes() + ""));

                    movieElement.addContent(makeElement("title", mov.getTitle()));
                    movieElement.addContent(makeElement("year", mov.getYear() + ""));
                    movieElement.addContent(makeElement("countries", "country", mov.getCountry()));
                    movieElement.addContent(makeElement("genres", "genre", mov.getGenre()));

                    movieElement.addContent(makeElement("writers", "writer", mov.getWriter()));
                    movieElement.addContent(makeElement("directors", "director", mov.getDirector()));
                    movieElement.addContent(makeElement("actors", "actor", mov.getActors()));

                    movieElement.addContent(makeElement("poster", mov.getPoster()));

                    movieElement.addContent(makeElement("plot", mov.getPlot()));

                    movieElement.addContent(makeElement("file", en.getKey().getAbsolutePath()));

                    rootElement.addContent(movieElement);

                    nofMovies++;
                }

                Document doc = new Document();
                doc.setRootElement(rootElement);

                // close IO
                XMLOutputter xmlOutput = new XMLOutputter();
                xmlOutput.setFormat(Format.getPrettyFormat());
                xmlOutput.output(doc, new FileWriter(outputFile));

                // close dialog
                dialog.setVisible(false);

            } catch (Exception ex) {
            }
        }
    }.start();
}

From source file:com.rometools.opml.io.impl.OPML10Generator.java

License:Apache License

/**
 * Creates an XML document (JDOM) for the given feed bean.
 *
 * @param feed the feed bean to generate the XML document from.
 * @return the generated XML document (JDOM).
 * @throws IllegalArgumentException thrown if the type of the given feed bean does not match with the type of the
 *             WireFeedGenerator.//w  ww  . j av a  2  s. co m
 * @throws FeedException thrown if the XML Document could not be created.
 */
@Override
public Document generate(final WireFeed feed) throws IllegalArgumentException, FeedException {

    if (!(feed instanceof Opml)) {
        throw new IllegalArgumentException("Not an OPML file");
    }

    final Opml opml = (Opml) feed;
    final Document doc = new Document();
    final Element root = new Element("opml");
    root.setAttribute("version", "1.0");
    doc.addContent(root);

    final Element head = generateHead(opml);

    if (head != null) {
        root.addContent(head);
    }

    final Element body = new Element("body");
    root.addContent(body);
    super.generateFeedModules(opml.getModules(), root);
    body.addContent(generateOutlines(opml.getOutlines()));

    return doc;
}

From source file:com.rometools.propono.atom.common.AtomService.java

License:Apache License

/**
 * Serialize an AtomService object into an XML document
 *//*from   w w  w  . ja v a  2s .c  o  m*/
public Document serviceToDocument() {
    final AtomService service = this;

    final Document doc = new Document();
    final Element root = new Element("service", ATOM_PROTOCOL);
    doc.setRootElement(root);
    final List<Workspace> spaces = service.getWorkspaces();
    for (final Workspace space : spaces) {
        root.addContent(space.workspaceToElement());
    }
    return doc;
}

From source file:com.rometools.propono.atom.server.AtomServlet.java

License:Apache License

/**
 * Handles an Atom GET by calling handler and writing results to response.
 *//*  ww w  . ja  v  a 2 s  .  com*/
@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse res)
        throws ServletException, IOException {
    LOG.debug("Entering");
    final AtomHandler handler = createAtomRequestHandler(req, res);
    final String userName = handler.getAuthenticatedUsername();
    if (userName != null) {
        final AtomRequest areq = new AtomRequestImpl(req);
        try {
            if (handler.isAtomServiceURI(areq)) {
                // return an Atom Service document
                final AtomService service = handler.getAtomService(areq);
                final Document doc = service.serviceToDocument();
                res.setContentType("application/atomsvc+xml; charset=utf-8");
                final Writer writer = res.getWriter();
                final XMLOutputter outputter = new XMLOutputter();
                outputter.setFormat(Format.getPrettyFormat());
                outputter.output(doc, writer);
                writer.close();
                res.setStatus(HttpServletResponse.SC_OK);
            } else if (handler.isCategoriesURI(areq)) {
                final Categories cats = handler.getCategories(areq);
                res.setContentType("application/xml");
                final Writer writer = res.getWriter();
                final Document catsDoc = new Document();
                catsDoc.setRootElement(cats.categoriesToElement());
                final XMLOutputter outputter = new XMLOutputter();
                outputter.output(catsDoc, writer);
                writer.close();
                res.setStatus(HttpServletResponse.SC_OK);
            } else if (handler.isCollectionURI(areq)) {
                // return a collection
                final Feed col = handler.getCollection(areq);
                col.setFeedType(FEED_TYPE);
                final WireFeedOutput wireFeedOutput = new WireFeedOutput();
                final Document feedDoc = wireFeedOutput.outputJDom(col);
                res.setContentType("application/atom+xml; charset=utf-8");
                final Writer writer = res.getWriter();
                final XMLOutputter outputter = new XMLOutputter();
                outputter.setFormat(Format.getPrettyFormat());
                outputter.output(feedDoc, writer);
                writer.close();
                res.setStatus(HttpServletResponse.SC_OK);
            } else if (handler.isEntryURI(areq)) {
                // return an entry
                final Entry entry = handler.getEntry(areq);
                if (entry != null) {
                    res.setContentType("application/atom+xml; type=entry; charset=utf-8");
                    final Writer writer = res.getWriter();
                    Atom10Generator.serializeEntry(entry, writer);
                    writer.close();
                } else {
                    res.setStatus(HttpServletResponse.SC_NOT_FOUND);
                }
            } else if (handler.isMediaEditURI(areq)) {
                final AtomMediaResource entry = handler.getMediaResource(areq);
                res.setContentType(entry.getContentType());
                res.setContentLength((int) entry.getContentLength());
                Utilities.copyInputToOutput(entry.getInputStream(), res.getOutputStream());
                res.getOutputStream().flush();
                res.getOutputStream().close();
            } else {
                res.setStatus(HttpServletResponse.SC_NOT_FOUND);
            }
        } catch (final AtomException ae) {
            res.sendError(ae.getStatus(), ae.getMessage());
            LOG.debug("An error occured while processing GET", ae);
        } catch (final Exception e) {
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
            LOG.debug("An error occured while processing GET", e);
        }
    } else {
        res.setHeader("WWW-Authenticate", "BASIC realm=\"AtomPub\"");
        res.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    }
    LOG.debug("Exiting");
}

From source file:com.rometools.rome.io.impl.OPML10Generator.java

License:Apache License

/**
 * Creates an XML document (JDOM) for the given feed bean.
 * <p>//from   ww  w  .  j av  a  2  s.co  m
 *
 * @param feed the feed bean to generate the XML document from.
 * @return the generated XML document (JDOM).
 * @throws IllegalArgumentException thrown if the type of the given feed bean does not match
 *             with the type of the WireFeedGenerator.
 * @throws FeedException thrown if the XML Document could not be created.
 */
@Override
public Document generate(final WireFeed feed) throws IllegalArgumentException, FeedException {
    if (!(feed instanceof Opml)) {
        throw new IllegalArgumentException("Not an OPML file");
    }

    final Opml opml = (Opml) feed;
    final Document doc = new Document();
    final Element root = new Element("opml");
    doc.addContent(root);

    final Element head = generateHead(opml);

    if (head != null) {
        root.addContent(head);
    }

    final Element body = new Element("body");
    root.addContent(body);
    super.generateFeedModules(opml.getModules(), root);
    body.addContent(generateOutlines(opml.getOutlines()));

    return doc;
}