List of usage examples for org.dom4j.io XMLWriter flush
public void flush() throws IOException
From source file:com.xpn.xwiki.objects.BaseElement.java
License:Open Source License
protected void fromXML(Element oel) throws XWikiException { // Serialize the Document (could not find a way to convert a dom4j Element into a usable StAX source) StringWriter writer = new StringWriter(); try {//from ww w . jav a 2 s . c o m org.dom4j.io.XMLWriter domWriter = new org.dom4j.io.XMLWriter(writer); domWriter.write(oel); domWriter.flush(); } catch (IOException e) { throw new XWikiException(XWikiException.MODULE_XWIKI_DOC, XWikiException.ERROR_DOC_XML_PARSING, "Error parsing xml", e, null); } // Actually parse the XML fromXML(writer.toString()); }
From source file:condorclient.utilities.XMLHandler.java
public String createName_IdXML() { String strXML = null;//w ww.j a v a 2s. co m Document document = DocumentHelper.createDocument(); // document. Element root = document.addElement("root"); Element info = root.addElement("info"); Element job = info.addElement("job"); job.addAttribute("name", "test"); job.addAttribute("id", "0"); StringWriter strWtr = new StringWriter(); OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding("UTF-8"); XMLWriter xmlWriter = new XMLWriter(strWtr, format); try { xmlWriter.write(document); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } strXML = strWtr.toString(); //-------- //------- //strXML=document.asXML(); //------ //------------- File file = new File("niInfo.xml"); if (file.exists()) { file.delete(); } try { file.createNewFile(); XMLWriter out = new XMLWriter(new FileWriter(file)); out.write(document); out.flush(); out.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } //-------------- return strXML; }
From source file:condorclient.utilities.XMLHandler.java
public String createXML() { String strXML = null;//from w ww . j av a2 s. co m Document document = DocumentHelper.createDocument(); // document. Element root = document.addElement("root"); Element job = root.addElement("Job"); Element jobDescFile = job.addElement("item"); jobDescFile.addAttribute("about", "descfile"); Element file_name = jobDescFile.addElement("name"); file_name.addText("submit.txt"); Element filer_path = jobDescFile.addElement("path"); filer_path.addText("D:\\HTCondor\\test\\2"); StringWriter strWtr = new StringWriter(); OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding("UTF-8"); XMLWriter xmlWriter = new XMLWriter(strWtr, format); try { xmlWriter.write(document); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } strXML = strWtr.toString(); //-------- //------- //strXML=document.asXML(); //------ //------------- File file = new File("condorclient.xml"); if (file.exists()) { file.delete(); } try { file.createNewFile(); XMLWriter out = new XMLWriter(new FileWriter(file)); out.write(document); out.flush(); out.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } //-------------- return strXML; }
From source file:controllers.FXMLScicumulusController.java
public void createScicumulusXML() throws IOException, Exception { paneGraph.requestFocus();//Altera o foco para o paneGraph this.fieldsRequired = Arrays.asList(txtTagWorkflow, txtDescriptionWorkflow, txtExecTagWorkflow, txtExpDirWorkflow, txtNameDatabase, txtServerDatabase, txtPortDatabase, txtUsernameDatabase, txtPasswordDatabase, txt_server_directory); //Monta o arquivo Scicumulus.xml // if (!isFieldEmpty()) { //Cria o diretrio de expanso this.directoryExp = dirProject.getAbsolutePath() + "/" + txtExpDirWorkflow.getText().trim(); File dir = new File(this.directoryExp); dir.mkdirs();/* w ww .ja v a2 s. co m*/ File dirPrograms = new File(this.directoryExp + "/programs"); // this.directoryPrograms = dirPrograms.getPath(); dirPrograms.mkdir(); setDataActivity(this.activity);//Utilizado para gravar a ltima activity Document doc = DocumentFactory.getInstance().createDocument(); Element root = doc.addElement("SciCumulus"); Element environment = root.addElement("environment"); environment.addAttribute("type", "LOCAL"); Element binary = root.addElement("binary"); binary.addAttribute("directory", this.directoryExp + "/bin"); binary.addAttribute("execution_version", "SCCore.jar"); Element constraint = root.addElement("constraint"); constraint.addAttribute("workflow_exectag", "montage-1"); constraint.addAttribute("cores", this.txt_cores_machines.getText()); Element workspace = root.addElement("workspace"); workspace.addAttribute("workflow_dir", this.dirProject.getAbsolutePath()); Element database = root.addElement("database"); database.addAttribute("name", txtNameDatabase.getText()); database.addAttribute("server", txtServerDatabase.getText()); database.addAttribute("port", txtPortDatabase.getText()); database.addAttribute("username", txtUsernameDatabase.getText()); database.addAttribute("password", txtPasswordDatabase.getText()); Element hydraWorkflow = root.addElement("conceptualWorkflow"); hydraWorkflow.addAttribute("tag", txtTagWorkflow.getText().replace(" ", "").trim()); hydraWorkflow.addAttribute("description", txtDescriptionWorkflow.getText()); hydraWorkflow.addAttribute("exectag", txtExecTagWorkflow.getText()); hydraWorkflow.addAttribute("expdir", this.directoryExp); Element hydraActivity; for (Activity act : this.activities) { hydraActivity = hydraWorkflow.addElement("activity"); hydraActivity.addAttribute("tag", act.getTag().replace(" ", "").trim()); hydraActivity.addAttribute("description", act.getDescription()); hydraActivity.addAttribute("type", act.getType()); hydraActivity.addAttribute("template", act.getTemplatedir()); hydraActivity.addAttribute("activation", act.getActivation()); hydraActivity.addAttribute("extractor", "./extractor.cmd"); dir = new File(this.directoryExp + "/template_" + act.getName()); dir.mkdirs(); //Criando arquivo experiment.cmd File fout = new File(dir.getPath() + "/" + "experiment.cmd"); FileOutputStream fos = new FileOutputStream(fout); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos)); for (String command : act.getCommands()) { bw.write("sleep " + chb_sleeptime.getValue().toString()); bw.newLine(); bw.write(command); bw.newLine(); } bw.close(); String input = new String(); String output = new String(); int cont = 0; for (Relation rel : this.relations) { if (act.equals(rel.nodeStart)) { if (cont == 0) { //Primeira entrada Element relation1 = hydraActivity.addElement("relation"); relation1.addAttribute("reltype", "Input"); relation1.addAttribute("name", "I" + act.getName()); // relation1.addAttribute("filename", act.getInput_filename());//Colocar o nome do arquivo } Element relation2 = hydraActivity.addElement("relation"); relation2.addAttribute("reltype", "Output"); relation2.addAttribute("name", "O" + act.getName()); // relation2.addAttribute("filename", act.getOutput_filename());//Colocar o nome do arquivo // input = "I"+act.getName(); } if (act.equals(rel.nodeEnd)) { Activity dependency = (Activity) rel.nodeStart; Element relation1 = hydraActivity.addElement("relation"); relation1.addAttribute("reltype", "Input"); relation1.addAttribute("name", "I" + act.getName()); relation1.addAttribute("filename", act.getInput_filename());//Colocar o nome do arquivo relation1.addAttribute("dependency", dependency.getTag());//Colocar o nome da dependncia se existir if (cont == this.relations.size() - 1) { //ltima sada Element relation2 = hydraActivity.addElement("relation"); relation2.addAttribute("reltype", "Output"); relation2.addAttribute("name", "O" + act.getName()); // relation2.addAttribute("filename", act.getOutput_filename());//Colocar o nome do arquivo } // output = "O"+act.getName(); } cont++; } input = "I" + act.getName(); output = "O" + act.getName(); for (Field fieldAct : act.getFields()) { Element field = hydraActivity.addElement("field"); field.addAttribute("name", fieldAct.getName()); field.addAttribute("type", fieldAct.getType()); field.addAttribute("input", input); if (!fieldAct.getType().equals("string")) { field.addAttribute("output", output); } if (fieldAct.getType().equals("float")) { field.addAttribute("decimalplaces", fieldAct.getDecimalPlaces()); } if (fieldAct.getType().equals("file")) { field.addAttribute("operation", fieldAct.getOperation()); } } // String input = new String(); // String output = new String(); // // int cont = 0; // for (Relation rel : this.relations) { // if (act.equals(rel.nodeStart)) { // if (cont == 0) { // //Primeira entrada // Element relation1 = hydraActivity.addElement("relation"); // relation1.addAttribute("reltype", "Input"); // relation1.addAttribute("name", rel.getName() + "_" + "input"); //// relation1.addAttribute("filename", act.getInput_filename());//Colocar o nome do arquivo // } // Element relation2 = hydraActivity.addElement("relation"); // relation2.addAttribute("reltype", "Output"); // relation2.addAttribute("name", rel.getName() + "_" + "output"); //// relation2.addAttribute("filename", act.getOutput_filename());//Colocar o nome do arquivo // // input = rel.getName(); // } // if (act.equals(rel.nodeEnd)) { // Activity dependency = (Activity) rel.nodeStart; // Element relation1 = hydraActivity.addElement("relation"); // relation1.addAttribute("reltype", "Input"); // relation1.addAttribute("name", rel.getName() + "_" + "input"); // relation1.addAttribute("filename", act.getInput_filename());//Colocar o nome do arquivo // relation1.addAttribute("dependency", dependency.getTag());//Colocar o nome da dependncia se existir // // if (cont == this.relations.size() - 1) { // //ltima sada // Element relation2 = hydraActivity.addElement("relation"); // relation2.addAttribute("reltype", "Output"); // relation2.addAttribute("name", rel.getName() + "_" + "output"); //// relation2.addAttribute("filename", act.getOutput_filename());//Colocar o nome do arquivo // } // output = rel.getName(); // } // cont++; // } // Element field = hydraActivity.addElement("field"); // field.addAttribute("name", "FASTA_FILE"); // field.addAttribute("type", "string"); // field.addAttribute("input", input); // field.addAttribute("output", output); Element file = hydraActivity.addElement("File"); file.addAttribute("filename", "experiment.cmd"); file.addAttribute("instrumented", "true"); } Element executionWorkflow = root.addElement("executionWorkflow"); executionWorkflow.addAttribute("tag", txtTagWorkflow.getText().replace(" ", "").trim()); executionWorkflow.addAttribute("execmodel", "DYN_FAF"); executionWorkflow.addAttribute("expdir", this.directoryExp); executionWorkflow.addAttribute("max_failure", "1"); executionWorkflow.addAttribute("user_interaction", "false"); executionWorkflow.addAttribute("redundancy", "false"); executionWorkflow.addAttribute("reliability", "0.1"); Element relationInput = executionWorkflow.addElement("relation"); // relationInput.addAttribute("name", "IListFits"); relationInput.addAttribute("name", "input_workflow"); relationInput.addAttribute("filename", this.inputFile.getName()); //Gravando arquivo FileOutputStream fos = new FileOutputStream(this.directoryExp + "/SciCumulus.xml"); OutputFormat format = OutputFormat.createPrettyPrint(); XMLWriter writer = new XMLWriter(fos, format); writer.write(doc); writer.flush(); try { //Criando o arquivo machines.conf createMachinesConf(); //Criando o arquivo parameter.txt // createParameterTxt(ta_parameters.getText()); } catch (IOException ex) { Logger.getLogger(FXMLScicumulusController.class.getName()).log(Level.SEVERE, null, ex); } //Copiando arquivos para o diretrio programs Utils.copyFiles(this.dirPrograms, directoryExp + "/programs/"); Utils.copyFiles(this.inputFile, directoryExp + "/" + this.inputFile.getName()); // sendWorkflow(this.directoryExp, "/deploy/experiments"); // sendWorkflow(this.directoryExp, this.txt_server_directory.getText().trim()); // String[] dirComplete = this.directoryExp.split(this.directoryDefaultFiles)[1].split("/"); // String dirLocal = this.directoryDefaultFiles + dirComplete[0]; // sendWorkflow(dirLocal, this.txt_server_directory.getText().trim()); sendWorkflow(this.dirProject.getAbsolutePath(), this.txt_server_directory.getText().trim()); // }else{ // JOptionPane.showMessageDialog(null, "Preencha os campos obrigatrios!"); // } // if (isActivityEmpty()) { // Dialogs.create() // .owner(null) // .title("Activity Duplicate") // .masthead(null) // .message("Existe uma activity que no est conectada!") // .showInformation(); // } }
From source file:controllers.FXMLScicumulusController.java
private void saveProject(String file) throws FileNotFoundException, UnsupportedEncodingException, IOException { Document doc = DocumentFactory.getInstance().createDocument(); Element root = doc.addElement("SciCumulus"); root.addAttribute("nameProject", txt_name_workflow.getText().trim()); Element activities = root.addElement("activities"); activities.addAttribute("quant", Integer.toString(this.activities.size())); for (Activity act : this.activities) { Element activity = activities.addElement("activity"); activity.addAttribute("id", act.getIdObject()); activity.addAttribute("name", act.getName()); activity.addAttribute("login", act.getLogin()); activity.addAttribute("password", act.getPassword()); activity.addAttribute("tag", act.getTag()); activity.addAttribute("description", act.getDescription()); activity.addAttribute("type", act.getType()); activity.addAttribute("templatedir", act.getTemplatedir()); activity.addAttribute("activation", act.getActivation()); activity.addAttribute("input_filename", act.getInput_filename()); activity.addAttribute("output_filename", act.getOutput_filename()); activity.addAttribute("timeCommand", act.getTimeCommand().toString()); // activity.addAttribute("commands", act.getCommands().toString()); for (Field field : act.getFields()) { Element fields = activity.addElement("fields"); fields.addAttribute("name", field.getName()); fields.addAttribute("type", field.getType()); fields.addAttribute("operation", field.getOperation()); fields.addAttribute("decimalPlaces", field.getDecimalPlaces()); fields.addAttribute("input", field.getInput()); fields.addAttribute("output", field.getOutput()); }/*from w ww . j a va 2s .c o m*/ } Element relations = root.addElement("relations"); relations.addAttribute("quant", Integer.toString(this.relations.size())); for (Relation rel : this.relations) { Element relation = relations.addElement("relation"); relation.addAttribute("id", rel.getIdObject()); Activity actStart = (Activity) rel.getNodeStart(); Activity actEnd = (Activity) rel.getNodeEnd(); relation.addAttribute("name", rel.getName()); relation.addAttribute("idActStart", actStart.getIdObject()); relation.addAttribute("nameActStart", actStart.getName()); relation.addAttribute("idActEnd", actEnd.getIdObject()); relation.addAttribute("nameActEnd", actEnd.getName()); } //Gravando arquivo FileOutputStream fos = new FileOutputStream(file); OutputFormat format = OutputFormat.createPrettyPrint(); XMLWriter writer = new XMLWriter(fos, format); writer.write(doc); writer.flush(); }
From source file:controllers.ServiceController.java
License:Apache License
private boolean writeBodyToFile(String filename) { String xmlFile = filename + ".xml"; String jsonFile = filename + ".shape.json"; try {/*from w ww . j a v a 2 s. c o m*/ BufferedReader br = request.getReader(); boolean hasJson = false; StringBuffer buf = new StringBuffer(); //Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(xmlFile),"utf-8")); String inputLine; while ((inputLine = br.readLine()) != null) { if (inputLine.equals("===boundary===")) { /*?shapes*/ //writer.close(); //writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(jsonFile),"utf-8")); SAXReader reader = new SAXReader(); reader.setEntityResolver(new DTDEntityResolver()); Document document = reader.read(new StringReader(buf.toString())); OutputFormat format = new OutputFormat(" ", true); XMLWriter writer = new XMLWriter( new BufferedWriter(new OutputStreamWriter(new FileOutputStream(xmlFile), "utf-8")), format); writer.write(document); writer.flush(); writer.close(); hasJson = true; buf = new StringBuffer(); continue; } buf.append(inputLine).append("\n"); //writer.write(inputLine); //writer.write("\n"); } //writer.close(); br.close(); if (!hasJson) { Trace.write(Trace.Error, "write osworkflow: no json-shape define!"); return false; } String jsonString = buf.toString(); jsonString = formatJsonStrings(jsonString); if (jsonString == null) { Trace.write(Trace.Error, "write osworkflow[json]: " + buf.toString()); return false; } Writer jsonWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(jsonFile), "utf-8")); jsonWriter.write(jsonString); jsonWriter.close(); return true; } catch (DocumentException de) { Trace.write(Trace.Error, de, "write osworkflow[xml]."); } catch (IOException e) { Trace.write(Trace.Error, e, "write osworkflow."); } return false; }
From source file:cz.mzk.editor.server.fedora.utils.DocumentSaver.java
License:Open Source License
public static boolean writeDocument(Document document, OutputStream out, PrintType printType) { OutputFormat format = chooseOutputFormat(printType); try {/*from w ww. j a v a 2 s . c o m*/ XMLWriter writer = new XMLWriter(out, format); writer.write(document); writer.flush(); return true; } catch (UnsupportedEncodingException ex) { logger.log(Level.SEVERE, null, ex); return false; } catch (IOException ex) { logger.log(Level.SEVERE, null, ex); return false; } }
From source file:datasource.XMLTools.java
License:Open Source License
public static long writeToXML(Document doc, String Filename) { long errorcode = 0; try {/* w ww . j a v a2s. c o m*/ OutputFormat outformat = OutputFormat.createPrettyPrint(); outformat.setEncoding("UTF-8"); FileOutputStream out = new FileOutputStream(Filename); XMLWriter writer = new XMLWriter(out, outformat); writer.write(doc); writer.flush(); } catch (Exception x) { System.out.println(x.getMessage()); errorcode = x.hashCode(); } return errorcode; }
From source file:de.innovationgate.wgpublisher.lucene.LuceneIndexConfiguration.java
License:Open Source License
/** * writes the current configuration to file * @throws IOException/* ww w .j av a2 s . com*/ */ 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.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 w w w . ja v a2 s .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("]!")); }