Example usage for org.jdom2.output XMLOutputter XMLOutputter

List of usage examples for org.jdom2.output XMLOutputter XMLOutputter

Introduction

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

Prototype

public XMLOutputter(XMLOutputProcessor processor) 

Source Link

Document

This will create an XMLOutputter with the specified XMLOutputProcessor.

Usage

From source file:org.mycore.common.MCRUtils.java

License:Open Source License

/**
 * Transforms the given {@link Document} into a String
 * /*from   w  w w  . j a va  2  s . co  m*/
 * @return the xml document as {@link String} or null if an {@link Exception} occurs
 * @deprecated use {@link XMLOutputter} directly
 */
@Deprecated
public static String asString(Document doc) {
    return new XMLOutputter(Format.getPrettyFormat()).outputString(doc);
}

From source file:org.mycore.common.MCRUtils.java

License:Open Source License

/**
 * Transforms the given Element into a String
 * /*from   ww  w.  j  a  va2 s . co m*/
 * @return the xml element as {@link String}
 * @deprecated use {@link XMLOutputter} directly
 */
@Deprecated
public static String asString(Element elm) {
    return new XMLOutputter(Format.getPrettyFormat()).outputString(elm);
}

From source file:org.mycore.common.xml.MCRXMLHelper.java

License:Open Source License

private static Element canonicalElement(Parent e) throws IOException, SAXParseException {
    XMLOutputter xout = new XMLOutputter(Format.getCompactFormat());
    MCRByteArrayOutputStream bout = new MCRByteArrayOutputStream();
    if (e instanceof Element) {
        xout.output((Element) e, bout);
    } else {/*from   w w  w  .  ja va 2  s  .c o  m*/
        xout.output((Document) e, bout);
    }
    Document xml = MCRXMLParserFactory.getNonValidatingParser()
            .parseXML(new MCRByteContent(bout.getBuffer(), 0, bout.size()));
    return xml.getRootElement();
}

From source file:org.mycore.datamodel.metadata.MCRObjectMetadata.java

License:Open Source License

/**
 * This method adds MCRMetaElement's from a given MCRObjectMetadata to
 * this data set if there are any differences between the data sets.
 * /*from  ww  w.  j  av a 2  s  .c o  m*/
 * @param input
 *            the MCRObjectMetadata, that should merged into this data set
 *            
 * @deprecated use {@link MCRObjectMerger#mergeMetadata(MCRObject, boolean)} instead
 */
public final void mergeMetadata(MCRObjectMetadata input) {

    for (MCRMetaElement metaElement : input) {
        int pos = -1;
        for (int j = 0; j < size(); j++) {
            if (meta_list.get(j).getTag().equals(metaElement.getTag())) {
                pos = j;
            }
        }
        if (pos != -1) {
            for (int j = 0; j < metaElement.size(); j++) {
                boolean found = false;
                for (MCRMetaInterface mcrMetaInterface : meta_list.get(pos)) {
                    Element xml = mcrMetaInterface.createXML();
                    Element xmlNEW = metaElement.getElement(j).createXML();
                    List<Element> childrenXML = xml.getChildren();
                    if (childrenXML.size() > 0 && xmlNEW.getChildren().size() > 0) {
                        int i = 0;
                        for (Element element : childrenXML) {
                            Element elementNew = xmlNEW.getChild(element.getName());

                            if (elementNew != null && element != null) {
                                if (element.getText().equals(elementNew.getText())) {
                                    i++;
                                }
                            }
                        }
                        if (i == childrenXML.size()) {
                            found = true;
                        }
                    } else {
                        if (xml.getText().equals(xmlNEW.getText())) {
                            found = true;
                        } else if (!found) {
                            int i = 0;
                            List<Attribute> attributes = xml.getAttributes();
                            for (Attribute attribute : attributes) {
                                Attribute attr = xmlNEW.getAttribute(attribute.getName());
                                if ((attr != null) && attr.equals(attribute)) {
                                    i++;
                                }
                            }
                            if (i == attributes.size()) {
                                found = true;
                            }

                        }
                    }
                }
                MCRMetaInterface obj = metaElement.getElement(j);
                if (!found) {
                    meta_list.get(pos).addMetaObject(obj);
                } else if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("Found equal tags: \n\r"
                            + new XMLOutputter(Format.getPrettyFormat()).outputString(obj.createXML()));
                }
            }
        } else {
            meta_list.add(metaElement);
        }
    }
}

From source file:org.mycore.datamodel.metadata.validator.MCREditorOutValidator.java

License:Open Source License

/**
 * instantiate the validator with the editor input <code>jdom_in</code>.
 * /*from  w  ww  .  j  a  v a  2  s.c  o m*/
 * <code>id</code> will be set as the MCRObjectID for the resulting object
 * that can be fetched with <code>generateValidMyCoReObject()</code>
 * 
 * @param jdom_in
 *            editor input
 */
public MCREditorOutValidator(Document jdom_in, MCRObjectID id) throws JDOMException, IOException {
    errorlog = new ArrayList<String>();
    input = jdom_in;
    this.id = id;
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(
                "XML before validation:\n" + new XMLOutputter(Format.getPrettyFormat()).outputString(input));
    }
    checkObject();
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(
                "XML after validation:\n" + new XMLOutputter(Format.getPrettyFormat()).outputString(input));
    }
}

From source file:org.mycore.datamodel.metadata.validator.MCREditorOutValidator.java

License:Open Source License

/**
 * tries to generate a valid MCRObject as JDOM Document.
 * /*from w  ww  .j  a  v a  2 s .  c  o m*/
 * @return MCRObject
 */
public Document generateValidMyCoReObject() throws JDOMException, SAXParseException, IOException {
    MCRObject obj;
    // load the JDOM object
    XPathFactory.instance().compile("/mycoreobject/*/*/*/@editor.output", Filters.attribute()).evaluate(input)
            .forEach(Attribute::detach);
    try {
        byte[] xml = new MCRJDOMContent(input).asByteArray();
        obj = new MCRObject(xml, true);
    } catch (SAXParseException e) {
        XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat());
        LOGGER.warn("Failure while parsing document:\n" + xout.outputString(input));
        throw e;
    }
    Date curTime = new Date();
    obj.getService().setDate("modifydate", curTime);

    // return the XML tree
    input = obj.createXML();
    return input;
}

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 .j  a  v a  2s.  c om
 * @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.cli.MCRClassification2Commands.java

License:Open Source License

/**
 * Save a MCRClassification./*  ww w . j  a  v  a2s . c o m*/
 *
 * @param ID
 *            the ID of the MCRClassification to be save.
 * @param dirname
 *            the directory to export the classification to
 * @param style
 *            the name part of the stylesheet like <em>style</em>
 *            -classification.xsl
 * @return false if an error was occured, else true
 */
@MCRCommand(syntax = "export classification {0} to directory {1} with {2}", help = "The command exports the classification with MCRObjectID {0} as xml file to directory named {1} using the stylesheet {2}-object.xsl. For {2} save is the default.", order = 60)
public static boolean export(String ID, String dirname, String style) throws Exception {
    String dname = "";
    if (dirname.length() != 0) {
        try {
            File dir = new File(dirname);
            if (!dir.isDirectory()) {
                dir.mkdir();
            }
            if (!dir.isDirectory()) {
                LOGGER.error("Can't find or create directory " + dir.getAbsolutePath());
                return false;
            } else {
                dname = dirname;
            }
        } catch (Exception e) {
            LOGGER.error("Can't find or create directory " + dirname, e);
            return false;
        }
    }
    MCRCategory cl = DAO.getCategory(MCRCategoryID.rootID(ID), -1);
    Document classDoc = MCRCategoryTransformer.getMetaDataDocument(cl, false);

    Transformer trans = getTransformer(style);
    File xmlOutput = new File(dname, ID + ".xml");
    FileOutputStream out = new FileOutputStream(xmlOutput);
    if (trans != null) {
        StreamResult sr = new StreamResult(out);
        trans.transform(new org.jdom2.transform.JDOMSource(classDoc), sr);
    } else {
        XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat());
        xout.output(classDoc, out);
        out.flush();
    }
    LOGGER.info("Classifcation " + ID + " saved to " + xmlOutput.getCanonicalPath() + ".");
    return true;
}

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

License:Open Source License

private static void readEditorInput(Element editor, MCREditorSession mcrEditor) {
    String sourceURI = mcrEditor.getSourceURI();
    LOGGER.info("Editor reading XML input from " + sourceURI);
    Element input = MCRURIResolver.instance().resolve(sourceURI);
    if (LOGGER.isDebugEnabled()) {
        LOGGER.info(new XMLOutputter(Format.getPrettyFormat()).outputString(input));
    }/*w ww  .  j  a  v a2  s . c om*/
    MCREditorSubmission sub = new MCREditorSubmission(input, editor);
    MCREditorDefReader.fixConditionedVariables(editor);
    editor.addContent(sub.buildInputElements());
    editor.addContent(sub.buildRepeatElements());
}

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

License:Open Source License

/**
 * Writes the output of editor to a local file in the web application
 * directory. Usage: &lt;target type="webapp" name="{relative_path_to_file}"
 * url="{redirect url after file is written}" /&gt; If cancel url is given,
 * user is redirected to that page, otherwise target url is used.
 * //from ww  w. j  ava  2 s. com
 * @throws IOException
 */
private void sendToWebAppFile(HttpServletRequest req, HttpServletResponse res, MCREditorSubmission sub,
        Element editor) throws IOException {
    String path = sub.getParameters().getParameter("_target-name");

    LOGGER.debug("Writing editor output to webapp file " + path);

    File f = getWebAppFile(path);
    if (!f.getParentFile().exists()) {
        f.getParentFile().mkdirs();
    }
    FileOutputStream fout = new FileOutputStream(f);
    XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat().setEncoding("UTF-8"));
    outputter.output(sub.getXML(), fout);
    fout.close();

    String url = sub.getParameters().getParameter("_target-url");
    Element cancel = editor.getChild("cancel");
    if ((url == null || url.length() == 0) && cancel != null && cancel.getAttributeValue("url") != null) {
        url = cancel.getAttributeValue("url");
    }

    LOGGER.debug("EditorServlet redirecting to " + url);
    res.sendRedirect(res.encodeRedirectURL(url));
}