List of usage examples for org.dom4j.io XMLWriter write
public void write(Object object) throws IOException
From source file:cc.warlock.build.FeatureVersionReplacer.java
License:Open Source License
protected void replaceVersions() throws BuildException { SAXReader reader = new SAXReader(); try {//from ww w . java2 s . c om File featureFile = new File(new File(new File(buildDirectory, "features"), feature), "feature.xml"); Document featureDoc = reader.read(featureFile); Element featureEl = featureDoc.getRootElement(); featureEl.attribute("version").setValue(version); // Properties versions = new Properties(); // File versionsFile = new File(buildDirectory, "finalPluginsVersions.properties"); // FileInputStream stream = new FileInputStream(versionsFile); // versions.load(stream); // stream.close(); // // for (Element pluginEl : (List<Element>) featureEl.elements("plugin")) // { // if (pluginEl.attributeValue("version").equals("0.0.0")) // { // if (versions.containsKey(pluginEl.attributeValue("id"))) // pluginEl.attribute("version").setValue(versions.getProperty(pluginEl.attributeValue("id"))); // } // } OutputFormat format = OutputFormat.createPrettyPrint(); FileOutputStream outStream = new FileOutputStream(featureFile); XMLWriter writer = new XMLWriter(outStream, format); writer.write(featureDoc); outStream.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:cc.warlock.core.configuration.WarlockConfiguration.java
License:Open Source License
public void save() { Document document = DocumentHelper.createDocument(); Element warlockConfig = DocumentHelper.createElement("warlock-config"); document.setRootElement(warlockConfig); for (IConfigurationProvider provider : providers) { List<Element> elements = provider.getTopLevelElements(); for (Element element : elements) { warlockConfig.add(element);// w w w .j a va 2 s .c o m } } for (Element unhandled : unhandledElements) { // Make sure to resave unhandled elements, just in case the corresponding handler wasn't instantiated warlockConfig.add(unhandled.createCopy()); } try { if (configFile.exists()) { File backupFile = new File(configFile.getPath() + ".bak"); if (backupFile.exists()) backupFile.renameTo(new File(backupFile.getPath() + ".1")); configFile.renameTo(backupFile); } OutputFormat format = OutputFormat.createPrettyPrint(); FileOutputStream stream = new FileOutputStream(configFile); XMLWriter writer = new XMLWriter(stream, format); writer.write(document); stream.close(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:cn.com.iscs.base.util.XMLProperties.java
License:Open Source License
/** * Saves the properties to disk as an XML document. A temporary file is used * during the writing process for maximum safety. *///ww w . j a va 2s.c o m private synchronized void saveProperties() { boolean error = false; // Write data out to a temporary file first. File tempFile = null; Writer writer = null; try { tempFile = new File(file.getParentFile(), file.getName() + ".tmp"); writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tempFile), "UTF-8")); OutputFormat prettyPrinter = OutputFormat.createPrettyPrint(); XMLWriter xmlWriter = new XMLWriter(writer, prettyPrinter); xmlWriter.write(document); } catch (Exception e) { e.printStackTrace(); // There were errors so abort replacing the old property file. error = true; } finally { if (writer != null) { try { writer.close(); } catch (IOException e1) { // Log.error(e1); e1.printStackTrace(); error = true; } } } // No errors occured, so delete the main file. if (!error) { // Delete the old file so we can replace it. if (!file.delete()) { System.err.print("Error deleting property file: " + file.getAbsolutePath()); return; } // Copy new contents to the file. try { copy(tempFile, file); } catch (Exception e) { // Log.error(e); e.printStackTrace(); // There were errors so abort replacing the old property file. error = true; } // If no errors, delete the temp file. if (!error) { tempFile.delete(); } } }
From source file:cn.com.xdays.xshop.action.admin.InstallAction.java
public String save() throws URISyntaxException, IOException, DocumentException { if (isInstalled()) { return ajaxJsonErrorMessage("SHOP++?????"); }// ww w . j a v a 2s . c o 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 { Class.forName("com.mysql.jdbc.Driver"); // ? 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 (Exception 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:cn.feng.web.ssm.excel.controller.StringUtils.java
License:Apache License
/** * //from ww w. j a v a2 s . c o m * dom4j * @param document * @return */ public static String document2str(Document document, String chartset) { String result = ""; OutputFormat format; ByteArrayOutputStream out; try { format = OutputFormat.createPrettyPrint(); format.setEncoding(chartset); out = new ByteArrayOutputStream(); XMLWriter writer = new XMLWriter(out, format); writer.write(document); writer.flush(); writer.close(); result = out.toString(format.getEncoding()); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return result; }
From source file:cn.ict.zyq.bestConf.util.ParseXMLToYaml.java
License:Open Source License
public static void appendXMLByDOM4J(HashMap target, String source, String destination) throws IOException { SAXReader reader = new SAXReader(); try {//ww w. j av a2 s . c o m Document document = reader.read(new File(source)); Element configStore = document.getRootElement(); Iterator iter = target.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); String key = entry.getKey().toString(); String val = entry.getValue().toString(); Element property = configStore.addElement("property"); Element name = property.addElement("name"); name.setText(key); Element value = property.addElement("value"); value.setText(val); } OutputFormat format = OutputFormat.createPrettyPrint(); XMLWriter writer = new XMLWriter(new FileOutputStream(destination), format); writer.write(document); writer.close(); } catch (DocumentException e) { e.printStackTrace(); } }
From source file:cn.itcreator.android.reader.util.XMLUtil.java
License:Open Source License
/** * save the list to a xml file//from ww w .j av a 2s . co m * @param list the list u wanna save * @return */ public boolean saveToFile(List<BookMark> list) { boolean result = true; Element root = null; root = mDocument.getRootElement(); if (null == root) { root = mDocument.addElement("bookmark"); } for (BookMark bookMark : list) { Element mark = root.addElement("mark"); mark.addAttribute("markName", bookMark.getMarkName()); mark.addAttribute("currentOffset", "" + bookMark.getCurrentOffset()); } OutputFormat format = OutputFormat.createPrettyPrint(); /** Give the xml file encode */ format.setEncoding(Constant.UTF8); try { XMLWriter writer = new XMLWriter(new FileOutputStream(mFilePath), format); writer.write(mDocument); writer.close(); } catch (IOException e) { result = false; } return result; }
From source file:cn.mario256.blog.util.SystemUtils.java
License:Open Source License
/** * // w ww.j a v a 2 s .c om * * @param setting * */ @SuppressWarnings("unchecked") public static void setSetting(Setting setting) { Assert.notNull(setting); try { File turingXmlFile = new ClassPathResource(CommonAttributes.TURING_XML_PATH).getFile(); Document document = new SAXReader().read(turingXmlFile); List<org.dom4j.Element> elements = document.selectNodes("/turing/setting"); for (org.dom4j.Element element : elements) { try { String name = element.attributeValue("name"); String value = BEAN_UTILS.getProperty(setting, name); Attribute attribute = element.attribute("value"); attribute.setValue(value); } catch (IllegalAccessException e) { throw new RuntimeException(e.getMessage(), e); } catch (InvocationTargetException e) { throw new RuntimeException(e.getMessage(), e); } catch (NoSuchMethodException e) { throw new RuntimeException(e.getMessage(), e); } } XMLWriter xmlWriter = null; try { OutputFormat outputFormat = OutputFormat.createPrettyPrint(); outputFormat.setEncoding("UTF-8"); outputFormat.setIndent(true); outputFormat.setIndent(" "); outputFormat.setNewlines(true); xmlWriter = new XMLWriter(new FileOutputStream(turingXmlFile), outputFormat); xmlWriter.write(document); xmlWriter.flush(); } catch (FileNotFoundException e) { throw new RuntimeException(e.getMessage(), e); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e.getMessage(), e); } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } finally { try { if (xmlWriter != null) { xmlWriter.close(); } } catch (IOException e) { } } Ehcache cache = CACHE_MANAGER.getEhcache(Setting.CACHE_NAME); String cacheKey = "setting"; cache.put(new Element(cacheKey, setting)); } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } catch (DocumentException e) { throw new RuntimeException(e.getMessage(), e); } }
From source file:com.adobe.ac.pmd.metrics.engine.AbstractMetrics.java
License:Apache License
public void execute(final File outputFile) throws DocumentException, IOException { final String builtReport = buildReport(loadMetrics()); final Document document = DocumentHelper.parseText(builtReport); final OutputFormat format = OutputFormat.createPrettyPrint(); if (!outputFile.exists()) { if (outputFile.createNewFile() == false) { LOGGER.warning("Could not create a new output file"); }/*from ww w . j av a 2 s . c o m*/ } final XMLWriter writer = new XMLWriter(new FileOutputStream(outputFile), format); writer.write(document); writer.close(); }
From source file:com.ah.be.admin.adminBackupUnit.AhBackupTool.java
private void backupDomainTable(String strPath, String strDomainName, String strTableName) { Connection con = null;//w ww .ja v a2 s. co m XMLWriter output = null; ResultSet rsTable = null; Statement stTable = null; try { if (!(strPath.substring(strPath.length() - 1).equals(File.separator) || strPath.substring(strPath.length() - 1).equals("/"))) { strPath = strPath + File.separatorChar; } // Class.forName("org.postgresql.Driver").newInstance(); // // String strUrl = "jdbc:postgresql://localhost:5432/hm"; // // String strUsr = "hivemanager"; // // String strPsd = "aerohive"; AhBackupNewTool oTool = new AhBackupNewTool(); con = oTool.initCon(); try { stTable = con.createStatement(); String strSql; int intFileCount = 0; int intRecordNum; while (true) { intRecordNum = 0; strSql = "select * from " + strTableName + " where domainname='" + strDomainName + "'" + " limit " + 5000 + " offset " + intFileCount * 5000; if (!AhBackupNewTool.isValidCoon(con)) { con = oTool.initCon(); stTable = con.createStatement(); } rsTable = stTable.executeQuery(strSql); Document document = DocumentHelper.createDocument(); Element table = document.addElement("table").addAttribute("schema", strTableName); ResultSetMetaData rsmd = rsTable.getMetaData(); int iCount = rsmd.getColumnCount(); while (rsTable.next()) { intRecordNum++; Element row = table.addElement("row"); for (int icol = 1; icol <= iCount; icol++) { String newStr; if (rsTable.getString(icol) == null) { newStr = "NULL"; } else if ("null".equalsIgnoreCase(rsTable.getString(icol))) { newStr = "_" + rsTable.getString(icol) + "_"; } else { newStr = rsTable.getString(icol); } if (1 == intRecordNum) { row.addElement("field").addAttribute("name", rsmd.getColumnName(icol)) .addAttribute("value", newStr); } else { row.addElement("field").addAttribute("value", newStr); } } } if (intRecordNum <= 0 && 0 != intFileCount) break; File file; if (intFileCount == 0) { file = new File(strPath + strTableName.toLowerCase() + ".xml"); } else { file = new File(strPath + strTableName.toLowerCase() + "_" + intFileCount + ".xml"); } intFileCount++; output = new XMLWriter(new FileOutputStream(file)); output.write(document); output.close(); if (5000 > intRecordNum) break; } rsTable.close(); stTable.close(); } catch (Exception ex) { BeLogTools.restoreLog(BeLogTools.ERROR, ex.getMessage()); } } catch (Exception ex) { // add the debug msg BeLogTools.restoreLog(BeLogTools.ERROR, ex.getMessage()); } finally { if (null != con) { try { con.close(); } catch (Exception conex) { BeLogTools.restoreLog(BeLogTools.ERROR, conex.getMessage()); } } if (null != output) { try { output.close(); } catch (Exception outex) { BeLogTools.restoreLog(BeLogTools.ERROR, outex.getMessage()); } } if (null != rsTable) { try { rsTable.close(); } catch (Exception rsex) { BeLogTools.restoreLog(BeLogTools.ERROR, rsex.getMessage()); } } if (null != stTable) { try { stTable.close(); } catch (Exception stex) { BeLogTools.restoreLog(BeLogTools.ERROR, stex.getMessage()); } } } }