List of usage examples for org.dom4j.io XMLWriter XMLWriter
public XMLWriter(OutputStream out, OutputFormat format) throws UnsupportedEncodingException
From source file:de.codecentric.multitool.xml.XmlLibrary.java
License:Apache License
/** * Konvertiert ein XML-Document in einen XML-String * //from w w w . j a va 2 s .co m * | ${xmlString} = | Get Xml From String | ${xmlDoc} | */ public String getStringFromXml(Document document) throws IOException { OutputFormat format = OutputFormat.createCompactFormat(); format.setSuppressDeclaration(true); StringWriter writer = new StringWriter(); XMLWriter xmlWriter = new XMLWriter(writer, format); xmlWriter.write(document); return writer.toString(); }
From source file:de.hasait.eclipse.common.xml.XDocument.java
License:Apache License
public String asFormattedXml(final String lineSeparator, final String indent, final boolean newlines, final boolean trimText) { StringWriter sw = new StringWriter(); try {/*from w w w .j ava 2s .c om*/ OutputFormat outputFormat = new OutputFormat(indent, newlines); outputFormat.setTrimText(trimText); outputFormat.setLineSeparator(lineSeparator); new XMLWriter(sw, outputFormat).write(_document); } catch (IOException e) { // Should not happen for StringWriter throw new RuntimeException(e); } return sw.getBuffer().toString(); }
From source file:de.hasait.eclipse.common.xml.XElement.java
License:Apache License
public String asFormattedXml(final String lineSeparator, final String indent, final boolean newlines, final boolean trimText) { StringWriter sw = new StringWriter(); try {/*w w w .ja va 2s. c om*/ OutputFormat outputFormat = new OutputFormat(indent, newlines); outputFormat.setTrimText(trimText); outputFormat.setLineSeparator(lineSeparator); new XMLWriter(sw, outputFormat).write(_element); } catch (IOException e) { // Should not happen for StringWriter throw new RuntimeException(e); } return sw.getBuffer().toString(); }
From source file:de.innovationgate.wgpublisher.lucene.LuceneIndexConfiguration.java
License:Open Source License
/** * writes the current configuration to file * @throws IOException/*from w ww. java 2 s . co m*/ */ private void writeConfigDoc() throws IOException { OutputFormat format = OutputFormat.createPrettyPrint(); XMLWriter writer = new XMLWriter(new FileWriter(_configFile), format); writer.write(_configDoc); writer.flush(); writer.close(); }
From source file:de.innovationgate.wgpublisher.WGACore.java
License:Open Source License
public String updateConfigDocument(Document newConfig) throws UnsupportedEncodingException, FileNotFoundException, IOException, ParserConfigurationException, DocumentException { String newTimestamp = WGACore.DATEFORMAT_GMT.format(new Date()); newConfig.getRootElement().addAttribute("timestamp", newTimestamp); OutputFormat outputFormat = OutputFormat.createPrettyPrint(); outputFormat.setTrimText(true);/*w w w. ja v a 2 s . c o m*/ outputFormat.setNewlines(true); XMLWriter writer = new XMLWriter(new FileOutputStream(getConfigFile()), outputFormat); writer.write(newConfig); writer.close(); return newTimestamp; }
From source file:de.matzefratze123.heavyspleef.persistence.handler.CachingReadWriteHandler.java
License:Open Source License
@Override public void saveGame(Game game) throws IOException { File gameFile = new File(xmlFolder, game.getName() + ".xml"); if (!gameFile.exists()) { gameFile.createNewFile();//from w ww .ja va2s . c o m } Document document = DocumentHelper.createDocument(); Element rootElement = document.addElement("game"); xmlContext.write(game, rootElement); File gameSchematicFolder = new File(schematicFolder, game.getName()); if (!gameSchematicFolder.exists()) { gameSchematicFolder.mkdir(); } XMLWriter writer = null; try { FileOutputStream out = new FileOutputStream(gameFile); writer = new XMLWriter(out, xmlOutputFormat); writer.write(document); } finally { if (writer != null) { writer.close(); } } for (Floor floor : game.getFloors()) { File floorFile = new File(gameSchematicFolder, getFloorFileName(floor)); if (!floorFile.exists()) { floorFile.createNewFile(); } schematicContext.write(floorFile, floor); } }
From source file:de.thischwa.pmcms.model.tool.WriteBackup.java
License:LGPL
@Override public void run() { logger.debug("Try to backup [" + site.getUrl() + "]."); if (monitor != null) monitor.beginTask(LabelHolder.get("task.backup.monitor").concat(" ").concat(String.valueOf(pageCount)), pageCount * 2 + 1);/*from ww w. j a v a2s.co m*/ // Create file infrastructure. File dataBaseXml = null; try { dataBaseXml = File.createTempFile("database", ".xml", Constants.TEMP_DIR.getAbsoluteFile()); } catch (IOException e1) { throw new RuntimeException( "Can't create temp file for the database xml file because: " + e1.getMessage(), e1); } Document dom = DocumentHelper.createDocument(); dom.setXMLEncoding(Constants.STANDARD_ENCODING); Element siteEl = dom.addElement("site").addAttribute("version", IBackupParser.DBXML_2).addAttribute("url", site.getUrl()); siteEl.addElement("title").addCDATA(site.getTitle()); Element elementTransfer = siteEl.addElement("transfer"); elementTransfer.addAttribute("host", site.getTransferHost()) .addAttribute("user", site.getTransferLoginUser()) .addAttribute("password", site.getTransferLoginPassword()) .addAttribute("startdir", site.getTransferStartDirectory()); for (Macro macro : site.getMacros()) { Element marcoEl = siteEl.addElement("macro"); marcoEl.addElement("name").addCDATA(macro.getName()); marcoEl.addElement("text").addCDATA(macro.getText()); } if (site.getLayoutTemplate() != null) { Template template = site.getLayoutTemplate(); Element templateEl = siteEl.addElement("template"); init(templateEl, template); } for (Template template : site.getTemplates()) { Element templateEl = siteEl.addElement("template"); init(templateEl, template); } if (!CollectionUtils.isEmpty(site.getPages())) for (Page page : site.getPages()) addPageToElement(siteEl, page); for (Level level : site.getSublevels()) addLevelToElement(siteEl, level); OutputStream out = null; try { // It's really important to use the XMLWriter instead of the FileWriter because the FileWriter takes the default // encoding of the OS. This my cause some trouble with special chars on some OSs! out = new BufferedOutputStream(new FileOutputStream(dataBaseXml)); OutputFormat outformat = OutputFormat.createPrettyPrint(); outformat.setEncoding(Constants.STANDARD_ENCODING); XMLWriter writer = new XMLWriter(out, outformat); writer.write(dom); writer.flush(); } catch (IOException e) { throw new FatalException("While exporting the database xml: " + e.getMessage(), e); } finally { IOUtils.closeQuietly(out); } // Generate the zip file, cache and export dir will be ignored. File backupZip = new File(InitializationManager.getSitesBackupDir(), site.getUrl().concat("_").concat(new SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date()) .concat(".").concat(Constants.BACKUP_EXTENSION))); List<File> filesToIgnore = new ArrayList<File>(); filesToIgnore.add(PoPathInfo.getSiteImageCacheDirectory(site).getAbsoluteFile()); filesToIgnore.add(PoPathInfo.getSiteExportDirectory(site).getAbsoluteFile()); Collection<File> filesToBackup = FileTool.collectFiles(PoPathInfo.getSiteDirectory(site).getAbsoluteFile(), filesToIgnore); File sitesDir = InitializationManager.getSitesDir(); Map<File, String> zipEntries = new HashMap<File, String>(); for (File file : filesToBackup) { String entryName = file.getAbsolutePath().substring(sitesDir.getAbsolutePath().length() + 1); entryName = StringUtils.replace(entryName, File.separator, "/"); // Slashes are zip conform zipEntries.put(file, entryName); incProgressValue(); } zipEntries.put(dataBaseXml, "db.xml"); try { if (monitor != null) monitor.beginTask(LabelHolder.get("zip.compress").concat(String.valueOf(zipEntries.size())), zipEntries.size()); Zip.compressFiles(backupZip, zipEntries, monitor); } catch (IOException e) { throw new FatalException("While generating zip: " + e.getMessage(), e); } dataBaseXml.delete(); logger.info("Site backuped successfull to [".concat(backupZip.getAbsolutePath()).concat("]!")); }
From source file:de.thischwa.pmcms.view.renderer.ExportRenderer.java
License:LGPL
/** * Start the export of the static html pages. * //from w w w . j av a 2 s . co m * @throws RuntimeException if an exception is happened during rendering. */ @Override public void run() { logger.debug("Entered run."); File siteDir = PoPathInfo.getSiteDirectory(this.site); if (monitor != null) monitor.beginTask( String.format("%s: %d", LabelHolder.get("task.export.monitor"), this.renderableObjects.size()), this.renderableObjects.size()); //$NON-NLS-1$ if (CollectionUtils.isEmpty(site.getPages())) renderRedirector(); try { FileUtils.cleanDirectory(exportDir); // build the directory structure for the renderables for (IRenderable ro : renderableObjects) { File dir = PathTool.getExportFile(ro, poExtension).getParentFile(); if (!dir.exists()) dir.mkdirs(); } // loop through the renderable objects renderRenderables(); if (!exportController.isError() && !isInterruptByUser) { logger.debug("Static export successfull!"); // extra files to copy Set<File> filesToCopy = renderData.getFilesToCopy(); for (File srcFile : filesToCopy) { String exportPathPart = srcFile.getAbsolutePath() .substring(siteDir.getAbsolutePath().length() + 1); File destFile = new File(exportDir, exportPathPart); if (srcFile.isFile()) FileUtils.copyFile(srcFile, destFile); } logger.debug("Extra files successful copied!"); // generate hashes Collection<File> exportedFiles = FileTool.collectFiles(exportDir); if (monitor != null) { monitor.done(); monitor.beginTask("Calculate checksums", exportedFiles.size()); } Document dom = ChecksumTool .getDomChecksums(ChecksumTool.get(exportedFiles, exportDir.getAbsolutePath(), monitor)); ByteArrayOutputStream out = new ByteArrayOutputStream(); OutputFormat outformat = OutputFormat.createPrettyPrint(); outformat.setEncoding(Constants.STANDARD_ENCODING); XMLWriter writer = new XMLWriter(out, outformat); writer.write(dom); writer.flush(); String formatedDomString = out.toString(); InputStream in = new ByteArrayInputStream(formatedDomString.getBytes()); Map<InputStream, String> toCompress = new HashMap<InputStream, String>(); toCompress.put(in, checksumFilename); File zipFile = new File(PoPathInfo.getSiteExportDirectory(site), FilenameUtils.getBaseName(checksumFilename) + ".zip"); Zip.compress(zipFile, toCompress); zipFile = null; } else FileUtils.cleanDirectory(exportDir); } catch (Exception e) { logger.error("Error while export: " + e.getMessage(), e); throw new FatalException("Error while export " + this.site.getUrl() + e.getMessage(), e); } finally { if (monitor != null) monitor.done(); } }
From source file:de.thischwa.pmcms.view.renderer.VelocityUtils.java
License:LGPL
/** * Replace the img-tag and a-tag with the equivalent velocity macro. Mainly used before saving a field value to the database. * //from w w w . j av a 2 s.co m * @throws RenderingException * If any exception was thrown while replacing the tags. */ @SuppressWarnings("unchecked") public static String replaceTags(final Site site, final String oldValue) throws RenderingException { if (StringUtils.isBlank(oldValue)) return null; // 1. add a root element (to have a proper xml) and replace the ampersand String newValue = String.format("<dummytag>\n%s\n</dummytag>", StringUtils.replace(oldValue, "&", ampReplacer)); Map<String, String> replacements = new HashMap<String, String>(); try { Document dom = DocumentHelper.parseText(newValue); dom.setXMLEncoding(Constants.STANDARD_ENCODING); // 2. Collect the keys, identify the img-tags. List<Node> imgs = dom.selectNodes("//img", "."); for (Node node : imgs) { Element element = (Element) node; if (element.attributeValue("src").startsWith("/")) // only internal links have to replaced with a velocity macro replacements.put(node.asXML(), generateVelocityImageToolCall(site, element.attributeIterator())); } // 3. Collect the keys, identify the a-tags List<Node> links = dom.selectNodes("//a", "."); for (Node node : links) { Element element = (Element) node; if (element.attributeValue("href").startsWith("/")) // only internal links have to replaced with a velocity macro replacements.put(element.asXML(), generateVelocityLinkToolCall(site, element)); } // 4. Replace the tags with the velomacro. StringWriter stringWriter = new StringWriter(); XMLWriter writer = new XMLWriter(stringWriter, sourceFormat); writer.write(dom.selectSingleNode("dummytag")); writer.close(); newValue = stringWriter.toString(); for (String stringToReplace : replacements.keySet()) newValue = StringUtils.replace(newValue, stringToReplace, replacements.get(stringToReplace)); newValue = StringUtils.replace(newValue, "<dummytag>", ""); newValue = StringUtils.replace(newValue, "</dummytag>", ""); } catch (Exception e) { throw new RenderingException("While preprocessing the field value: " + e.getMessage(), e); } return StringUtils.replace(newValue, ampReplacer, "&"); }
From source file:de.tud.kom.p2psim.impl.network.gnp.topology.HostMap.java
License:Open Source License
/** * saves host postion location, GNP position, groups, GNP Space, PingER * Lookup table in an xml file used within the simulation * //from w w w . j a v a 2s .c o m * @param file */ public void exportToXml(File file) { log.debug("Export Hosts to an XML File"); try { OutputFormat format = OutputFormat.createPrettyPrint(); OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(file), "UTF-8"); XMLWriter writer = new XMLWriter(out, format); writer.write(getDocument()); writer.close(); } catch (IOException e) { System.out.println(e); } }