Example usage for org.dom4j.io OutputFormat createPrettyPrint

List of usage examples for org.dom4j.io OutputFormat createPrettyPrint

Introduction

In this page you can find the example usage for org.dom4j.io OutputFormat createPrettyPrint.

Prototype

public static OutputFormat createPrettyPrint() 

Source Link

Document

A static helper method to create the default pretty printing format.

Usage

From source file:org.nuclos.client.datasource.querybuilder.QueryBuilderEditor.java

License:Open Source License

/**
 * @return/* www.j  av a2s  .  com*/
 * @throws NuclosBusinessException
 */
public String getXML(DatasourceEntityOptions eOptions) throws CommonBusinessException {
    String result = "";
    try {
        final Document doc = DocumentHelper.createDocument();
        doc.addDocType(QueryBuilderConstants.DOCTYPE, null, QueryBuilderConstants.SYSTEMID);

        Element root = doc.addElement(QueryBuilderConstants.DOCTYPE);
        Element header = root.addElement(QueryBuilderConstants.TAG_HEADER);
        Element tables = root.addElement(QueryBuilderConstants.TAG_TABLES);
        Element connectors = root.addElement(QueryBuilderConstants.TAG_CONNECTORS);
        Element columns = root.addElement(QueryBuilderConstants.TAG_COLUMNS);
        Element parameters = root.addElement(QueryBuilderConstants.TAG_PARAMETERS);
        Element sql = root.addElement(QueryBuilderConstants.TAG_SQL);

        serializeHeader(header);
        serializeTables(tables);
        serializeConnectors(connectors);
        serializeColumns(columns);
        serializeParameters(parameters);

        if (eOptions != null) {
            Element entityoptions = root.addElement(QueryBuilderConstants.TAG_ENTITYOPTIONS);
            entityoptions.addAttribute("dynamic", eOptions.isDynamic() ? "yes" : "no");
        }

        final boolean bModelUsed = parent.isModelUsed();
        sql.addAttribute("isModelUsed", bModelUsed ? "true" : "false");
        if (!bModelUsed) {
            sql.addCDATA(StringUtils.emptyIfNull(parent.getSql()));
        }

        final OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("UTF-8");
        //format.setEncoding("ISO-8859-1");
        final StringWriter sw = new StringWriter();
        final XMLWriter xmlw = new XMLWriter(sw, format);
        xmlw.write(doc);
        xmlw.close();
        result = sw.toString();
    } catch (IOException ex) {
        throw new NuclosFatalException(ex);
    }
    return result;
}

From source file:org.nuclos.server.transfer.ejb3.XmlExportFacadeBean.java

License:Open Source License

/**
 *
 * @param exportEntities// ww  w .j av a  2  s.  c  o  m
 *            map of ids and entitynames to export
 * @return Zip File with Xml output and Document files
 * @throws IOException
 * @throws CommonPermissionException
 * @throws CommonFinderException
 * @throws CreateException
 * @throws CommonCreateException
 * @throws NuclosBusinessRuleException
 * @throws Exception
 * @jboss.method-attributes read-only = "true"
 */
public org.nuclos.common2.File xmlExport(Map<Integer, String> exportEntities, boolean deepexport,
        boolean withDependants, String sFileName) throws CommonFinderException, CommonPermissionException,
        IOException, CommonCreateException, NuclosBusinessRuleException {

    today = new Date();
    dateFormat = new SimpleDateFormat("dd.MM.yyy HH:mm:ss");
    iActionNumber = 1;

    // List of exported Ids
    exportedIds = new ArrayList<Pair<String, Integer>>();

    // map of subforms with their foreign keys of the entities
    mpGoSubFormsWithForeignKeys = new HashMap<Integer, Map<EntityAndFieldName, String>>();
    mpMdSubFormsWithForeignKeys = new HashMap<String, Map<EntityAndFieldName, String>>();

    // create and clear export dirs
    File expimpDir = NuclosSystemParameters.getDirectory(NuclosSystemParameters.EXPORT_IMPORT_PATH);
    if (!expimpDir.exists()) {
        expimpDir.mkdir();
    }
    File expimpTimestampDir = new File(expimpDir, "" + today.getTime());
    expimpTimestampDir.mkdir();
    try {
        File expimpTsResourceDir = new File(expimpTimestampDir, "ressource");
        expimpTsResourceDir.mkdir();

        Set<Integer> stExportId = exportEntities.keySet();

        // create XML Document and Header
        Document document = DocumentHelper.createDocument();
        Element header = document.addElement("nucleusXmlExport");
        header.addAttribute("version",
                ApplicationProperties.getInstance().getNuclosVersion().getVersionNumber());
        header.addAttribute("date", dateFormat.format(today));
        String sRootEntity = "";
        if (!stExportId.isEmpty()) {
            sRootEntity = exportEntities.get(stExportId.toArray()[0]);
        }
        header.addAttribute("rootentity", sRootEntity);
        header.addAttribute("deepexport", Boolean.toString(deepexport));

        info("Begin Export: user [" + getCurrentUserName() + "] date [" + today + "] entity [" + sRootEntity
                + "]");
        iProtocolId = getProtocolFacade().writeExportImportLogHeader(XmlExportImportHelper.EXPIMP_TYPE_EXPORT,
                getCurrentUserName(), today, sRootEntity, sFileName);

        //         // special handling for elisa, that means the following:
        //         // deep export = main data + subform data will be exported
        //         // no deep export = only main data will be exported
        //         if (deepexport) {
        //            bElisaDeepExport = true;
        //            deepexport = false;
        //         }
        //         else {
        //            bElisaDeepExport = false;
        //         }

        for (Integer iExportId : stExportId) {
            // call recursive XML Helper Method
            xmlExportHelper(exportEntities.get(iExportId), iExportId, header, deepexport, withDependants, true);
        }

        try {
            // write XML File
            final OutputFormat format = OutputFormat.createPrettyPrint();
            format.setTrimText(false);
            format.setEncoding("UTF-8");

            final File fExport = new File(expimpTimestampDir.getPath() + "/export.xml");
            final Writer osr = new BufferedWriter(
                    new OutputStreamWriter(new FileOutputStream(fExport), "UTF-8"));
            final XMLWriter writer = new XMLWriter(osr, format);
            try {
                writer.write(document);
            } finally {
                writer.close();
            }
            // activate the following code, if you want to save the exported file in the database
            // NOTE: it is recommended to compress the stored data
            //xmlExportImportProtocol.addXmlFile(iProtocolId, IOUtils.readFromTextFile(fExport, "UTF-8"));
        } catch (IOException e) {
            throw new IOException("xmlexport.error.creating.file", e);
            //"Fehler beim erstellen der XML-Export-Datei aufgetreten: "+e);
        }

        try {
            // Zip Export Files
            XmlExportImportHelper.zipFolder(expimpTimestampDir, "nucleus_export.zip");
        } catch (Exception e) {
            throw new NuclosFatalException("xmlexport.error.creating.zipfile", e);
            //"Fehler beim erstellen der ZIP-Export-Datei aufgetreten: "+e);
        }

        // create serializeable File from Zip
        org.nuclos.common2.File transfile = XmlExportImportHelper
                .createFile(expimpTimestampDir.getAbsolutePath(), "nucleus_export.zip");

        getProtocolFacade().addFile(iProtocolId, transfile.getContents());

        info("END Export");

        return transfile;
    } finally {
        // delete export dir
        XmlExportImportHelper.deleteDir(expimpTimestampDir);
    }
}

From source file:org.nuxeo.automation.scripting.blockly.converter.Chains2Blockly.java

License:Open Source License

public String convertXML(InputStream xmlChains) throws IOException {
    Element root = convert(xmlChains);
    OutputFormat format = OutputFormat.createPrettyPrint();
    StringWriter out = new StringWriter();
    XMLWriter writer = new XMLWriter(out, format);
    writer.write(root);/* w  w  w  .j av a 2 s .  c  o  m*/
    out.flush();
    return out.getBuffer().toString();
}

From source file:org.nuxeo.ecm.platform.audit.io.IOLogEntryBase.java

License:Open Source License

protected static void writeXML(Document doc, OutputStream out) throws IOException {
    OutputFormat format = OutputFormat.createPrettyPrint();
    XMLWriter writer = new XMLWriter(out, format);
    writer.write(doc);//from   w ww  .ja  v a  2  s  . c om
}

From source file:org.nuxeo.ecm.webapp.liveedit.LiveEditBootstrapHelper.java

License:Apache License

/**
 * Creates the bootstrap file. It is called from the browser's addon. The URL composition tells the case and what to
 * create. The structure is depicted in the NXP-1881. Rux NXP-1959: add new tag on root level describing the action:
 * actionEdit, actionNew or actionFromTemplate.
 *
 * @return the bootstrap file content//ww  w  .  j  a va2 s .c  o  m
 */
public void getBootstrap() throws IOException {
    String currentRepoID = documentManager.getRepositoryName();

    CoreSession session = documentManager;
    CoreSession templateSession = documentManager;
    try {
        if (repoID != null && !currentRepoID.equals(repoID)) {
            session = CoreInstance.openCoreSession(repoID);
        }

        if (templateRepoID != null && !currentRepoID.equals(templateRepoID)) {
            templateSession = CoreInstance.openCoreSession(templateRepoID);
        }

        DocumentModel doc = null;
        DocumentModel templateDoc = null;
        String filename = null;
        if (ACTION_EDIT_DOCUMENT.equals(action)) {
            // fetch the document to edit to get its mimetype and document
            // type
            doc = session.getDocument(new IdRef(docRef));
            docType = doc.getType();
            Blob blob = null;
            if (blobPropertyName != null) {
                blob = (Blob) doc.getPropertyValue(blobPropertyName);
                if (blob == null) {
                    throw new NuxeoException(
                            String.format("could not find blob to edit with property '%s'", blobPropertyName));
                }
            } else {
                blob = (Blob) doc.getProperty(schema, blobField);
                if (blob == null) {
                    throw new NuxeoException(String.format(
                            "could not find blob to edit with schema '%s' and field '%s'", schema, blobField));
                }
            }
            mimetype = blob.getMimeType();
            if (filenamePropertyName != null) {
                filename = (String) doc.getPropertyValue(filenamePropertyName);
            } else {
                filename = (String) doc.getProperty(schema, filenameField);
            }
        } else if (ACTION_CREATE_DOCUMENT.equals(action)) {
            // creating a new document all parameters are read from the
            // request parameters
        } else if (ACTION_CREATE_DOCUMENT_FROM_TEMPLATE.equals(action)) {
            // fetch the template blob to get its mimetype
            templateDoc = templateSession.getDocument(new IdRef(templateDocRef));
            Blob blob = (Blob) templateDoc.getProperty(templateSchema, templateBlobField);
            if (blob == null) {
                throw new NuxeoException(
                        String.format("could not find template blob with schema '%s' and field '%s'",
                                templateSchema, templateBlobField));
            }
            mimetype = blob.getMimeType();
            // leave docType from the request query parameter
        } else {
            throw new NuxeoException(String.format(
                    "action '%s' is not a valid LiveEdit action: should be one of '%s', '%s' or '%s'", action,
                    ACTION_CREATE_DOCUMENT, ACTION_CREATE_DOCUMENT_FROM_TEMPLATE, ACTION_EDIT_DOCUMENT));
        }

        FacesContext context = FacesContext.getCurrentInstance();
        HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
        HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();

        Element root = DocumentFactory.getInstance().createElement(liveEditTag);
        root.addNamespace("", XML_LE_NAMESPACE);
        // RUX NXP-1959: action id
        Element actionInfo = root.addElement(actionSelectorTag);
        actionInfo.setText(action);

        // Document related informations
        Element docInfo = root.addElement(documentTag);
        addTextElement(docInfo, docRefTag, docRef);
        Element docPathT = docInfo.addElement(docPathTag);
        Element docTitleT = docInfo.addElement(docTitleTag);
        if (doc != null) {
            docPathT.setText(doc.getPathAsString());
            docTitleT.setText(doc.getTitle());
        }
        addTextElement(docInfo, docRepositoryTag, repoID);

        addTextElement(docInfo, docSchemaNameTag, schema);
        addTextElement(docInfo, docFieldNameTag, blobField);
        addTextElement(docInfo, docBlobFieldNameTag, blobField);
        Element docFieldPathT = docInfo.addElement(docfieldPathTag);
        Element docBlobFieldPathT = docInfo.addElement(docBlobFieldPathTag);
        if (blobPropertyName != null) {
            // FIXME AT: NXP-2306: send blobPropertyName correctly (?)
            docFieldPathT.setText(blobPropertyName);
            docBlobFieldPathT.setText(blobPropertyName);
        } else {
            if (schema != null && blobField != null) {
                docFieldPathT.setText(schema + ':' + blobField);
                docBlobFieldPathT.setText(schema + ':' + blobField);
            }
        }
        addTextElement(docInfo, docFilenameFieldNameTag, filenameField);
        Element docFilenameFieldPathT = docInfo.addElement(docFilenameFieldPathTag);
        if (filenamePropertyName != null) {
            docFilenameFieldPathT.setText(filenamePropertyName);
        } else {
            if (schema != null && blobField != null) {
                docFilenameFieldPathT.setText(schema + ':' + filenameField);
            }
        }

        addTextElement(docInfo, docfileNameTag, filename);
        addTextElement(docInfo, docTypeTag, docType);
        addTextElement(docInfo, docMimetypeTag, mimetype);
        addTextElement(docInfo, docFileExtensionTag, getFileExtension(mimetype));

        Element docFileAuthorizedExtensions = docInfo.addElement(docFileAuthorizedExtensionsTag);
        List<String> authorizedExtensions = getFileExtensions(mimetype);
        if (authorizedExtensions != null) {
            for (String extension : authorizedExtensions) {
                addTextElement(docFileAuthorizedExtensions, docFileAuthorizedExtensionTag, extension);
            }
        }

        Element docIsVersionT = docInfo.addElement(docIsVersionTag);
        Element docIsLockedT = docInfo.addElement(docIsLockedTag);
        if (ACTION_EDIT_DOCUMENT.equals(action)) {
            docIsVersionT.setText(Boolean.toString(doc.isVersion()));
            docIsLockedT.setText(Boolean.toString(doc.isLocked()));
        }

        // template information for ACTION_CREATE_DOCUMENT_FROM_TEMPLATE

        Element templateDocInfo = root.addElement(templateDocumentTag);
        addTextElement(templateDocInfo, docRefTag, templateDocRef);
        docPathT = templateDocInfo.addElement(docPathTag);
        docTitleT = templateDocInfo.addElement(docTitleTag);
        if (templateDoc != null) {
            docPathT.setText(templateDoc.getPathAsString());
            docTitleT.setText(templateDoc.getTitle());
        }
        addTextElement(templateDocInfo, docRepositoryTag, templateRepoID);
        addTextElement(templateDocInfo, docSchemaNameTag, templateSchema);
        addTextElement(templateDocInfo, docFieldNameTag, templateBlobField);
        addTextElement(templateDocInfo, docBlobFieldNameTag, templateBlobField);
        docFieldPathT = templateDocInfo.addElement(docfieldPathTag);
        docBlobFieldPathT = templateDocInfo.addElement(docBlobFieldPathTag);
        if (templateSchema != null && templateBlobField != null) {
            docFieldPathT.setText(templateSchema + ":" + templateBlobField);
            docBlobFieldPathT.setText(templateSchema + ":" + templateBlobField);
        }
        addTextElement(templateDocInfo, docMimetypeTag, mimetype);
        addTextElement(templateDocInfo, docFileExtensionTag, getFileExtension(mimetype));

        Element templateFileAuthorizedExtensions = templateDocInfo.addElement(docFileAuthorizedExtensionsTag);
        if (authorizedExtensions != null) {
            for (String extension : authorizedExtensions) {
                addTextElement(templateFileAuthorizedExtensions, docFileAuthorizedExtensionTag, extension);
            }
        }

        // Browser request related informations
        Element requestInfo = root.addElement(requestInfoTag);
        Cookie[] cookies = request.getCookies();
        Element cookiesT = requestInfo.addElement(requestCookiesTag);
        for (Cookie cookie : cookies) {
            Element cookieT = cookiesT.addElement(requestCookieTag);
            cookieT.addAttribute("name", cookie.getName());
            cookieT.setText(cookie.getValue());
        }
        Element headersT = requestInfo.addElement(requestHeadersTag);
        Enumeration hEnum = request.getHeaderNames();
        while (hEnum.hasMoreElements()) {
            String hName = (String) hEnum.nextElement();
            if (!hName.equalsIgnoreCase("cookie")) {
                Element headerT = headersT.addElement(requestHeaderTag);
                headerT.addAttribute("name", hName);
                headerT.setText(request.getHeader(hName));
            }
        }
        addTextElement(requestInfo, requestBaseURLTag, BaseURL.getBaseURL(request));

        // User related informations
        String username = context.getExternalContext().getUserPrincipal().getName();
        Element userInfo = root.addElement(userInfoTag);
        addTextElement(userInfo, userNameTag, username);
        addTextElement(userInfo, userPasswordTag, "");
        addTextElement(userInfo, userTokenTag, "");
        addTextElement(userInfo, userLocaleTag, context.getViewRoot().getLocale().toString());
        // Rux NXP-1882: the wsdl locations
        String baseUrl = BaseURL.getBaseURL(request);
        Element wsdlLocations = root.addElement(wsdlLocationsTag);
        Element wsdlAccessWST = wsdlLocations.addElement(wsdlAccessWebServiceTag);
        wsdlAccessWST.setText(baseUrl + "webservices/nuxeoAccess?wsdl");
        Element wsdlEEWST = wsdlLocations.addElement(wsdlLEWebServiceTag);
        wsdlEEWST.setText(baseUrl + "webservices/nuxeoLEWS?wsdl");

        // Server related informations
        Element serverInfo = root.addElement(serverInfoTag);
        Element serverVersionT = serverInfo.addElement(serverVersionTag);
        serverVersionT.setText("5.1"); // TODO: use a buildtime generated
        // version tag instead

        // Client related informations
        Element editId = root.addElement(editIdTag);
        editId.setText(getEditId(doc, session, username));

        // serialize bootstrap XML document in the response
        Document xmlDoc = DocumentFactory.getInstance().createDocument();
        xmlDoc.setRootElement(root);
        response.setContentType("text/xml; charset=UTF-8");

        // use a formatter to make it easier to debug live edit client
        // implementations
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("UTF-8");
        XMLWriter writer = new XMLWriter(response.getOutputStream(), format);
        writer.write(xmlDoc);

        response.flushBuffer();
        context.responseComplete();
    } finally {
        if (session != null && session != documentManager) {
            session.close();
        }
        if (templateSession != null && templateSession != documentManager) {
            templateSession.close();
        }
    }
}

From source file:org.olat.ims.cp.ContentPackage.java

License:Apache License

/**
 * writes the manifest.xml//www  .  j  av  a  2 s  . co  m
 */
void writeToFile() {
    final String filename = "imsmanifest.xml";
    final OutputFormat format = OutputFormat.createPrettyPrint();

    try {
        VFSLeaf outFile;
        // file may exist
        outFile = (VFSLeaf) cpcore.getRootDir().resolve("/" + filename);
        if (outFile == null) {
            // if not, create it
            outFile = cpcore.getRootDir().createChildLeaf("/" + filename);
        }
        final DefaultDocument manifestDocument = cpcore.buildDocument();
        final XMLWriter writer = new XMLWriter(outFile.getOutputStream(false), format);
        writer.write(manifestDocument);
    } catch (final Exception e) {
        log.error("imsmanifest for ores " + ores.getResourceableId() + "couldn't be written to file.", e);
        throw new OLATRuntimeException(CPOrganizations.class, "Error writing imsmanifest-file",
                new IOException());
    }
}

From source file:org.olat.ims.qti.qpool.QTIExportProcessor.java

License:Apache License

private void addMetadata(QuestionItemFull fullItem, String dir, ZipOutputStream zout) {
    try {// w  w  w. jav a 2  s. co m
        Document document = DocumentHelper.createDocument();
        Element qtimetadata = document.addElement("qtimetadata");
        QTIMetadataConverter enricher = new QTIMetadataConverter(qtimetadata);
        enricher.toXml(fullItem);
        zout.putNextEntry(new ZipEntry(dir + "/" + "qitem_" + fullItem.getKey() + "_metadata.xml"));
        OutputFormat format = OutputFormat.createPrettyPrint();
        XMLWriter writer = new XMLWriter(zout, format);
        writer.write(document);
    } catch (IOException e) {
        log.error("", e);
    }
}

From source file:org.openadaptor.thirdparty.dom4j.Dom4jToXmlConvertor.java

License:Open Source License

/**
 * Converts the supplied DOM document into its XML equivalent. If the <code>prettyPrint</code> has been set then the
 * XML is returned formatted with indents and newlines
 * //from   w  ww .  j  av  a 2 s  . co  m
 * @param document
 *          the DOM document to be converted
 * 
 * @return the XML
 */
private String asString(Document document) {
    // Easy peasy.
    if (!prettyPrint)
        return document.asXML();

    if (outputFormat == null) {
        outputFormat = OutputFormat.createPrettyPrint();
        outputFormat.setIndent("\t");
    }

    String xml;
    StringWriter writer = new StringWriter();
    XMLWriter out = new XMLWriter(writer, outputFormat);

    try {
        out.write(document);
        xml = writer.toString();
    } catch (IOException ioe) { // Should never happen, but if it does, give up on pretty print.
        log.warn("Failed to pretty print - falling back to default");
        xml = document.asXML();
    }

    return xml;
}

From source file:org.openadaptor.util.XmlUtils.java

License:Open Source License

/**
 * Uses a Dom4j SAXReader to apply formatting to the supplied XML fragment. In this case we use a prettyprinter to
 * indent the tags.//from  w ww  . ja va  2s  . c om
 * 
 * @param xml
 *          The XML to be formatted (can be just a fragment)
 * @param isFragment
 *          If you supplied a XML fragment then this must be set to true so that the writer doesn't output an XML
 *          declaration
 * 
 * @return the formatted XML
 * 
 * @throws IOException
 *           if there was a problem applying the formatting
 * @throws DocumentException
 *           if there was a problem with the XML
 */
public static String format(String xml, boolean isFragment) throws IOException, DocumentException {

    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setSuppressDeclaration(isFragment);
    format.setIndent("\t");

    SAXReader reader = new SAXReader();
    Reader r = new StringReader(xml);
    org.dom4j.Document document = reader.read(r);

    Writer w = new StringWriter();
    XMLWriter out = new XMLWriter(w, format);
    out.write(document);
    out.close();

    return w.toString();
}

From source file:org.openbravo.dal.xml.XMLUtil.java

License:Open Source License

/**
 * Converts a Dom4j document to a string. A number of specific settings: 1) output encoding is
 * UTF-8, 2) text nodes are not trimmed//from   w w  w.ja va  2s  . co m
 * 
 * @param document
 *          the Dom4j to convert to a XML string
 * @return the XML representation
 */
public String toString(Document document) {
    try {
        final OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("UTF-8");
        format.setTrimText(false);
        final StringWriter out = new StringWriter();
        final XMLWriter writer = new XMLWriter(out, format);
        writer.write(document);
        writer.close();
        return out.toString();
    } catch (final Exception e) {
        throw new OBException(e);
    }
}