List of usage examples for org.dom4j DocumentHelper createDocument
public static Document createDocument()
From source file:controler.ExportDataToXML.java
public ExportDataToXML() throws UnsupportedEncodingException, IOException { ArrayList<Password> data = ApplicationData.getPasswords(); Document document = DocumentHelper.createDocument(); Element root = document.addElement("Registos"); Element registo;/*from w ww. j a va2s . c om*/ int ord = 0; for (Password reg : data) { ord++; registo = root.addElement("Registo").addAttribute("num", "" + ord); registo.addElement("titulo").addText(reg.getTitle()); registo.addElement("user").addText(reg.getUser()); registo.addElement("pass").addText(reg.getPass()); registo.addElement("site").addText(reg.getSite()); registo.addElement("nota").addText(reg.getNote()); } // Pretty print the document to System.out OutputFormat format = OutputFormat.createPrettyPrint(); XMLWriter writer; writer = new XMLWriter(System.out, format); writer.write(document); //write to file FileOutputStream fos = new FileOutputStream("cyphDados.xml"); writer = new XMLWriter(fos, format); writer.write(document); //fos.close(); }
From source file:core.harvesters.Harvester.java
private void createStatistics() { if (metadataFormat.equals("dc")) { int i = 0; for (Record record : records) { observer.analayzingRecords(i); String license = getMetadataValue("rights", record); String formatExtension = getMetadataValue("format", record); String date = getMetadataValue("date", record); if (licenses.containsKey(license)) { int newValue = licenses.get(license) + 1; licenses.remove(license); licenses.put(license, newValue); } else { licenses.put(license, 1); }/*from w w w.j a v a2 s.c o m*/ if (formatExtensions.containsKey(formatExtension)) { int newValue = formatExtensions.get(formatExtension) + 1; formatExtensions.remove(formatExtension); formatExtensions.put(formatExtension, newValue); } else { formatExtensions.put(formatExtension, 1); } if (dates.containsKey(date)) { int newValue = dates.get(date) + 1; dates.remove(date); dates.put(date, newValue); } else { dates.put(date, 1); } i++; } } else if (metadataFormat.equals("p3dm")) { int i = 0; for (Record record : records) { observer.analayzingRecords(i); String license = getElement("LICENSE", record).attributeValue("NAME"); String formatExtension = getElement("MODELFILES", record).element("MODELFILE") .elementText("EXTENSION"); String date = getElement("DATES", record).element("DATEAVAILABLE").getText(); if (licenses.containsKey(license)) { int newValue = licenses.get(license) + 1; licenses.remove(license); licenses.put(license, newValue); } else { licenses.put(license, 1); } if (formatExtensions.containsKey(formatExtension)) { int newValue = formatExtensions.get(formatExtension) + 1; formatExtensions.remove(formatExtension); formatExtensions.put(formatExtension, newValue); } else { formatExtensions.put(formatExtension, 1); } if (dates.containsKey(date)) { int newValue = dates.get(date) + 1; dates.remove(date); dates.put(date, newValue); } else { dates.put(date, 1); } i++; } } else { return; } statisticsXml = DocumentHelper.createDocument(); Element root = statisticsXml.addElement("StatisticalData"); root.addAttribute("harvesterUrl", url); root.addElement("DocumentCount").setText(String.valueOf(documentCount)); Element licensesElement = root.addElement("Licenses"); for (Entry<String, Integer> e : this.licenses.entrySet()) { Element elem = licensesElement.addElement("License"); elem.addAttribute("id", e.getKey()); elem.setText(e.getValue().toString()); } PieChart pie = new PieChart("Licenses overview", licenses); File fileLicensesPie = new File( new StringBuilder().append(savePath).append(File.separator).append("licenses.png").toString()); pie.generateImage(300, 250, fileLicensesPie); Element datesElement = root.addElement("Dates"); for (Entry<String, Integer> e : this.dates.entrySet()) { Element elem = datesElement.addElement("Date"); elem.addAttribute("id", e.getKey()); elem.setText(e.getValue().toString()); } Histogram histoDates = new Histogram("\"Documents added on\" overview", dates, 0); File histoDatesFile = new File( new StringBuilder().append(savePath).append(File.separator).append("dates.png").toString()); histoDates.generateImage(500, 500, histoDatesFile); Element formatsElement = root.addElement("Formats"); for (Entry<String, Integer> e : this.formatExtensions.entrySet()) { Element elem = formatsElement.addElement("Format"); elem.addAttribute("id", e.getKey()); elem.setText(e.getValue().toString()); } Histogram histoFormats = new Histogram("Documents format overview", formatExtensions, 1); File histoFormatsFile = new File( new StringBuilder().append(savePath).append(File.separator).append("formats.png").toString()); histoFormats.generateImage(500, 500, histoFormatsFile); // load the transformer using JAXP TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = null; try { transformer = factory.newTransformer( new StreamSource(getClass().getResourceAsStream("/src/main/resources/statistics.xsl"))); } catch (TransformerConfigurationException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } // now lets style the given document DocumentSource source = new DocumentSource(statisticsXml); DocumentResult result = new DocumentResult(); try { transformer.transform(source, result); } catch (TransformerException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } // return the transformed document statisticsHtml = result.getDocument(); }
From source file:cz.dasnet.dasik.Dasik.java
License:Open Source License
@Override protected void onConnect() { log.info("Connected on " + getServer()); auth();/*from ww w.ja v a 2 s . c o m*/ if (authed) { requestInvites(); } final Dasik bot = this; try { Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { bot.joinChannels(); } }, 1000); TimerTask dumpTask = new TimerTask() { @Override public void run() { Document document = DocumentHelper.createDocument(); Element channelinfo = document.addElement("channelinfo"); for (String c : activeChannels.keySet()) { Element channel = channelinfo.addElement("channel"); Element name = channel.addElement("name"); name.setText(c); Element size = channel.addElement("size"); size.setText("" + getUsers(c).length); } Element updatetime = channelinfo.addElement("updatetime"); updatetime.setText(new Long(new Date().getTime() / 1000).toString()); try { XMLWriter writer = new XMLWriter(new FileWriter("channelinfo.xml")); writer.write(document); writer.close(); } catch (IOException ex) { log.error("Unable to dump channel info", ex); } } }; Timer dump = new Timer("dump", true); dump.schedule(dumpTask, 10000, 60000); } catch (Exception ex) { this.joinChannels(); log.error("Channel autojoin timer failed to schedule the task.", ex); } }
From source file:de.ailis.xadrian.data.Complex.java
License:Open Source License
/** * Converts the complex into XML and returns it. * * @return The complex as XML/*from www . j av a 2 s .c om*/ */ public Document toXML() { final Document document = DocumentHelper.createDocument(); final Element root = document.addElement("complex"); root.addAttribute("version", "4"); root.addAttribute("game", this.game.getId()); root.addAttribute("suns", Integer.toString(getSuns().getPercent())); if (this.sector != null) root.addAttribute("sector", this.sector.getId()); root.addAttribute("addBaseComplex", Boolean.toString(this.addBaseComplex)); root.addAttribute("showingProductionStats", Boolean.toString(this.showingProductionStats)); root.addAttribute("showingShoppingList", Boolean.toString(this.showingShoppingList)); root.addAttribute("showingStorageCapacities", Boolean.toString(this.showingStorageCapacities)); root.addAttribute("showingComplexSetup", Boolean.toString(this.showingComplexSetup)); if (!this.factories.isEmpty()) { final Element factoriesE = root.addElement("complexFactories"); for (final ComplexFactory factory : this.factories) { final Element factoryE = factoriesE.addElement("complexFactory"); factoryE.addAttribute("factory", factory.getFactory().getId()); factoryE.addAttribute("disabled", Boolean.toString(factory.isDisabled())); if (factory.getFactory().isMine()) { final Element yieldsE = factoryE.addElement("yields"); for (final Integer yield : factory.getYields()) { final Element yieldE = yieldsE.addElement("yield"); yieldE.setText(Integer.toString(yield)); } } else { factoryE.addAttribute("quantity", Integer.toString(factory.getQuantity())); } } } if (!this.customPrices.isEmpty()) { final Element waresE = root.addElement("complexWares"); for (final Map.Entry<Ware, Integer> entry : this.customPrices.entrySet()) { final Ware ware = entry.getKey(); final int price = entry.getValue(); final Element wareE = waresE.addElement("complexWare"); wareE.addAttribute("ware", ware.getId()); wareE.addAttribute("use", Boolean.valueOf(price > 0).toString()); wareE.addAttribute("price", Integer.toString(Math.abs(price))); } } final Element shoppingListE = root.addElement("built"); shoppingListE.addAttribute("kits", Integer.toString(this.builtKits)); for (final Entry<String, Integer> entry : this.builtFactories.entrySet()) { final String id = entry.getKey(); final int quantity = entry.getValue(); final Element factoryE = shoppingListE.addElement("factory"); factoryE.addAttribute("id", id); factoryE.addAttribute("quantity", Integer.toString(quantity)); } return document; }
From source file:de.decoit.siemgui.service.converter.NeustaCorrelationRuleConverter.java
License:Open Source License
/** * Create a rule XML document from domain object information. * * @param description Rule description string * @param cond Rule condition object// w w w . ja v a 2 s. c o m * @param action Rule action object * @return Created XML document */ private Document createRuleXmlDocument(String description, CorrelationRuleCondition cond, CorrelationRuleAction action) { Document doc = DocumentHelper.createDocument(); Element eRule = doc.addElement("rule"); // Create the <rule><description>...</description></rule> block if (description != null) { eRule.addElement("description").addText(description); } // Create the <rule><condition><query>...</query></condition></rule> block if (cond.getQuery() != null) { eRule.addElement("condition").addElement("query").addText(cond.getQuery()); } // Create the <rule><action></action></rule> element Element eAction = eRule.addElement("action"); // Create the <rule><action><incidentname>...</incidentname></action></rule> block if (action.getIncidentName() != null) { eAction.addElement("incidentname").addText(action.getIncidentName()); } // Create the <rule><action><risk>...</risk></action></rule> block if (action.getRisk() != null) { eAction.addElement("risk").addText(action.getRisk()); } // Create the <rule><action><query>...</query></action></rule> blocks (multiple) action.getQuery().stream().forEach((q) -> { eAction.addElement("query").addText(q); }); // Create the <rule><action><updatequery>...</updatequery></action></rule> blocks (multiple) action.getUpdateQuery().stream().forEach((uq) -> { eAction.addElement("updatequery").addText(uq); }); // Create the <rule><action><recommendation>...</recommendation></action></rule> blocks (multiple) action.getRecommendation().stream().forEach((r) -> { eAction.addElement("recommendation").addText(r); }); // Create the <rule><action><explanation>...</explanation></action></rule> blocks (multiple) action.getExplanation().stream().forEach((e) -> { eAction.addElement("explanation").addText(e); }); return doc; }
From source file:de.innovationgate.webgate.api.WGCSSJSModule.java
License:Open Source License
/** * If codetype is XML, returns the contained XML-code as dom Document. * @throws DocumentException/*from w w w . j a v a 2s . c o m*/ * @throws WGAPIException */ public Document getDOMDocument() throws DocumentException, WGAPIException { if (!getCodeType().equals(CODETYPE_XML)) { return DocumentHelper.createDocument(); } return DocumentHelper.parseText(getCode()); }
From source file:de.innovationgate.wga.server.api.Xml.java
License:Open Source License
/** * Creates a new empty DOM document */ public Document create() throws WGException { return DocumentHelper.createDocument(); }
From source file:de.innovationgate.wgpublisher.webtml.Root.java
License:Open Source License
private void enableDebug(HttpSession session, Status status) { Document doc = DocumentHelper.createDocument(); Element rootElement = doc.addElement("tmldebugdocument"); rootElement.addAttribute("url", WGUtils.reduce(getStatus().getRequestURL(), 100)); rootElement.addAttribute("started", DEBUG_TIMESTAMP_FORMAT.format(new Date())); rootElement.addAttribute("traceresults", String.valueOf(session.getAttribute(WGACore.ATTRIB_TMLDEBUG_TRACE_RESULTS))); rootElement.addAttribute("traceoptions", String.valueOf(session.getAttribute(WGACore.ATTRIB_TMLDEBUG_TRACE_OPTIONS))); rootElement.addAttribute("ajax", status._ajax ? "true" : "false"); List<Document> debugDocuments = WGACore.getDebugDocumentsList(session); debugDocuments.add(doc);/* w ww.j av a 2 s . c om*/ createDebugNode(rootElement); status.iterationDebugNode = status.debugNode.addElement("starttag"); try { getStatus().debugNode.addAttribute("context", getTMLContext().getpath()); } catch (WGAPIException e) { getStatus().debugNode.addAttribute("context", "Unable to retrieve contextpath bc. of exception: " + e.getClass().getName() + " message: " + e.getMessage()); } }
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 ww w. j av a 2 s.c om*/ } 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);/* ww w .j a v a2s .c o 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("]!")); }