Java tutorial
package cn.com.xdays.xshop.action.admin; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.URISyntaxException; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import java.util.Properties; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.StringUtils; import org.apache.struts2.convention.annotation.ParentPackage; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.Node; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; import cn.com.xdays.xshop.util.SystemConfigUtil; import com.opensymphony.xwork2.interceptor.annotations.InputConfig; import com.opensymphony.xwork2.validator.annotations.RequiredFieldValidator; import com.opensymphony.xwork2.validator.annotations.Validations; import freemarker.ext.beans.BeansWrapper; import freemarker.template.TemplateHashModel; /** * ??Action - * ============================================================================ * ? 2008-2010 ???? * ---------------------------------------------------------------------------- * ???SHOP++????SHOP++?? * ---------------------------------------------------------------------------- * http://www.shopxx.net * ---------------------------------------------------------------------------- * KEY: SHOPXX8DDD613CBE6FE3988F4CE19EAC8724CB * ============================================================================ */ @ParentPackage("admin") public class InstallAction extends BaseAdminAction { private static final long serialVersionUID = -83169049612878557L; public static final String JDBC_CONFIG_FILE_NAME = "jdbc.properties";// JDBC? public static final String JDBC_CONFIG_FILE_DESCRIPTION = "SHOP++ JDBC?";// JDBC??? public static final String SQL_INSTALL_FILE_NAME = "shopxx.sql";// SQL public static final String BACKUP_WEB_CONFIG_FILE_NAME = "backup-web.xml";// Web??? public static final String BACKUP_APPLICATION_CONTEXT_CONFIG_FILE_NAME = "backup-applicationContext.xml";// Spring??? public static final String BACKUP_COMPASS_APPLICATION_CONTEXT_CONFIG_FILE_NAME = "backup-applicationContext-compass.xml";// Compass??? public static final String BACKUP_SECURITY_APPLICATION_CONTEXT_CONFIG_FILE_NAME = "backup-applicationContext-security.xml";// SpringSecurity??? public static final String WEB_CONFIG_FILE_NAME = "web.xml";// Web??? public static final String APPLICATION_CONTEXT_CONFIG_FILE_NAME = "applicationContext.xml";// Spring??? public static final String COMPASS_APPLICATION_CONTEXT_CONFIG_FILE_NAME = "applicationContext-compass.xml";// Compass??? public static final String SECURITY_APPLICATION_CONTEXT_CONFIG_FILE_NAME = "applicationContext-security.xml";// SpringSecurity??? private Boolean isAgreeAgreement; private String databaseHost; private String databasePort; private String databaseUsername; private String databasePassword; private String databaseName; private String adminUsername; private String adminPassword; private String installStatus; // ??? public String license() { if (isInstalled()) { addActionError("SHOP++?????"); return ERROR; } return "license"; } // @Validations(requiredFields = { @RequiredFieldValidator(fieldName = "isAgreeAgreement", message = "???????!") }) @InputConfig(resultName = "error") public String check() { if (isInstalled()) { addActionError("SHOP++?????"); return ERROR; } if (!isAgreeAgreement) { addActionError("???????!"); } return "check"; } // ? public String setting() { if (isInstalled()) { addActionError("SHOP++?????"); return ERROR; } return "setting"; } // ? public String save() throws URISyntaxException, IOException, DocumentException { if (isInstalled()) { return ajaxJsonErrorMessage("SHOP++?????"); } 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++?????"); } // ? private boolean isInstalled() { try { 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); Node isInstalledNode = document.selectSingleNode("/shopxx/systemConfig/isInstalled"); if (isInstalledNode != null && StringUtils.equalsIgnoreCase(isInstalledNode.getText(), "false")) { return false; } else { return true; } } catch (Exception e) { e.printStackTrace(); return true; } } // freemarker?? public TemplateHashModel getStatics() { return BeansWrapper.getDefaultInstance().getStaticModels(); } public Boolean getIsAgreeAgreement() { return isAgreeAgreement; } public void setIsAgreeAgreement(Boolean isAgreeAgreement) { this.isAgreeAgreement = isAgreeAgreement; } public String getDatabaseHost() { return databaseHost; } public void setDatabaseHost(String databaseHost) { this.databaseHost = databaseHost; } public String getDatabasePort() { return databasePort; } public void setDatabasePort(String databasePort) { this.databasePort = databasePort; } public String getDatabaseUsername() { return databaseUsername; } public void setDatabaseUsername(String databaseUsername) { this.databaseUsername = databaseUsername; } public String getDatabasePassword() { return databasePassword; } public void setDatabasePassword(String databasePassword) { this.databasePassword = databasePassword; } public String getDatabaseName() { return databaseName; } public void setDatabaseName(String databaseName) { this.databaseName = databaseName; } public String getAdminUsername() { return adminUsername; } public void setAdminUsername(String adminUsername) { this.adminUsername = adminUsername; } public String getAdminPassword() { return adminPassword; } public void setAdminPassword(String adminPassword) { this.adminPassword = adminPassword; } public String getInstallStatus() { return installStatus; } public void setInstallStatus(String installStatus) { this.installStatus = installStatus; } }