List of usage examples for org.dom4j.io OutputFormat setIndent
public void setIndent(boolean doIndent)
From source file:com.wedian.site.common.utils.SettingUtils.java
License:Open Source License
/** * /*from ww w. j a v a2 s. c o m*/ * * @param setting * */ public static void set(Setting setting) { try { File shopxxXmlFile = new ClassPathResource(CommonAttributes.SITE_XML_PATH).getFile(); Document document = new SAXReader().read(shopxxXmlFile); List<Element> elements = document.selectNodes("/site/setting"); for (Element element : elements) { try { String name = element.attributeValue("name"); String value = beanUtils.getProperty(setting, name); Attribute attribute = element.attribute("value"); attribute.setValue(value); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } } FileOutputStream fileOutputStream = null; XMLWriter xmlWriter = null; try { OutputFormat outputFormat = OutputFormat.createPrettyPrint(); outputFormat.setEncoding("UTF-8"); outputFormat.setIndent(true); outputFormat.setIndent(" "); outputFormat.setNewlines(true); fileOutputStream = new FileOutputStream(shopxxXmlFile); xmlWriter = new XMLWriter(fileOutputStream, outputFormat); xmlWriter.write(document); } catch (Exception e) { e.printStackTrace(); } finally { if (xmlWriter != null) { try { xmlWriter.close(); } catch (IOException e) { } } IOUtils.closeQuietly(fileOutputStream); } Ehcache cache = cacheManager.getEhcache(Setting.CACHE_NAME); cache.put(new net.sf.ehcache.Element(Setting.CACHE_KEY, setting)); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.zg.action.admin.InstallAction.java
public String save() throws URISyntaxException, IOException, DocumentException { if (isInstalled()) { return ajaxJsonErrorMessage("SHOP++?????"); }/* www. j a v a 2s. co m*/ if (StringUtils.isEmpty(databaseHost)) { return ajaxJsonErrorMessage("?!"); } if (StringUtils.isEmpty(databasePort)) { return ajaxJsonErrorMessage("??!"); } if (StringUtils.isEmpty(databaseUsername)) { return ajaxJsonErrorMessage("???!"); } if (StringUtils.isEmpty(databasePassword)) { return ajaxJsonErrorMessage("??!"); } if (StringUtils.isEmpty(databaseName)) { return ajaxJsonErrorMessage("???!"); } if (StringUtils.isEmpty(adminUsername)) { return ajaxJsonErrorMessage("???!"); } if (StringUtils.isEmpty(adminPassword)) { return ajaxJsonErrorMessage("??!"); } if (StringUtils.isEmpty(installStatus)) { Map<String, String> jsonMap = new HashMap<String, String>(); jsonMap.put(STATUS, "requiredCheckFinish"); return ajaxJson(jsonMap); } String jdbcUrl = "jdbc:mysql://" + databaseHost + ":" + databasePort + "/" + databaseName + "?useUnicode=true&characterEncoding=UTF-8"; Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { // ? connection = DriverManager.getConnection(jdbcUrl, databaseUsername, databasePassword); DatabaseMetaData databaseMetaData = connection.getMetaData(); String[] types = { "TABLE" }; resultSet = databaseMetaData.getTables(null, databaseName, "%", types); if (StringUtils.equalsIgnoreCase(installStatus, "databaseCheck")) { Map<String, String> jsonMap = new HashMap<String, String>(); jsonMap.put(STATUS, "databaseCheckFinish"); return ajaxJson(jsonMap); } // ? if (StringUtils.equalsIgnoreCase(installStatus, "databaseCreate")) { StringBuffer stringBuffer = new StringBuffer(); BufferedReader bufferedReader = null; String sqlFilePath = Thread.currentThread().getContextClassLoader().getResource("").toURI() .getPath() + SQL_INSTALL_FILE_NAME; bufferedReader = new BufferedReader( new InputStreamReader(new FileInputStream(sqlFilePath), "UTF-8")); String line = ""; while (null != line) { line = bufferedReader.readLine(); stringBuffer.append(line); if (null != line && line.endsWith(";")) { System.out.println("[SHOP++?]SQL: " + line); preparedStatement = connection.prepareStatement(stringBuffer.toString()); preparedStatement.executeUpdate(); stringBuffer = new StringBuffer(); } } String insertAdminSql = "INSERT INTO `admin` VALUES ('402881862bec2a21012bec2bd8de0003','2010-10-10 0:0:0','2010-10-10 0:0:0','','admin@shopxx.net',b'1',b'0',b'0',b'0',NULL,NULL,0,NULL,'?','" + DigestUtils.md5Hex(adminPassword) + "','" + adminUsername + "');"; String insertAdminRoleSql = "INSERT INTO `admin_role` VALUES ('402881862bec2a21012bec2bd8de0003','402881862bec2a21012bec2b70510002');"; preparedStatement = connection.prepareStatement(insertAdminSql); preparedStatement.executeUpdate(); preparedStatement = connection.prepareStatement(insertAdminRoleSql); preparedStatement.executeUpdate(); } } catch (SQLException e) { e.printStackTrace(); return ajaxJsonErrorMessage("???!"); } finally { try { if (resultSet != null) { resultSet.close(); resultSet = null; } if (preparedStatement != null) { preparedStatement.close(); preparedStatement = null; } if (connection != null) { connection.close(); connection = null; } } catch (SQLException e) { e.printStackTrace(); } } // ??? String configFilePath = Thread.currentThread().getContextClassLoader().getResource("").toURI().getPath() + JDBC_CONFIG_FILE_NAME; Properties properties = new Properties(); properties.put("jdbc.driver", "com.mysql.jdbc.Driver"); properties.put("jdbc.url", jdbcUrl); properties.put("jdbc.username", databaseUsername); properties.put("jdbc.password", databasePassword); properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect"); properties.put("hibernate.show_sql", "false"); properties.put("hibernate.format_sql", "false"); OutputStream outputStream = new FileOutputStream(configFilePath); properties.store(outputStream, JDBC_CONFIG_FILE_DESCRIPTION); outputStream.close(); // ?? String backupWebConfigFilePath = Thread.currentThread().getContextClassLoader().getResource("").toURI() .getPath() + BACKUP_WEB_CONFIG_FILE_NAME; String backupApplicationContextConfigFilePath = Thread.currentThread().getContextClassLoader() .getResource("").toURI().getPath() + BACKUP_APPLICATION_CONTEXT_CONFIG_FILE_NAME; String backupCompassApplicationContextConfigFilePath = Thread.currentThread().getContextClassLoader() .getResource("").toURI().getPath() + BACKUP_COMPASS_APPLICATION_CONTEXT_CONFIG_FILE_NAME; String backupSecurityApplicationContextConfigFilePath = Thread.currentThread().getContextClassLoader() .getResource("").toURI().getPath() + BACKUP_SECURITY_APPLICATION_CONTEXT_CONFIG_FILE_NAME; String webConfigFilePath = new File( Thread.currentThread().getContextClassLoader().getResource("").toURI().getPath()).getParent() + "/" + WEB_CONFIG_FILE_NAME; String applicationContextConfigFilePath = Thread.currentThread().getContextClassLoader().getResource("") .toURI().getPath() + APPLICATION_CONTEXT_CONFIG_FILE_NAME; String compassApplicationContextConfigFilePath = Thread.currentThread().getContextClassLoader() .getResource("").toURI().getPath() + COMPASS_APPLICATION_CONTEXT_CONFIG_FILE_NAME; String securityApplicationContextConfigFilePath = Thread.currentThread().getContextClassLoader() .getResource("").toURI().getPath() + SECURITY_APPLICATION_CONTEXT_CONFIG_FILE_NAME; FileUtils.copyFile(new File(backupWebConfigFilePath), new File(webConfigFilePath)); FileUtils.copyFile(new File(backupApplicationContextConfigFilePath), new File(applicationContextConfigFilePath)); FileUtils.copyFile(new File(backupCompassApplicationContextConfigFilePath), new File(compassApplicationContextConfigFilePath)); FileUtils.copyFile(new File(backupSecurityApplicationContextConfigFilePath), new File(securityApplicationContextConfigFilePath)); // ?? //String systemConfigFilePath = Thread.currentThread().getContextClassLoader().getResource("").toURI().getPath() + SystemConfigUtils.CONFIG_FILE_NAME; File systemConfigFile = new File( ConfigurationManager.getConfigProperties(SystemConfigUtils.CONFIG_FILE_PATH_NAME)); SAXReader saxReader = new SAXReader(); Document document = saxReader.read(systemConfigFile); Element rootElement = document.getRootElement(); Element systemConfigElement = rootElement.element("systemConfig"); Node isInstalledNode = document.selectSingleNode("/shopxx/systemConfig/isInstalled"); if (isInstalledNode == null) { isInstalledNode = systemConfigElement.addElement("isInstalled"); } isInstalledNode.setText("true"); try { OutputFormat outputFormat = OutputFormat.createPrettyPrint();// XML? outputFormat.setEncoding("UTF-8");// XML? outputFormat.setIndent(true);// ? outputFormat.setIndent(" ");// TAB? outputFormat.setNewlines(true);// ?? XMLWriter xmlWriter = new XMLWriter(new FileOutputStream(systemConfigFile), outputFormat); xmlWriter.write(document); xmlWriter.close(); } catch (Exception e) { e.printStackTrace(); } return ajaxJsonSuccessMessage("SHOP++?????"); }
From source file:com.zuuyii.action.admin.InstallAction.java
public String save() throws URISyntaxException, IOException, DocumentException { if (isInstalled()) { return ajaxJsonErrorMessage("SHOP++?????"); }//from w w w . ja va 2 s. com if (StringUtils.isEmpty(databaseHost)) { return ajaxJsonErrorMessage("?!"); } if (StringUtils.isEmpty(databasePort)) { return ajaxJsonErrorMessage("??!"); } if (StringUtils.isEmpty(databaseUsername)) { return ajaxJsonErrorMessage("???!"); } if (StringUtils.isEmpty(databasePassword)) { return ajaxJsonErrorMessage("??!"); } if (StringUtils.isEmpty(databaseName)) { return ajaxJsonErrorMessage("???!"); } if (StringUtils.isEmpty(adminUsername)) { return ajaxJsonErrorMessage("???!"); } if (StringUtils.isEmpty(adminPassword)) { return ajaxJsonErrorMessage("??!"); } if (StringUtils.isEmpty(installStatus)) { Map<String, String> jsonMap = new HashMap<String, String>(); jsonMap.put(STATUS, "requiredCheckFinish"); return ajaxJson(jsonMap); } String jdbcUrl = "jdbc:mysql://" + databaseHost + ":" + databasePort + "/" + databaseName + "?useUnicode=true&characterEncoding=UTF-8"; Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { // ? connection = DriverManager.getConnection(jdbcUrl, databaseUsername, databasePassword); DatabaseMetaData databaseMetaData = connection.getMetaData(); String[] types = { "TABLE" }; resultSet = databaseMetaData.getTables(null, databaseName, "%", types); if (StringUtils.equalsIgnoreCase(installStatus, "databaseCheck")) { Map<String, String> jsonMap = new HashMap<String, String>(); jsonMap.put(STATUS, "databaseCheckFinish"); return ajaxJson(jsonMap); } // ? if (StringUtils.equalsIgnoreCase(installStatus, "databaseCreate")) { StringBuffer stringBuffer = new StringBuffer(); BufferedReader bufferedReader = null; String sqlFilePath = Thread.currentThread().getContextClassLoader().getResource("").toURI() .getPath() + SQL_INSTALL_FILE_NAME; bufferedReader = new BufferedReader( new InputStreamReader(new FileInputStream(sqlFilePath), "UTF-8")); String line = ""; while (null != line) { line = bufferedReader.readLine(); stringBuffer.append(line); if (null != line && line.endsWith(";")) { System.out.println("[SHOP++?]SQL: " + line); preparedStatement = connection.prepareStatement(stringBuffer.toString()); preparedStatement.executeUpdate(); stringBuffer = new StringBuffer(); } } String insertAdminSql = "INSERT INTO `Admin` VALUES ('402881862bec2a21012bec2bd8de0003','2010-10-10 0:0:0','2010-10-10 0:0:0','','admin@shopxx.net',b'1',b'0',b'0',b'0',NULL,NULL,0,NULL,'?','" + DigestUtils.md5Hex(adminPassword) + "','" + adminUsername + "');"; String insertAdminRoleSql = "INSERT INTO `Admin_Role` VALUES ('402881862bec2a21012bec2bd8de0003','402881862bec2a21012bec2b70510002');"; preparedStatement = connection.prepareStatement(insertAdminSql); preparedStatement.executeUpdate(); preparedStatement = connection.prepareStatement(insertAdminRoleSql); preparedStatement.executeUpdate(); } } catch (SQLException e) { e.printStackTrace(); return ajaxJsonErrorMessage("???!"); } finally { try { if (resultSet != null) { resultSet.close(); resultSet = null; } if (preparedStatement != null) { preparedStatement.close(); preparedStatement = null; } if (connection != null) { connection.close(); connection = null; } } catch (SQLException e) { e.printStackTrace(); } } // ??? String configFilePath = Thread.currentThread().getContextClassLoader().getResource("").toURI().getPath() + JDBC_CONFIG_FILE_NAME; Properties properties = new Properties(); properties.put("jdbc.driver", "com.mysql.jdbc.Driver"); properties.put("jdbc.url", jdbcUrl); properties.put("jdbc.username", databaseUsername); properties.put("jdbc.password", databasePassword); properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect"); properties.put("hibernate.show_sql", "false"); properties.put("hibernate.format_sql", "false"); OutputStream outputStream = new FileOutputStream(configFilePath); properties.store(outputStream, JDBC_CONFIG_FILE_DESCRIPTION); outputStream.close(); // ?? /*String backupWebConfigFilePath = Thread.currentThread().getContextClassLoader().getResource("").toURI().getPath() + BACKUP_WEB_CONFIG_FILE_NAME; String backupApplicationContextConfigFilePath = Thread.currentThread().getContextClassLoader().getResource("").toURI().getPath() + BACKUP_APPLICATION_CONTEXT_CONFIG_FILE_NAME; String backupCompassApplicationContextConfigFilePath = Thread.currentThread().getContextClassLoader().getResource("").toURI().getPath() + BACKUP_COMPASS_APPLICATION_CONTEXT_CONFIG_FILE_NAME; String backupSecurityApplicationContextConfigFilePath = Thread.currentThread().getContextClassLoader().getResource("").toURI().getPath() + BACKUP_SECURITY_APPLICATION_CONTEXT_CONFIG_FILE_NAME; String webConfigFilePath = new File(Thread.currentThread().getContextClassLoader().getResource("").toURI().getPath()).getParent() + "/" + WEB_CONFIG_FILE_NAME; String applicationContextConfigFilePath = Thread.currentThread().getContextClassLoader().getResource("").toURI().getPath() + APPLICATION_CONTEXT_CONFIG_FILE_NAME; String compassApplicationContextConfigFilePath = Thread.currentThread().getContextClassLoader().getResource("").toURI().getPath() + COMPASS_APPLICATION_CONTEXT_CONFIG_FILE_NAME; String securityApplicationContextConfigFilePath = Thread.currentThread().getContextClassLoader().getResource("").toURI().getPath() + SECURITY_APPLICATION_CONTEXT_CONFIG_FILE_NAME; FileUtils.copyFile(new File(backupWebConfigFilePath), new File(webConfigFilePath)); FileUtils.copyFile(new File(backupApplicationContextConfigFilePath), new File(applicationContextConfigFilePath)); FileUtils.copyFile(new File(backupCompassApplicationContextConfigFilePath), new File(compassApplicationContextConfigFilePath)); FileUtils.copyFile(new File(backupSecurityApplicationContextConfigFilePath), new File(securityApplicationContextConfigFilePath)); */ // ?? String systemConfigFilePath = Thread.currentThread().getContextClassLoader().getResource("").toURI() .getPath() + SystemConfigUtil.CONFIG_FILE_NAME; File systemConfigFile = new File(systemConfigFilePath); SAXReader saxReader = new SAXReader(); Document document = saxReader.read(systemConfigFile); Element rootElement = document.getRootElement(); Element systemConfigElement = rootElement.element("systemConfig"); Node isInstalledNode = document.selectSingleNode("/shopxx/systemConfig/isInstalled"); if (isInstalledNode == null) { isInstalledNode = systemConfigElement.addElement("isInstalled"); } isInstalledNode.setText("true"); try { OutputFormat outputFormat = OutputFormat.createPrettyPrint();// XML? outputFormat.setEncoding("UTF-8");// XML? outputFormat.setIndent(true);// ? outputFormat.setIndent(" ");// TAB? outputFormat.setNewlines(true);// ?? XMLWriter xmlWriter = new XMLWriter(new FileOutputStream(systemConfigFile), outputFormat); xmlWriter.write(document); xmlWriter.close(); } catch (Exception e) { e.printStackTrace(); } return ajaxJsonSuccessMessage("SHOP++?????"); }
From source file:delphsim.model.Epidemia.java
License:Open Source License
/** * Guarda la informacin de esta epidemia en el archivo pasado como * parmetro, siguiendo el esquema del .xsd de la aplicacin. * @param archivoDestino El archivo destino donde se guardar el modelo. * @throws java.io.IOException Si hay problemas al escribir en disco. * @throws org.dom4j.DocumentException Si hay problemas al crear el objeto de tipo rbol. * @throws java.lang.Exception Si se produce algn otro problema. */// w ww. j a v a2s . c om public void guardarXML(File archivoDestino) throws IOException, DocumentException, Exception { // Primero crear el documento dom4j con la informacin del modelo Document documento = DocumentHelper.createDocument(); // Elemento raz epidemia Element elementoEpidemia = new DefaultElement("epidemia"); documento.setRootElement(elementoEpidemia); elementoEpidemia.addAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); elementoEpidemia.addAttribute("xsi:noNamespaceSchemaLocation", "DelphSim1.18.xsd"); elementoEpidemia.addAttribute("unidadTiempo", this.unidadTiempo); // Elementos parmetros if (this.parametros != null) { for (Parametro param : this.parametros) { Element elementoParametro = param.volcarAXML(); elementoEpidemia.add(elementoParametro); } } // Elementos procesos if (this.procesos != null) { for (Proceso proc : this.procesos) { Element elementoProceso = proc.volcarAXML(); elementoEpidemia.add(elementoProceso); } } // Elemento poblacin Element elementoPoblacion = this.poblacion.volcarAXML(); elementoEpidemia.add(elementoPoblacion); // Elementos compartimentos for (Compartimento comp : this.compartimentos) { Element elementoCompartimento = comp.volcarAXML(); elementoEpidemia.add(elementoCompartimento); } // Luego crear el formato, stream y escritor de la salida OutputFormat formato = OutputFormat.createPrettyPrint(); formato.setEncoding("UTF-16"); formato.setIndent("\t"); formato.setNewLineAfterDeclaration(false); formato.setPadText(false); formato.setTrimText(true); formato.setXHTML(true); java.io.OutputStreamWriter salida = new java.io.OutputStreamWriter( new java.io.FileOutputStream(archivoDestino), "UTF-16"); XMLWriter escritor = new XMLWriter(salida, formato); // Y escribir escritor.write(documento); escritor.close(); }
From source file:delphsim.model.Resultado.java
License:Open Source License
/** * Mtodo esttico que exporta los valores obtenidos tras la simulacin al * formato XML./*ww w.j a va2s.c om*/ * @param destino El archivo de destino. * @param nombres Los nombres de las distintas columnas/funciones. * @param definiciones La definicin de cada columna/funcin. * @param temps Array con los archivos temporales de los cuales obtener los * datos a exportar. * @param numPuntosTotal El nmero de puntos total que contienen los * archivos temporales. * @param numPuntosExportar El nmero de puntos que quiere obtener el usuario. * @throws java.io.IOException Si hubiera algn problema al crear el archivo en disco. */ public static void exportarComoXML(File destino, String[] nombres, String[] definiciones, File[] temps, long numPuntosTotal, long numPuntosExportar) throws IOException { // Crear el documento, el elemento 'raiz' y asignarlo org.dom4j.Document documento = DocumentHelper.createDocument(); DefaultElement elementoResultado = new DefaultElement("resultado"); documento.setRootElement(elementoResultado); // Creamos los bfers de lectura para leer los temporales BufferedReader[] buffers = new BufferedReader[temps.length]; for (int i = 0; i < temps.length; i++) { buffers[i] = new BufferedReader(new FileReader(temps[i])); } // Calculamos cada cuanto tenemos que guardar un punto double cadaCuanto; if (numPuntosTotal == numPuntosExportar) { cadaCuanto = 1.0d; } else { cadaCuanto = new Double(numPuntosTotal) / new Double(numPuntosExportar - 1); } long siguientePuntoExportar = 0; long contadorNumPuntoLeido = 0; long contadorNumPuntosExportados = 0; // Comenzamos a leer los temporales aadiendo elementos al documento String[] valores = new String[buffers.length]; for (int i = 0; i < buffers.length; i++) { valores[i] = buffers[i].readLine(); } // En el momento en que se lee un null, se termina while (valores[0] != null) { // Para cada punto que haya que exportar if (siguientePuntoExportar == contadorNumPuntoLeido) { DefaultElement nuevaFila = new DefaultElement("fila"); // Para el tiempo, nuevo elemento, su valor y aadirlo a la fila DefaultElement elementoTiempo = new DefaultElement("Tiempo"); elementoTiempo.setText(valores[0]); nuevaFila.add(elementoTiempo); // Lo mismo para cada linea, pero ademas con nombre y definicin for (int i = 1; i < valores.length; i++) { DefaultElement elementoLinea = new DefaultElement("Lnea" + i); elementoLinea.add(new DefaultAttribute("nombre", nombres[i])); elementoLinea.add(new DefaultAttribute("definicion", definiciones[i])); elementoLinea.setText(valores[i]); nuevaFila.add(elementoLinea); } // Y aadimos la nueva fila elementoResultado.add(nuevaFila); // Calculamos el siguiente punto a exportar contadorNumPuntosExportados++; siguientePuntoExportar = Math.round(cadaCuanto * contadorNumPuntosExportados); if (siguientePuntoExportar >= numPuntosTotal) { siguientePuntoExportar = numPuntosTotal - 1; } } // Leemos la siguiente lnea de los ficheros for (int i = 0; i < buffers.length; i++) { valores[i] = buffers[i].readLine(); } contadorNumPuntoLeido++; } // Cerramos los bfers y el archivo de salida for (int i = 0; i < buffers.length; i++) { buffers[i].close(); } // Imprimimos el documento como XML OutputFormat formato = OutputFormat.createPrettyPrint(); formato.setEncoding("UTF-16"); formato.setIndent("\t"); formato.setNewLineAfterDeclaration(false); formato.setPadText(false); formato.setTrimText(true); formato.setXHTML(true); OutputStreamWriter salida = new OutputStreamWriter(new FileOutputStream(destino), "UTF-16"); XMLWriter escritor = new XMLWriter(salida, formato); escritor.write(documento); escritor.flush(); escritor.close(); }
From source file:edu.ccut.saturn.manager.dict.core.dbmanager.Dom4jUtils.java
License:Apache License
public static String writeXml(String file, Document doc) { String message = null;/*from ww w. j a va 2 s . c o m*/ XMLWriter writer = null; OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding("GB2312"); format.setIndent(true); format.setIndent(" "); format.setNewlines(true); OutputStream out = null; try { out = new FileOutputStream(file); } catch (FileNotFoundException e1) { try { String path = Thread.currentThread().getContextClassLoader().getResource(BLANK_STRING).getFile() + file.substring(1); out = new FileOutputStream(path); } catch (FileNotFoundException e) { e.printStackTrace(); } } try { writer = new XMLWriter(out, format); writer.write(doc); } catch (Exception e) { e.printStackTrace(); } finally { try { writer.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } } message = TRUE; return message; }
From source file:eml.studio.server.oozie.workflow.WFGraph.java
License:Open Source License
/** * Transform the Graph into an workflow xml definition * @param jobname the job name of Oozie job, can't be null * @return workflow xml//from w w w .j a v a 2s . com */ public String toWorkflow(String jobname) { Namespace xmlns = new Namespace("", "uri:oozie:workflow:0.4"); // root namespace uri QName qName = QName.get("workflow-app", xmlns); // your root element's name Element workflow = DocumentHelper.createElement(qName); Document xmldoc = DocumentHelper.createDocument(workflow); // Create workflow root workflow.addAttribute("xmlns", "uri:oozie:workflow:0.4"); // <workflow-app name='xxx'></workflow-app> if (jobname == null || "".equals(jobname)) workflow.addAttribute("name", "Not specified"); else workflow.addAttribute("name", jobname); Queue<NodeDef> que = new LinkedList<NodeDef>(); que.add(start); while (!que.isEmpty()) { NodeDef cur = que.remove(); cur.append2XML(workflow); for (NodeDef toNode : cur.getOutNodes()) { toNode.delInNode(cur); if (toNode.getInDegree() == 0) que.add(toNode); } } // Set XML document format OutputFormat outputFormat = OutputFormat.createPrettyPrint(); // Set XML encoding, use the specified encoding to save the XML document to the string, it can be specified GBK or ISO8859-1 outputFormat.setEncoding("UTF-8"); outputFormat.setSuppressDeclaration(true); // Whether generate xml header outputFormat.setIndent(true); // Whether set indentation outputFormat.setIndent(" "); // Implement indentation with four spaces outputFormat.setNewlines(true); // Set whether to wrap try { // stringWriter is used to save xml document StringWriter stringWriter = new StringWriter(); // xmlWriter is used to write XML document to string(tool) XMLWriter xmlWriter = new XMLWriter(stringWriter, outputFormat); // Write the created XML document into the string xmlWriter.write(xmldoc); xmlWriter.close(); System.out.println(stringWriter.toString().trim()); // Print the string, that is, the XML document return stringWriter.toString().trim(); } catch (Exception ex) { ex.printStackTrace(); } return null; }
From source file:eml.studio.server.oozie.workflow.WFGraph.java
License:Open Source License
public static void main(String args[]) { Namespace rootNs = new Namespace("", "uri:oozie:workflow:0.4"); // root namespace uri QName rootQName = QName.get("workflow-app", rootNs); // your root element's name Element workflow = DocumentHelper.createElement(rootQName); Document doc = DocumentHelper.createDocument(workflow); workflow.addAttribute("name", "test"); Element test = workflow.addElement("test"); test.addText("hello"); OutputFormat outputFormat = OutputFormat.createPrettyPrint(); outputFormat.setEncoding("UTF-8"); outputFormat.setIndent(true); outputFormat.setIndent(" "); outputFormat.setNewlines(true);//from ww w . j a va2 s . c om try { StringWriter stringWriter = new StringWriter(); XMLWriter xmlWriter = new XMLWriter(stringWriter); xmlWriter.write(doc); xmlWriter.close(); System.out.println(doc.asXML()); System.out.println(stringWriter.toString().trim()); } catch (Exception ex) { ex.printStackTrace(); } }
From source file:eu.planets_project.pp.plato.action.workflow.ValidatePlanAction.java
License:Open Source License
/** * reads the executable preservation plan and formats it. * /*from ww w .ja v a 2 s .com*/ */ private String formatExecutablePlan(String executablePlan) { if (executablePlan == null || "".equals(executablePlan)) { return ""; } try { Document doc = DocumentHelper.parseText(executablePlan); StringWriter sw = new StringWriter(); OutputFormat format = OutputFormat.createPrettyPrint(); format.setNewlines(true); format.setTrimText(true); format.setIndent(" "); format.setExpandEmptyElements(false); format.setNewLineAfterNTags(20); XMLWriter writer = new XMLWriter(sw, format); writer.write(doc); writer.close(); return sw.toString(); } catch (DocumentException e) { return ""; } catch (IOException e) { return ""; } }
From source file:gov.guilin.util.SettingUtils.java
License:Open Source License
/** * /*from w w w . j a v a 2 s. c o m*/ * * @param setting * */ public static void set(Setting setting) { try { File guilinXmlFile = new ClassPathResource(CommonAttributes.XML_PATH).getFile(); Document document = new SAXReader().read(guilinXmlFile); List<Element> elements = document.selectNodes("/guilin/setting"); for (Element element : elements) { try { String name = element.attributeValue("name"); String value = beanUtils.getProperty(setting, name); Attribute attribute = element.attribute("value"); attribute.setValue(value); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } } FileOutputStream fileOutputStream = null; XMLWriter xmlWriter = null; try { OutputFormat outputFormat = OutputFormat.createPrettyPrint(); outputFormat.setEncoding("UTF-8"); outputFormat.setIndent(true); outputFormat.setIndent(" "); outputFormat.setNewlines(true); fileOutputStream = new FileOutputStream(guilinXmlFile); xmlWriter = new XMLWriter(fileOutputStream, outputFormat); xmlWriter.write(document); } catch (Exception e) { e.printStackTrace(); } finally { if (xmlWriter != null) { try { xmlWriter.close(); } catch (IOException e) { } } IOUtils.closeQuietly(fileOutputStream); } Ehcache cache = cacheManager.getEhcache(Setting.CACHE_NAME); cache.put(new net.sf.ehcache.Element(Setting.CACHE_KEY, setting)); } catch (Exception e) { e.printStackTrace(); } }