⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 installaction.java

📁 个人认为是最好的Java论坛源码
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
/*
 * Copyright (c) 2003, 2004 Rafael Steil
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, 
 * with or without modification, are permitted provided 
 * that the following conditions are met:
 * 
 * 1) Redistributions of source code must retain the above 
 * copyright notice, this list of conditions and the 
 * following  disclaimer.
 * 2)  Redistributions in binary form must reproduce the 
 * above copyright notice, this list of conditions and 
 * the following disclaimer in the documentation and/or 
 * other materials provided with the distribution.
 * 3) Neither the name of "Rafael Steil" nor 
 * the names of its contributors may be used to endorse 
 * or promote products derived from this software without 
 * specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 
 * HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, 
 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR 
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL 
 * THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE 
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES 
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
 * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER 
 * IN CONTRACT, STRICT LIABILITY, OR TORT 
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF 
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE
 * 
 * This file creation date: 27/08/2004 - 18:15:54
 * The JForum Project
 * http://www.jforum.net
 */
package net.jforum.view.install;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.nio.channels.FileChannel;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;

import javax.servlet.http.HttpServletResponse;

import net.jforum.ActionServletRequest;
import net.jforum.Command;
import net.jforum.ConfigLoader;
import net.jforum.DBConnection;
import net.jforum.DataSourceConnection;
import net.jforum.InstallServlet;
import net.jforum.SessionFacade;
import net.jforum.SimpleConnection;
import net.jforum.entities.UserSession;
import net.jforum.util.FileMonitor;
import net.jforum.util.I18n;
import net.jforum.util.MD5;
import net.jforum.util.preferences.ConfigKeys;
import net.jforum.util.preferences.SystemGlobals;
import net.jforum.util.preferences.SystemGlobalsListener;

import org.apache.log4j.Logger;

import freemarker.template.SimpleHash;
import freemarker.template.Template;

/**
 * @author Rafael Steil
 * @version $Id: InstallAction.java,v 1.27 2005/03/03 14:44:54 rafaelsteil Exp $
 */
public class InstallAction extends Command
{
	private static Logger logger = Logger.getLogger(InstallAction.class);
	
	public void welcome() throws Exception
	{
		this.checkLanguage();
		
		this.context.put("language", this.getFromSession("language"));
		this.context.put("database", this.getFromSession("database"));
		this.context.put("dbhost", this.getFromSession("dbHost"));
		this.context.put("dbuser", this.getFromSession("dbUser"));
		this.context.put("dbname", this.getFromSession("dbName"));
		this.context.put("dbpasswd", this.getFromSession("dbPassword"));
		this.context.put("dbencoding", this.getFromSession("dbEncoding"));
		this.context.put("use_pool", this.getFromSession("usePool"));
		this.context.put("forum_link", this.getFromSession("forumLink"));
		this.context.put("siteLink", this.getFromSession("siteLink"));
		this.context.put("dbdatasource", this.getFromSession("dbdatasource"));
		
		this.context.put("moduleAction", "install.htm");
	}
	
	private void checkLanguage() throws IOException
	{
		String lang = this.request.getParameter("l");
		if (lang == null || !I18n.languageExists(lang)) {
			return;
		}
		
		I18n.load(lang);
		
		UserSession us = new UserSession();
		us.setLang(lang);
		
		SessionFacade.add(us);
		this.addToSessionAndContext("language", lang);
	}
	
	private String getFromSession(String key)
	{
		return (String)this.request.getSession().getAttribute(key);
	}
	
	private void error()
	{
		this.context.put("moduleAction", "install_error.htm");
	}
	
	public void doInstall() throws Exception
	{
		Connection conn = null;
		
		if (!this.checkForWritableDir()) {
			return;
		}
		
		this.removeUserConfig();
		
		if (!"passed".equals(this.getFromSession("configureDatabase"))) {
			logger.info("Going to configure the database...");
			conn = this.configureDatabase();
			if (conn == null) {
				this.context.put("message", I18n.getMessage("Install.databaseError"));
				this.error();
				return;
			}
		}
		
		logger.info("Database configuration ok");

		// Database Configuration is ok
		this.addToSessionAndContext("configureDatabase", "passed");
		
		DBConnection simpleConnection = new SimpleConnection();
		if (conn == null) {
			conn = simpleConnection.getConnection();
		}
		
		if (!"passed".equals(this.getFromSession("createTables")) && !this.createTables(conn)) {
			this.context.put("message", I18n.getMessage("Install.createTablesError"));
			simpleConnection.releaseConnection(conn);
			this.error();
			return;
		}
		
		// Create tables is ok
		this.addToSessionAndContext("createTables", "passed");
		logger.info("Table creation is ok");
		
		if (!"passed".equals(this.getFromSession("importTablesData")) && !this.importTablesData(conn)) {
			this.context.put("message", I18n.getMessage("Install.importTablesDataError"));
			simpleConnection.releaseConnection(conn);
			this.error();
			return;
		}
		
		// Dump is ok
		this.addToSessionAndContext("importTablesData", "passed");
		
		if (!this.updateAdminPassword(conn)) {
			this.context.put("message", I18n.getMessage("Install.updateAdminError"));
			simpleConnection.releaseConnection(conn);
			this.error();
			return;
		}
		
		simpleConnection.releaseConnection(conn);

		InstallServlet.setRedirect(this.request.getContextPath() + "/install/install"
				+ SystemGlobals.getValue(ConfigKeys.SERVLET_EXTENSION)
				+ "?module=install&action=finished");
	}
	
	private void removeUserConfig()
	{
		File f = new File(SystemGlobals.getValue(ConfigKeys.INSTALLATION_CONFIG));
		if (f.exists() && f.canWrite()) {
			try {
				f.delete();
			}
			catch (Exception e) {
				logger.info(e.toString());
			}
		}
	}
	
	public void finished() throws Exception
	{
		this.context.put("clickHere", I18n.getMessage("Install.clickHere"));
		this.context.put("forumLink", this.getFromSession("forumLink"));
		this.context.put("moduleAction", "install_finished.htm");
		
		String lang = this.getFromSession("language");
		if (lang == null) {
			lang = "en_US";
		}
		
		this.context.put("lang", lang);
		
		this.doFinalSteps();
		this.configureSystemGlobals();

		SystemGlobals.loadQueries(SystemGlobals.getValue(ConfigKeys.SQL_QUERIES_GENERIC));
        SystemGlobals.loadQueries(SystemGlobals.getValue(ConfigKeys.SQL_QUERIES_DRIVER));
        
        SessionFacade.remove(this.request.getSession().getId());
	}
	
	private void doFinalSteps()
	{
		try {
			// Modules Mapping
			String modulesMapping = SystemGlobals.getValue(ConfigKeys.CONFIG_DIR) + "/modulesMapping.properties";
			if (new File(modulesMapping).canWrite()) {
				Properties p = new Properties();
				p.load(new FileInputStream(modulesMapping));
				
				if (p.containsKey("install")) {
					p.remove("install");
					
					p.store(new FileOutputStream(modulesMapping), "Modified by JForum Installer");
					
					this.addToSessionAndContext("mappingFixed", "true");
					ConfigLoader.loadModulesMapping(SystemGlobals.getValue(ConfigKeys.CONFIG_DIR));
				}
			}
		}
		catch (Exception e) {
			logger.warn("Error while working on modulesMapping.properties: " + e);
		}
		
		
		try {
			// Index renaming
			String index = SystemGlobals.getApplicationPath() + "/index.htm";
			File indexFile = new File(index);
			if (indexFile.canWrite()) {
				String newIndex = SystemGlobals.getApplicationPath() + "/new_rename.htm";
				File newIndexFile = new File(newIndex);
				if (newIndexFile.exists()) {
					indexFile.delete();
					newIndexFile.renameTo(indexFile);
					
					this.addToSessionAndContext("indexFixed", "true");
				}
			}
		}
		catch (Exception e) {
			logger.warn("Error while renaming index.htm: " + e);
		}
	}
	
	private void configureSystemGlobals() throws Exception
	{
		SystemGlobals.setValue(ConfigKeys.USER_HASH_SEQUENCE, MD5.crypt(this.getFromSession("dbPassword")
				+ System.currentTimeMillis()));

		SystemGlobals.setValue(ConfigKeys.FORUM_LINK, this.getFromSession("forumLink"));
		
		SystemGlobals.setValue(ConfigKeys.I18N_DEFAULT, this.getFromSession("language"));
		SystemGlobals.setValue(ConfigKeys.INSTALLED, "true");
		SystemGlobals.saveInstallation();
		
		this.restartSystemGlobals();
	}
	
	private boolean importTablesData(Connection conn) throws Exception
	{
		boolean status = true;
		boolean autoCommit = conn.getAutoCommit();
		conn.setAutoCommit(false);
		
		String dbType = this.getFromSession("database");
		
		if (dbType.startsWith("mysql")) {
			dbType = "mysql";
		}
		
		List statements = this.readFromDat(SystemGlobals.getApplicationPath() + "/install/" + dbType + "_dump.dat");
		for (Iterator iter = statements.iterator(); iter.hasNext();) {
			String query = (String)iter.next();
			if (query == null || "".equals(query.trim())) {
				continue;
			}
			
			query = query.trim();
			
			Statement s = conn.createStatement();
			
			try {
				if (query.startsWith("UPDATE") || query.startsWith("INSERT")
						|| query.startsWith("SET")) {
					s.executeUpdate(query);
				}
				else if (query.startsWith("SELECT")) {
					s.executeQuery(query);
				}
				else {
					throw new Exception("Invalid query: " + query);
				}
			}
			catch (SQLException ex) {
				status = false;
				conn.rollback();
				logger.error("Error importing data for " + query + ": " + ex);
				this.context.put("exceptionMessage", ex.getMessage() + "\n" + query);
				break;
			}
			finally {
				s.close();
			}
		}
		
		conn.setAutoCommit(autoCommit);
		return status;
	}
	
	private Properties loadProperties(String filename) throws IOException
	{
		Properties p = new Properties();
		FileInputStream inputStream = new FileInputStream(filename);
		p.load(inputStream);
		inputStream.close();
		
		return p;
	}
	
	private boolean createTables(Connection conn) throws Exception
	{
		logger.info("Going to create tables...");
		String dbType = this.getFromSession("database");
		
		if ("postgresql".equals(dbType)) {

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -