Example usage for org.jdom2.output Format getPrettyFormat

List of usage examples for org.jdom2.output Format getPrettyFormat

Introduction

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

Prototype

public static Format getPrettyFormat() 

Source Link

Document

Returns a new Format object that performs whitespace beautification with 2-space indents, uses the UTF-8 encoding, doesn't expand empty elements, includes the declaration and encoding, and uses the default entity escape strategy.

Usage

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 ww  w .j  a  va  2 s  .co  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  www. ja v  a2s . 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 ww  .j  av  a  2s.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.cli.MCRClassification2Commands.java

License:Open Source License

/**
 * Save a MCRClassification.//from   ww w . j ava 2 s. co  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. ja 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  w  w  w.  ja  va  2  s.  co m*/
 * @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));
}

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

License:Open Source License

private void sendToDebug(HttpServletResponse res, Document unprocessed, MCREditorSubmission sub)
        throws IOException, UnsupportedEncodingException {
    res.setContentType("text/html; charset=UTF-8");

    PrintWriter pw = res.getWriter();

    pw.println("<html><body><p><pre>");

    for (int i = 0; i < sub.getVariables().size(); i++) {
        MCREditorVariable var = (MCREditorVariable) sub.getVariables().get(i);
        pw.println(var.getPath() + " = " + var.getValue());

        FileItem file = var.getFile();

        if (file != null) {
            pw.println("      is uploaded file " + file.getContentType() + ", " + file.getSize() + " bytes");
        }//w  w w  .  j ava  2 s .  co  m
    }

    pw.println("</pre></p><p>");

    XMLOutputter outputter = new XMLOutputter();
    Format fmt = Format.getPrettyFormat();
    fmt.setLineSeparator("\n");
    fmt.setOmitDeclaration(true);
    outputter.setFormat(fmt);

    Element pre = new Element("pre");
    pre.addContent(outputter.outputString(unprocessed));
    outputter.output(pre, pw);

    pre = new Element("pre");
    pre.addContent(outputter.outputString(sub.getXML()));
    outputter.output(pre, pw);

    pw.println("</p></body></html>");
    pw.close();
}

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 ww .  j  av  a2  s .  c om
    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());
}

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

License:Open Source License

protected Element getURI(String uri) {
    Element e = MCRURIResolver.instance().resolve(uri).detach();
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("get " + uri);
        XMLOutputter out = new XMLOutputter(Format.getPrettyFormat());
        LOGGER.debug(out.outputString(e));
    }//from w  ww  .  j  av a2s.  c  om
    return e;
}

From source file:org.mycore.restapi.v1.MCRRestAPIClassifications.java

License:Open Source License

/**
 *
 * @param info - a Jersey Context Object for URI
 *     Possible values are: json | xml (required)
 *///  w  w w  .  j a v a2  s  .  c  o  m
@GET
@Path("/")
@Produces({ MediaType.TEXT_XML + ";charset=UTF-8", MediaType.APPLICATION_JSON + ";charset=UTF-8" })
public Response listClassifications(@Context UriInfo info,
        @QueryParam("format") @DefaultValue("json") String format) {
    if (FORMAT_XML.equals(format)) {
        StringWriter sw = new StringWriter();

        XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat());
        Document docOut = new Document();
        Element eRoot = new Element("mycoreclassifications");
        docOut.setRootElement(eRoot);

        for (MCRCategory cat : DAO.getRootCategories()) {
            eRoot.addContent(
                    new Element("mycoreclass").setAttribute("ID", cat.getId().getRootID()).setAttribute("href",
                            info.getAbsolutePathBuilder().path(cat.getId().getRootID()).build().toString()));
        }
        try {
            xout.output(docOut, sw);
            return Response.ok(sw.toString()).type("application/xml; charset=UTF-8").build();
        } catch (IOException e) {
            //ToDo
        }
    }

    if (FORMAT_JSON.equals(format)) {
        StringWriter sw = new StringWriter();
        try {
            JsonWriter writer = new JsonWriter(sw);
            writer.setIndent("    ");
            writer.beginObject();
            writer.name("mycoreclass");
            writer.beginArray();
            for (MCRCategory cat : DAO.getRootCategories()) {
                writer.beginObject();
                writer.name("ID").value(cat.getId().getRootID());
                writer.name("href")
                        .value(info.getAbsolutePathBuilder().path(cat.getId().getRootID()).build().toString());
                writer.endObject();
            }
            writer.endArray();
            writer.endObject();

            writer.close();

            return Response.ok(sw.toString()).type("application/json; charset=UTF-8").build();
        } catch (IOException e) {
            //toDo
        }
    }
    return Response.status(Status.BAD_REQUEST).build();
}