org.dom4j.io.OutputFormat Java Examples
The following examples show how to use
org.dom4j.io.OutputFormat.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ImportFileUpdater.java From alfresco-repository with GNU Lesser General Public License v3.0 | 6 votes |
/** * Get the writer for the import file * * @param destination the destination XML import file * @return the XML writer */ private XMLWriter getWriter(String destination) { try { // Define output format OutputFormat format = OutputFormat.createPrettyPrint(); format.setNewLineAfterDeclaration(false); format.setIndentSize(INDENT_SIZE); format.setEncoding(this.fileEncoding); return new XMLWriter(new FileOutputStream(destination), format); } catch (Exception exception) { throw new AlfrescoRuntimeException("Unable to create XML writer.", exception); } }
Example #2
Source File: XmlHelper.java From projectforge-webapp with GNU General Public License v3.0 | 6 votes |
public static String toString(final Element el, final boolean prettyFormat) { if (el == null) { return ""; } final StringWriter out = new StringWriter(); final OutputFormat format = new OutputFormat(); if (prettyFormat == true) { format.setNewlines(true); format.setIndentSize(2); } final XMLWriter writer = new XMLWriter(out, format); String result = null; try { writer.write(el); result = out.toString(); writer.close(); } catch (final IOException ex) { log.error(ex.getMessage(), ex); } return result; }
Example #3
Source File: DefaultXmlWriter.java From yarg with Apache License 2.0 | 6 votes |
@Override public String buildXml(Report report) { try { Document document = DocumentFactory.getInstance().createDocument(); Element root = document.addElement("report"); root.addAttribute("name", report.getName()); writeTemplates(report, root); writeInputParameters(report, root); writeValueFormats(report, root); writeRootBand(report, root); StringWriter stringWriter = new StringWriter(); new XMLWriter(stringWriter, OutputFormat.createPrettyPrint()).write(document); return stringWriter.toString(); } catch (IOException e) { throw new ReportingException(e); } }
Example #4
Source File: XmlApiHelper.java From unitime with Apache License 2.0 | 6 votes |
@Override public <R> void setResponse(R response) throws IOException { iResponse.setContentType("application/xml"); iResponse.setCharacterEncoding("UTF-8"); iResponse.setHeader("Pragma", "no-cache" ); iResponse.addHeader("Cache-Control", "must-revalidate" ); iResponse.addHeader("Cache-Control", "no-cache" ); iResponse.addHeader("Cache-Control", "no-store" ); iResponse.setDateHeader("Date", new Date().getTime()); iResponse.setDateHeader("Expires", 0); iResponse.setHeader("Content-Disposition", "attachment; filename=\"response.xml\"" ); Writer writer = iResponse.getWriter(); try { new XMLWriter(writer, OutputFormat.createPrettyPrint()).write(response); } finally { writer.flush(); writer.close(); } }
Example #5
Source File: XSLConfiguration.java From CogniCrypt with Eclipse Public License 2.0 | 6 votes |
@Override public File persistConf() throws IOException { final XMLClaferParser parser = new XMLClaferParser(); Document configInXMLFormat = parser.displayInstanceValues(instance, this.options); if (configInXMLFormat != null) { final OutputFormat format = OutputFormat.createPrettyPrint(); final XMLWriter writer = new XMLWriter(new FileWriter(pathOnDisk), format); writer.write(configInXMLFormat); writer.close(); configInXMLFormat = null; return new File(pathOnDisk); } else { Activator.getDefault().logError(Constants.NO_XML_INSTANCE_FILE_TO_WRITE); } return null; }
Example #6
Source File: FrameServletHandler.java From urule with Apache License 2.0 | 6 votes |
public void fileSource(HttpServletRequest req, HttpServletResponse resp) throws Exception { String path=req.getParameter("path"); path=Utils.decodeURL(path); InputStream inputStream=repositoryService.readFile(path,null); String content=IOUtils.toString(inputStream,"utf-8"); inputStream.close(); String xml=null; try{ Document doc=DocumentHelper.parseText(content); OutputFormat format=OutputFormat.createPrettyPrint(); StringWriter out=new StringWriter(); XMLWriter writer=new XMLWriter(out, format); writer.write(doc); xml=out.toString(); }catch(Exception ex){ xml=content; } Map<String,Object> result=new HashMap<String,Object>(); result.put("content", xml); writeObjectToJson(resp, result); }
Example #7
Source File: XMLTransferManifestWriter.java From alfresco-repository with GNU Lesser General Public License v3.0 | 6 votes |
/** * Start the transfer manifest */ public void startTransferManifest(Writer writer) throws SAXException { format = OutputFormat.createPrettyPrint(); format.setNewLineAfterDeclaration(false); format.setIndentSize(3); format.setEncoding("UTF-8"); this.writer = new XMLWriter(writer, format); this.writer.startDocument(); this.writer.startPrefixMapping(PREFIX, TransferModel.TRANSFER_MODEL_1_0_URI); this.writer.startPrefixMapping("cm", NamespaceService.CONTENT_MODEL_1_0_URI); // Start Transfer Manifest // uri, name, prefix this.writer.startElement(TransferModel.TRANSFER_MODEL_1_0_URI, ManifestModel.LOCALNAME_TRANSFER_MAINIFEST, PREFIX + ":" + ManifestModel.LOCALNAME_TRANSFER_MAINIFEST, EMPTY_ATTRIBUTES); }
Example #8
Source File: XMLTransferDestinationReportWriter.java From alfresco-repository with GNU Lesser General Public License v3.0 | 6 votes |
/** * Start the transfer report */ public void startTransferReport(String encoding, Writer writer) { OutputFormat format = OutputFormat.createPrettyPrint(); format.setNewLineAfterDeclaration(false); format.setIndentSize(3); format.setEncoding(encoding); try { this.writer = new XMLWriter(writer, format); this.writer.startDocument(); this.writer.startPrefixMapping(PREFIX, TransferDestinationReportModel.TRANSFER_REPORT_MODEL_1_0_URI); // Start Transfer Manifest // uri, name, prefix this.writer.startElement(TransferDestinationReportModel.TRANSFER_REPORT_MODEL_1_0_URI, TransferDestinationReportModel.LOCALNAME_TRANSFER_DEST_REPORT, PREFIX + ":" + TransferDestinationReportModel.LOCALNAME_TRANSFER_DEST_REPORT, EMPTY_ATTRIBUTES); } catch (SAXException se) { se.printStackTrace(); } }
Example #9
Source File: AbstractSolver.java From unitime with Apache License 2.0 | 6 votes |
@Override public byte[] exportXml() throws IOException { Lock lock = currentSolution().getLock().readLock(); lock.lock(); try { boolean anonymize = ApplicationProperty.SolverXMLExportNames.isFalse(); boolean idconv = ApplicationProperty.SolverXMLExportConvertIds.isTrue(); ByteArrayOutputStream ret = new ByteArrayOutputStream(); Document document = createCurrentSolutionBackup(anonymize, idconv); if (ApplicationProperty.SolverXMLExportConfiguration.isTrue()) saveProperties(document); (new XMLWriter(ret, OutputFormat.createPrettyPrint())).write(document); ret.flush(); ret.close(); return ret.toByteArray(); } finally { lock.unlock(); } }
Example #10
Source File: StudentSolver.java From unitime with Apache License 2.0 | 6 votes |
@Override public byte[] backupXml() { java.util.concurrent.locks.Lock lock = currentSolution().getLock().readLock(); lock.lock(); try { ByteArrayOutputStream ret = new ByteArrayOutputStream(); GZIPOutputStream gz = new GZIPOutputStream(ret); Document document = createCurrentSolutionBackup(false, false); saveProperties(document); new XMLWriter(gz, OutputFormat.createCompactFormat()).write(document); gz.flush(); gz.close(); return ret.toByteArray(); } catch (Exception e) { sLog.error(e.getMessage(),e); return null; } finally { lock.unlock(); } }
Example #11
Source File: FilePersister.java From olat with Apache License 2.0 | 6 votes |
/** * Persist results for this user/aiid as an XML document. dlPointer is aiid in this case. * * @param doc * @param type * @param info */ public static void createResultsReporting(final Document doc, final Identity subj, final String type, final long aiid) { final File fUserdataRoot = new File(getQtiFilePath()); final String path = RES_REPORTING + File.separator + subj.getName() + File.separator + type; final File fReportingDir = new File(fUserdataRoot, path); try { fReportingDir.mkdirs(); final OutputStream os = new FileOutputStream(new File(fReportingDir, aiid + ".xml")); final Element element = doc.getRootElement(); final XMLWriter xw = new XMLWriter(os, new OutputFormat(" ", true)); xw.write(element); // closing steams xw.close(); os.close(); } catch (final Exception e) { throw new OLATRuntimeException(FilePersister.class, "Error persisting results reporting for subject: '" + subj.getName() + "'; assessment id: '" + aiid + "'", e); } }
Example #12
Source File: OSMMapExtractor.java From rcrs-server with BSD 3-Clause "New" or "Revised" License | 6 votes |
private void write() { double pressLat = viewer.getLatitude(press.y); double pressLon = viewer.getLongitude(press.x); double releaseLat = viewer.getLatitude(release.y); double releaseLon = viewer.getLongitude(release.x); try { OSMMap newMap = new OSMMap(map, Math.min(pressLat, releaseLat), Math.min(pressLon, releaseLon), Math.max(pressLat, releaseLat), Math.max(pressLon, releaseLon)); Document d = newMap.toXML(); XMLWriter writer = new XMLWriter(out, OutputFormat.createPrettyPrint()); writer.write(d); writer.flush(); writer.close(); System.out.println("Wrote map"); } // CHECKSTYLE:OFF:IllegalCatch catch (Exception ex) { ex.printStackTrace(); } // CHECKSTYLE:ON:IllegalCatch }
Example #13
Source File: WriteXml.java From Crawer with MIT License | 6 votes |
/** * 写数据到xml * * @param datas * @throws Exception */ public static void witeXml(@SuppressWarnings("rawtypes") Map map,String xmlFilePath) throws Exception { Document doc = DomHelper.createDomFJ(); doc.addComment("以utf-8的编码"); Element books = DomHelper.appendChile("books", doc); /* 格式化输出 */ OutputFormat format = OutputFormat.createPrettyPrint();// 紧缩 format.setEncoding("utf-8"); // 设置utf-8编码 Element book = DomHelper.appendChile("book", books); //构建树形结构 rescue(book, map); //输出 FileOutputStream fos = new FileOutputStream(xmlFilePath); XMLWriter writer=new XMLWriter(fos,format); //写结构 writer.write(doc); //关闭流 writer.close(); }
Example #14
Source File: XmppStreamOpen.java From onos with Apache License 2.0 | 6 votes |
@Override public String toXml() { StringWriter out = new StringWriter(); XMLWriter writer = new XMLWriter(out, OutputFormat.createCompactFormat()); try { out.write("<"); writer.write(element.getQualifiedName()); for (Attribute attr : (List<Attribute>) element.attributes()) { writer.write(attr); } writer.write(Namespace.get(this.element.getNamespacePrefix(), this.element.getNamespaceURI())); writer.write(Namespace.get("jabber:client")); out.write(">"); } catch (IOException ex) { log.info("Error writing XML", ex); } return out.toString(); }
Example #15
Source File: VersionedXmlDoc.java From onedev with MIT License | 6 votes |
public String toXML(boolean pretty) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { OutputFormat format = new OutputFormat(); format.setEncoding(StandardCharsets.UTF_8.name()); if (pretty) { format.setIndent(true); format.setIndentSize(4); format.setNewlines(true); } else { format.setIndent(false); format.setNewlines(false); } new XMLWriter(baos, format).write(getWrapped()); return baos.toString(StandardCharsets.UTF_8.name()); } catch (Exception e) { throw ExceptionUtils.unchecked(e); } }
Example #16
Source File: Identity.java From hermes with Apache License 2.0 | 6 votes |
private static Document creXmlDoc(String xmlStr) { if (Strings.empty(xmlStr)) { throw new RuntimeException("参数不能为空"); } SAXReader saxReader = new SAXReader(); Document document = null; try { document = saxReader.read(new ByteArrayInputStream(xmlStr.getBytes("UTF-8"))); Element rootElement = document.getRootElement(); String getXMLEncoding = document.getXMLEncoding(); String rootname = rootElement.getName(); System.out.println("getXMLEncoding>>>" + getXMLEncoding + ",rootname>>>" + rootname); OutputFormat format = OutputFormat.createPrettyPrint(); /** 指定XML字符集编码 */ format.setEncoding("UTF-8"); Logger.info(xmlStr); } catch (Exception e) { e.printStackTrace(); } return document; }
Example #17
Source File: QTIExportImportTest.java From olat with Apache License 2.0 | 6 votes |
private static QTIDocument exportAndImportToQTIFormat(QTIDocument qtiDocOrig) throws IOException { Document qtiXmlDoc = qtiDocOrig.getDocument(); OutputFormat outformat = OutputFormat.createPrettyPrint(); String fileName = qtiDocOrig.getAssessment().getTitle() + "QTIFormat.xml"; OutputStreamWriter qtiXmlOutput = new OutputStreamWriter(new FileOutputStream(new File(TEMP_DIR, fileName)), Charset.forName("UTF-8")); XMLWriter writer = new XMLWriter(qtiXmlOutput, outformat); writer.write(qtiXmlDoc); writer.flush(); writer.close(); XMLParser xmlParser = new XMLParser(new IMSEntityResolver()); Document doc = xmlParser.parse(new FileInputStream(new File(TEMP_DIR, fileName)), true); ParserManager parser = new ParserManager(); QTIDocument qtiDocRestored = (QTIDocument) parser.parse(doc); return qtiDocRestored; }
Example #18
Source File: ScriptExportXML.java From unitime with Apache License 2.0 | 5 votes |
@Override public void export(ExportHelper helper) throws IOException { String s = helper.getParameter("script"); if (s == null) throw new IllegalArgumentException("No script provided, please set the script parameter."); Script script = ScriptDAO.getInstance().get(Long.valueOf(s)); if (script == null) throw new IllegalArgumentException("Stript " + s + " does not exist."); helper.getSessionContext().checkPermission(Right.ScriptEdit); helper.setup("text/xml", script.getName().replace('/', '-').replace('\\', '-').replace(':', '-') + ".xml", false); Document document = DocumentHelper.createDocument(); Element scriptEl = document.addElement("script"); scriptEl.addAttribute("name", script.getName()); if (script.getPermission() != null) scriptEl.addAttribute("permission", script.getPermission()); scriptEl.addAttribute("engine", script.getEngine()); if (script.getDescription() != null) scriptEl.addElement("description").add(new DOMCDATA(script.getDescription())); for (ScriptParameter parameter: script.getParameters()) { Element paramEl = scriptEl.addElement("parameter"); paramEl.addAttribute("name", parameter.getName()); if (parameter.getLabel() != null) paramEl.addAttribute("label", parameter.getLabel()); paramEl.addAttribute("type", parameter.getType()); if (parameter.getDefaultValue() != null) paramEl.addAttribute("default", parameter.getDefaultValue()); } if (script.getScript() != null) scriptEl.addElement("body").add(new DOMCDATA(script.getScript())); scriptEl.addAttribute("created", new Date().toString()); OutputStream out = helper.getOutputStream(); new XMLWriter(out, OutputFormat.createPrettyPrint()).write(document); }
Example #19
Source File: XMLUtil.java From APICloud-Studio with GNU General Public License v3.0 | 5 votes |
public static String formatXml(String str) throws Exception { Document document = null; document = DocumentHelper.parseText(str.trim()); // 格式化输出格式 OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding("UTF-8"); StringWriter writer = new StringWriter(); // 格式化输出流 XMLWriter xmlWriter = new XMLWriter(writer, format); // 将document写入到输出流 xmlWriter.write(document); xmlWriter.close(); return writer.toString(); }
Example #20
Source File: XmlClobType.java From unitime with Apache License 2.0 | 5 votes |
public void nullSafeSet(PreparedStatement ps, Object value, int index, SessionImplementor session) throws SQLException, HibernateException { if (value == null) { ps.setNull(index, sqlTypes()[0]); } else { try { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); XMLWriter writer = new XMLWriter(bytes,OutputFormat.createCompactFormat()); writer.write((Document)value); writer.flush(); writer.close(); ps.setCharacterStream(index, new CharArrayReader(bytes.toString().toCharArray(),0,bytes.size()), bytes.size()); } catch (IOException e) { throw new HibernateException(e.getMessage(),e); } } }
Example #21
Source File: ExamTest.java From unitime with Apache License 2.0 | 5 votes |
public void run() { try { if (iSolver.isRunning()) iSolver.stopSolver(); Solution solution = iSolver.lastSolution(); if (solution.getBestInfo()==null) { sLog.error("No best solution found."); } else solution.restoreBest(); sLog.info("Best solution:"+ToolBox.dict2string(solution.getExtendedInfo(),1)); sLog.info("Best solution found after "+solution.getBestTime()+" seconds ("+solution.getBestIteration()+" iterations)."); sLog.info("Number of assigned variables is "+solution.getModel().nrAssignedVariables(solution.getAssignment())); sLog.info("Total value of the solution is "+solution.getModel().getTotalValue(solution.getAssignment())); if (iSolver.getProperties().getPropertyBoolean("General.Save", false)) new ExamDatabaseSaver(iSolver).save(); File outFile = new File(iSolver.getProperties().getProperty("General.OutputFile",iSolver.getProperties().getProperty("General.Output")+File.separator+"solution.xml")); FileOutputStream fos = new FileOutputStream(outFile); (new XMLWriter(fos,OutputFormat.createPrettyPrint())).write(((ExamModel)solution.getModel()).save(solution.getAssignment())); fos.flush();fos.close(); Test.createReports((ExamModel)solution.getModel(), solution.getAssignment(), outFile.getParentFile(), outFile.getName().substring(0,outFile.getName().lastIndexOf('.'))); Progress.removeInstance(solution.getModel()); } catch (Exception e) { e.printStackTrace(); } }
Example #22
Source File: DOM4JSerializer.java From Pushjet-Android with BSD 2-Clause "Simplified" License | 5 votes |
public static void exportToFile(ExportInteraction exportInteraction, ExtensionFileFilter fileFilter, DOM4JSettingsNode settingsNode) { File file = promptForFile(exportInteraction, fileFilter); if (file == null) { //the user canceled. return; } FileOutputStream fileOutputStream = null; try { fileOutputStream = new FileOutputStream(file); } catch (FileNotFoundException e) { LOGGER.error("Could not write to file: " + file.getAbsolutePath(), e); exportInteraction.reportError("Could not write to file: " + file.getAbsolutePath()); return; } try { XMLWriter xmlWriter = new XMLWriter(fileOutputStream, OutputFormat.createPrettyPrint()); Element rootElement = settingsNode.getElement(); rootElement.detach(); Document document = DocumentHelper.createDocument(rootElement); xmlWriter.write(document); } catch (Throwable t) { LOGGER.error("Internal error. Failed to save.", t); exportInteraction.reportError("Internal error. Failed to save."); } finally { closeQuietly(fileOutputStream); } }
Example #23
Source File: MultiRepresentationTest.java From cacheonix-core with GNU Lesser General Public License v2.1 | 5 votes |
private void prettyPrint(Element element) { //System.out.println( element.asXML() ); try { OutputFormat format = OutputFormat.createPrettyPrint(); new XMLWriter( System.out, format ).write( element ); System.out.println(); } catch ( Throwable t ) { System.err.println( "Unable to pretty print element : " + t ); } }
Example #24
Source File: Dom4jManyToOneTest.java From cacheonix-core with GNU Lesser General Public License v2.1 | 5 votes |
public static void print(Element elt) throws Exception { OutputFormat outformat = OutputFormat.createPrettyPrint(); // outformat.setEncoding(aEncodingScheme); XMLWriter writer = new XMLWriter( System.out, outformat ); writer.write( elt ); writer.flush(); // System.out.println( elt.asXML() ); }
Example #25
Source File: XMLHelper.java From cacheonix-core with GNU Lesser General Public License v2.1 | 5 votes |
public static void dump(Element element) { try { // try to "pretty print" it OutputFormat outformat = OutputFormat.createPrettyPrint(); XMLWriter writer = new XMLWriter( System.out, outformat ); writer.write( element ); writer.flush(); System.out.println( "" ); } catch( Throwable t ) { // otherwise, just dump it System.out.println( element.asXML() ); } }
Example #26
Source File: JUnitFormatter.java From validatar with Apache License 2.0 | 5 votes |
/** * {@inheritDoc} * Writes out the report for the given testSuites in the JUnit XML format. */ @Override public void writeReport(List<TestSuite> testSuites) throws IOException { Document document = DocumentHelper.createDocument(); Element testSuitesRoot = document.addElement(TESTSUITES_TAG); // Output for each test suite for (TestSuite testSuite : testSuites) { Element testSuiteRoot = testSuitesRoot.addElement(TESTSUITE_TAG); testSuiteRoot.addAttribute(TESTS_ATTRIBUTE, Integer.toString(testSuite.queries.size() + testSuite.tests.size())); testSuiteRoot.addAttribute(NAME_ATTRIBUTE, testSuite.name); for (Query query : testSuite.queries) { Element queryNode = testSuiteRoot.addElement(TESTCASE_TAG).addAttribute(NAME_ATTRIBUTE, query.name); if (query.failed()) { String failureMessage = StringUtils.join(query.getMessages(), NEWLINE); queryNode.addElement(FAILED_TAG).addCDATA(failureMessage); } } for (Test test : testSuite.tests) { Element testNode = testSuiteRoot.addElement(TESTCASE_TAG).addAttribute(NAME_ATTRIBUTE, test.name); if (test.failed()) { Element target = testNode; if (test.isWarnOnly()) { testNode.addElement(SKIPPED_TAG); } else { target = testNode.addElement(FAILED_TAG); } target.addCDATA(NEWLINE + test.description + NEWLINE + StringUtils.join(test.getMessages(), NEWLINE)); } } } OutputFormat format = OutputFormat.createPrettyPrint(); XMLWriter writer = new XMLWriter(new FileWriter(outputFile), format); writer.write(document); writer.close(); }
Example #27
Source File: XmlUtil.java From SpringBootUnity with MIT License | 5 votes |
/** * xml转换为字符串 * * @param doc * @param encoding * @return * @throws Exception */ public static String toString(Document doc, String encoding) throws Exception { OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding(encoding); ByteArrayOutputStream byteOS = new ByteArrayOutputStream(); XMLWriter writer = new XMLWriter(new OutputStreamWriter(byteOS, encoding), format); writer.write(doc); writer.flush(); writer.close(); return byteOS.toString(encoding); }
Example #28
Source File: XmlUtil.java From SpringBootUnity with MIT License | 5 votes |
/** * 保存文档 * * @throws Exception */ public static void save(Document doc, String xmlPath, String encoding) throws Exception { OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding(encoding); XMLWriter writer = new XMLWriter(new OutputStreamWriter(new FileOutputStream(xmlPath), encoding), format); writer.write(doc); writer.flush(); writer.close(); }
Example #29
Source File: FeedsApiControllerV1.java From gocd with Apache License 2.0 | 5 votes |
public static String prettyPrint(Document document) throws IOException { StringWriter writer = new StringWriter(); OutputFormat format = OutputFormat.createPrettyPrint(); format.setNewLineAfterDeclaration(false); format.setIndentSize(2); new XMLWriter(writer, format).write(document); return writer.toString(); }
Example #30
Source File: AddMessages.java From spotbugs with GNU Lesser General Public License v2.1 | 5 votes |
@SuppressFBWarnings("DM_EXIT") public static void main(String[] args) throws Exception { if (args.length != 2) { System.err.println("Usage: " + AddMessages.class.getName() + " <input collection> <output collection>"); System.exit(1); } // Load plugins, in order to get message files DetectorFactoryCollection.instance(); String inputFile = args[0]; String outputFile = args[1]; Project project = new Project(); SortedBugCollection inputCollection = new SortedBugCollection(project); inputCollection.readXML(inputFile); Document document = inputCollection.toDocument(); AddMessages addMessages = new AddMessages(inputCollection, document); addMessages.execute(); XMLWriter writer = new XMLWriter(new BufferedOutputStream(new FileOutputStream(outputFile)), OutputFormat.createPrettyPrint()); writer.write(document); writer.close(); }