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(List<? extends Content> content) 

Source Link

Document

This will create a new Document, with the supplied list of content, and a DocType declaration only if the content contains a DocType instance.

Usage

From source file:org.mycore.frontend.cli.MCRAccessCommands.java

License:Open Source License

/**
 * This method just export the permissions to a file
 * //from  w  w w  .ja  v a2  s  .c o  m
 * @param filename
 *            the file written to
 */
@MCRCommand(syntax = "export all permissions to file {0}", help = "Export all permissions from the Access Control System to the file {0}.", order = 50)
public static void exportAllPermissionsToFile(String filename) throws Exception {
    MCRAccessInterface AI = MCRAccessManager.getAccessImpl();

    Element mcrpermissions = new Element("mcrpermissions");
    mcrpermissions.addNamespaceDeclaration(XSI_NAMESPACE);
    mcrpermissions.addNamespaceDeclaration(XLINK_NAMESPACE);
    mcrpermissions.setAttribute("noNamespaceSchemaLocation", "MCRPermissions.xsd", XSI_NAMESPACE);
    Document doc = new Document(mcrpermissions);
    Collection<String> permissions = AI.getPermissions();
    for (String permission : permissions) {
        Element mcrpermission = new Element("mcrpermission");
        mcrpermission.setAttribute("name", permission);
        String ruleDescription = AI.getRuleDescription(permission);
        if (!ruleDescription.equals("")) {
            mcrpermission.setAttribute("ruledescription", ruleDescription);
        }
        Element rule = AI.getRule(permission);
        mcrpermission.addContent(rule);
        mcrpermissions.addContent(mcrpermission);
    }
    File file = new File(filename);
    if (file.exists()) {
        LOGGER.warn("File " + filename + " yet exists, overwrite.");
    }
    FileOutputStream fos = new FileOutputStream(file);
    LOGGER.info("Writing to file " + filename + " ...");
    String mcr_encoding = CONFIG.getString("MCR.Metadata.DefaultEncoding", DEFAULT_ENCODING);
    XMLOutputter out = new XMLOutputter(Format.getPrettyFormat().setEncoding(mcr_encoding));
    out.output(doc, fos);
}

From source file:org.mycore.frontend.editor.MCREditorDefReader.java

License:Open Source License

private void validate(String uri, String ref) {
    if (ref != null && ref.length() > 0) {
        uri += "#" + ref;
    }/*from ww w  .jav a2s.  com*/
    LOGGER.info("Validating editor " + uri + "...");

    Document doc = new Document(editor);
    editor.setAttribute("noNamespaceSchemaLocation", "editor.xsd", MCRConstants.XSI_NAMESPACE);

    try {
        MCRXMLParserFactory.getValidatingParser().parseXML(new MCRJDOMContent(doc));
    } catch (Exception ex) {
        String msg = "Error validating editor " + uri;
        LOGGER.error(msg);
        throw new MCRConfigurationException(msg, ex);
    }

    editor.detach();
    editor.removeAttribute("noNamespaceSchemaLocation", MCRConstants.XSI_NAMESPACE);
    LOGGER.info("Validation succeeded.");
}

From source file:org.mycore.frontend.editor.MCREditorSubmission.java

License:Open Source License

private void buildTargetXML() {
    Element root;/*from  ww w. j  a v a2  s  . c o m*/
    if (variables.size() > 0) {
        root = buildElement(((MCREditorVariable) variables.get(0)).getPathElements()[0]);
    } else {
        root = buildElement(rootName.replace("/", ""));
    }

    for (Object variable : variables) {
        MCREditorVariable var = (MCREditorVariable) variable;

        Element parent = root;
        String[] elements = var.getPathElements();

        for (int j = 1; j < elements.length; j++) {
            String name = elements[j];

            if (name.endsWith("]")) {
                int pos = name.lastIndexOf("[");
                name = name.substring(0, pos) + "_XXX_" + name.substring(pos + 1, name.length() - 1);
            }

            Namespace ns = getNamespace(name);
            if (!ns.equals(Namespace.NO_NAMESPACE)) {
                name = name.substring(name.indexOf(":") + 1);
            }
            Element child = parent.getChild(name, ns);

            if (child == null) {
                child = new Element(name, ns);
                parent.addContent(child);
            }

            parent = child;
        }

        Object node;

        if (!var.isAttribute()) {
            parent.addContent(var.getValue());
            node = parent;
        } else {
            LOGGER.debug("Setting attribute " + var.getPath() + " = " + var.getValue());
            setAttribute(parent, var.getAttributeName(), var.getValue());
            node = parent.getAttribute(var.getAttributeName());
        }

        FileItem file = parms == null ? null : parms.getFileItem(var.getPath());

        if (file != null) {
            file2node.put(file, node);
            node2file.put(node, file);
        }
    }

    renameRepeatedElements(root);
    xml = new Document(root);
}

From source file:org.mycore.frontend.export.MCRExportCollection.java

License:Open Source License

public MCRExportCollection() {
    collection = new Element("exportCollection");
    new Document(collection);
}

From source file:org.mycore.frontend.indexbrowser.MCRGoogleSitemapCommon.java

License:Open Source License

/**
 * The method build the sitemap_google.xml JDOM document over all items.
 * //from   w ww  .j  av  a  2  s .c o  m
 * @return The sitemap_google.xml as JDOM document
 */
protected final Document buildSingleSitemap() throws Exception {
    LOGGER.debug("Build Google URL sitemap_google.xml for whole items.");
    // build document frame
    Element urlset = new Element("urlset", ns);
    urlset.addNamespaceDeclaration(XSI_NAMESPACE);
    urlset.setAttribute("noNamespaceSchemaLocation", SITEMAP_SCHEMA, XSI_NAMESPACE);
    Document jdom = new Document(urlset);
    // build over all types
    for (MCRObjectIDDate objectIDDate : objidlist) {
        urlset.addContent(buildURLElement(objectIDDate));
    }
    return jdom;
}

From source file:org.mycore.frontend.indexbrowser.MCRGoogleSitemapCommon.java

License:Open Source License

/**
 * The method call the database and build the sitemap_google.xml JDOM document.
 * /*from   w  ww  .  j a v a2 s .c  o  m*/
 * @param number
 *            number of this file - '1' = sitemap_google.xml - '&gt; 1' sitemap_google_xxx.xml
 * @return The sitemap.xml as JDOM document
 */
protected final Document buildPartSitemap(int number) throws Exception {
    LOGGER.debug("Build Google URL sitemap list number " + Integer.toString(number));
    // build document frame
    Element urlset = new Element("urlset", ns);
    urlset.addNamespaceDeclaration(XSI_NAMESPACE);
    urlset.setAttribute("schemaLocation", SITEMAP_SCHEMA, XSI_NAMESPACE);
    Document jdom = new Document(urlset);

    // build over all types
    int start = numberOfURLs * (number);
    int stop = numberOfURLs * (number + 1);
    if (stop > objidlist.size())
        stop = objidlist.size();
    LOGGER.debug("Build Google URL in range from " + Integer.toString(start) + " to "
            + Integer.toString(stop - 1) + ".");
    for (int i = start; i < stop; i++) {
        MCRObjectIDDate objectIDDate = objidlist.get(i);
        urlset.addContent(buildURLElement(objectIDDate));

    }
    return jdom;
}

From source file:org.mycore.frontend.indexbrowser.MCRGoogleSitemapCommon.java

License:Open Source License

/**
 * The method build the index sitemap_google.xml JDOM document.
 * /*from   www.j a  v a  2s.co m*/
 * @param number
 *            number of indexed files (must greater than 1
 * @return The index sitemap_google.xml as JDOM document
 */
protected final Document buildSitemapIndex(int number) {
    LOGGER.debug("Build Google sitemap number " + Integer.toString(number));
    // build document frame
    Element index = new Element("sitemapindex", ns);
    index.addNamespaceDeclaration(XSI_NAMESPACE);
    index.setAttribute("schemaLocation", SITEINDEX_SCHEMA, XSI_NAMESPACE);
    Document jdom = new Document(index);
    // build over all files
    for (int i = 0; i < number; i++) {
        Element sitemap = new Element("sitemap", ns);
        index.addContent(sitemap);
        StringBuilder sb = new StringBuilder(128);
        sb.append(baseurl).append(getFileName(i + 2, false));
        sitemap.addContent(new Element("loc", ns).addContent(sb.toString().trim()));
        String datestr = formatter.format((new GregorianCalendar(SITEMAP_TIMEZONE, SITEMAP_LOCALE)).getTime());
        sitemap.addContent(new Element("lastmod", ns).addContent(datestr.trim()));
    }
    return jdom;
}

From source file:org.mycore.frontend.xeditor.MCRXEditorTransformer.java

License:Open Source License

private void createEmptyDocumentFromXPath(String xPath) throws JaxenException, JDOMException {
    Element root = createRootElement(xPath);
    editorSession.setEditedXML(new Document(root));
    editorSession.setBreakpoint("Starting with empty XML document");
}

From source file:org.mycore.oai.classmapping.MCRClassificationMappingEventHandler.java

License:Open Source License

private void createMapping(MCRObject obj) {
    MCRMetaElement mappings = obj.getMetadata().getMetadataElement("mappings");
    if (mappings != null) {
        oldMappings = mappings.clone();//from ww  w . jav a  2  s  .  c o  m
        obj.getMetadata().removeMetadataElement("mappings");
    }

    Element currentClassElement = null;
    try {
        Document doc = new Document((Element) obj.getMetadata().createXML().detach());
        XPathExpression<Element> classElementPath = XPathFactory.instance().compile("//*[@categid]",
                Filters.element());
        List<Element> classList = classElementPath.evaluate(doc);
        if (classList.size() > 0) {
            mappings = new MCRMetaElement();
            mappings.setTag("mappings");
            mappings.setClass(MCRMetaClassification.class);
            mappings.setHeritable(false);
            mappings.setNotInherit(true);
            obj.getMetadata().setMetadataElement(mappings);
        }
        for (Element classElement : classList) {
            currentClassElement = classElement;
            MCRCategory categ = DAO.getCategory(new MCRCategoryID(classElement.getAttributeValue("classid"),
                    classElement.getAttributeValue("categid")), 0);
            addMappings(mappings, categ);
        }
    } catch (Exception je) {
        if (currentClassElement == null) {
            LOGGER.error("Error while finding classification elements", je);
        } else {
            LOGGER.error("Error while finding classification elements for "
                    + new XMLOutputter().outputString(currentClassElement), je);
        }
    } finally {
        if (mappings == null || mappings.size() == 0) {
            obj.getMetadata().removeMetadataElement("mappings");
        }
    }
}

From source file:org.mycore.oai.MCROAIDataProvider.java

License:Open Source License

@Override
protected void doGetPost(MCRServletJob job) throws Exception {
    HttpServletRequest request = job.getRequest();
    // get base url
    if (this.myBaseURL == null) {
        this.myBaseURL = MCRFrontendUtil.getBaseURL() + request.getServletPath().substring(1);
    }//from w  w  w . j a va 2 s .  co  m
    logRequest(request);
    // create new oai request
    OAIRequest oaiRequest = new OAIRequest(fixParameterMap(request.getParameterMap()));
    // create new oai provider
    OAIXMLProvider oaiProvider = new JAXBOAIProvider(getOAIAdapter());
    // handle request
    OAIResponse oaiResponse = oaiProvider.handleRequest(oaiRequest);
    // build response
    Element xmlRespone = oaiResponse.toXML();
    // fire
    job.getResponse().setContentType("text/xml; charset=UTF-8");
    XMLOutputter xout = new XMLOutputter();
    xout.setFormat(Format.getPrettyFormat().setEncoding("UTF-8"));
    xout.output(addXSLStyle(new Document(xmlRespone)), job.getResponse().getOutputStream());
}