List of usage examples for org.dom4j.io OutputFormat setEncoding
public void setEncoding(String encoding)
From source file:org.mitre.jawb.io.ATLASHelper.java
License:Open Source License
public static void dump(Document doc, OutputStream out) throws IOException { // Pretty print the document to System.out OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding("US-ASCII"); Writer writer = new OutputStreamWriter(out, "US-ASCII"); XMLWriter xmlWriter = new XMLWriter(writer, format); xmlWriter.write(doc);/* w w w .java 2 s .c o m*/ xmlWriter.close(); }
From source file:org.mitre.muc.callisto.session.SessionLogger.java
License:Open Source License
/** Write xml file to specified stream. */ private void dumpXML(Document xdoc, OutputStream out) throws IOException { OutputFormat outformat = OutputFormat.createPrettyPrint(); outformat.setEncoding("UTF-8"); XMLWriter writer = new XMLWriter(out, outformat); writer.write(xdoc);//from w ww .j a va2 s. c o m writer.flush(); }
From source file:org.nuclos.client.datasource.querybuilder.QueryBuilderEditor.java
License:Open Source License
/** * @return/* w w w. j av a 2 s . c o m*/ * @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//w ww . ja v a2 s . c om * 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.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/*from w ww . j a v a2s .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.openadaptor.auxil.convertor.xml.AbstractTestXmlConvertor.java
License:Open Source License
protected static String docAsString(Document doc, String encoding) { StringWriter sw = new StringWriter(); OutputFormat outputFormat = OutputFormat.createCompactFormat(); if (encoding != null) { outputFormat.setEncoding(encoding); // This definitely sets it in the header! }/* w w w .jav a2 s .c o m*/ XMLWriter writer = new XMLWriter(sw, outputFormat); try { writer.write(doc); } catch (IOException ioe) { fail("Failed to write XML as a String. Reason: " + ioe.toString()); } return sw.toString(); }
From source file:org.openadaptor.auxil.convertor.xml.OrderedMapToXmlConvertor.java
License:Open Source License
/** * Performs the actual conversion. Will recursively add each element of the map as * //from w w w.j a va 2 s .c o m * @param map * the map to be converted * @param returnAsString * if true then the Dom4j Document is returned * * @return the xml (or Dom4j Document) corresponding to the supplied OrderedMap * * @throws RecordException * if the conversion fails */ private Object convertOrderedMapToXml(IOrderedMap map, boolean returnAsString) throws RecordException { Object result = null; // Create a Document to hold the data. Document doc = DocumentHelper.createDocument(); if (encoding != null) { // Doesn't seem to have any effect here, so output formatter also sets it doc.setXMLEncoding(encoding); log.debug("Document encoding now " + doc.getXMLEncoding()); } String rootTag = rootElementTag; if (rootTag != null) { log.debug("Using Supplied root tag - unset rootElementTag property to disable"); } else { // Try and derive it. Must have a single entry, whose value is itself an OM. log.debug("rootElementTag property is not set. Deriving root tag from data."); if (map.size() == 1) { // Might be able to derive root tag. Object rootTagObject = map.keys().get(0); rootTag = rootTagObject == null ? null : rootTagObject.toString(); Object value = map.get(rootTag); if (value instanceof IOrderedMap) { // Bingo we're in. log.debug( "Deriving rootElementTag property from map (set rootElementTag property explicitly to prevent this"); map = (IOrderedMap) value; // Move down a level as we're adding it here. } else {// No go -be safe and add our own root. log.warn("Failed to derive root tag. Using default of " + OrderedMapToXmlConvertor.DEFAULT_ROOT_ELEMENT_TAG); rootTag = OrderedMapToXmlConvertor.DEFAULT_ROOT_ELEMENT_TAG; } } else {// More than one top level entry. Give up and default. log.warn("Top level has more than one entry. Using default of " + OrderedMapToXmlConvertor.DEFAULT_ROOT_ELEMENT_TAG); rootTag = OrderedMapToXmlConvertor.DEFAULT_ROOT_ELEMENT_TAG; } } //Fix for #SC35: OrderedMapToXmlConvertor should, but does not map slashes in the root tag rootTag = generateElementName(rootTag); log.debug("Document root tag will be: " + rootTag); // Prime the root tag. Element root = doc.addElement(rootTag); Iterator it = map.keys().iterator(); while (it.hasNext()) { String key = it.next().toString(); Object value = map.get(key); addElement(root, key, value); } // document done. Phew. if (returnAsString) { // Darn, need to output the Document as a String. StringWriter sw = new StringWriter(); OutputFormat outputFormat = OutputFormat.createCompactFormat(); if (encoding != null) { log.debug("Output Format encoding as " + encoding); outputFormat.setEncoding(encoding); // This definitely sets it in the header! } // outputFormat.setOmitEncoding(true); // outputFormat.setSuppressDeclaration(true); XMLWriter writer = new XMLWriter(sw, outputFormat); try { writer.write(doc); } catch (IOException ioe) { log.warn("Failed to write the XML as a String"); throw new RecordFormatException("Failed to write the XML as a String. Reason: " + ioe.toString(), ioe); } result = sw.toString(); } else { result = doc; } return result; }
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// w w w. j a va 2 s. 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); } }
From source file:org.opencms.configuration.CmsConfigurationManager.java
License:Open Source License
/** * Writes the XML configuration for the provided configuration instance.<p> * /*w w w . jav a 2 s . co m*/ * @param clazz the configuration class to write the XML for * @throws IOException in case of I/O errors while writing * @throws CmsConfigurationException if the given class is not a valid configuration class */ public void writeConfiguration(Class<?> clazz) throws IOException, CmsConfigurationException { I_CmsXmlConfiguration configuration = getConfiguration(clazz); if (configuration == null) { throw new CmsConfigurationException( Messages.get().container(Messages.ERR_CONFIG_WITH_UNKNOWN_CLASS_1, clazz.getName())); } // generate the file URL for the XML input File file = new File(m_baseFolder, configuration.getXmlFileName()); if (LOG.isDebugEnabled()) { LOG.debug(Messages.get().getBundle().key(Messages.LOG_WRITE_CONFIG_XMLFILE_1, file.getAbsolutePath())); } // generate the XML document Document config = generateXml(configuration); // output the document XMLWriter writer = null; OutputFormat format = OutputFormat.createPrettyPrint(); format.setIndentSize(4); format.setTrimText(false); format.setEncoding(CmsEncoder.ENCODING_UTF_8); try { OutputStream out = new FileOutputStream(file); writer = new XMLWriter(out, format); writer.write(config); writer.flush(); } finally { if (writer != null) { writer.close(); } } if (LOG.isInfoEnabled()) { LOG.info(Messages.get().getBundle().key(Messages.LOG_WRITE_CONFIG_SUCCESS_2, file.getAbsolutePath(), configuration.getClass().getName())); } }
From source file:org.opencms.util.ant.CmsXmlUtils.java
License:Open Source License
/** * Marshals (writes) an XML document into an output stream using XML pretty-print formatting.<p> * // www. ja va2 s . co m * @param document the XML document to marshal * @param out the output stream to write to * @param encoding the encoding to use * @return the output stream with the xml content * @throws Exception if something goes wrong */ public static OutputStream marshal(Document document, OutputStream out, String encoding) throws Exception { OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding(encoding); XMLWriter writer = new XMLWriter(out, format); writer.setEscapeText(false); writer.write(document); writer.close(); return out; }