package com.mingsoft.servlet.install;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import com.mingsoft.entity.ResutEntity;
import com.mingsoft.servlet.BaseServlet;
import com.mysql.jdbc.Connection;

/**
 * @author 荣繁奎
 * @date:2013-11-18 下午02:04:53
 * @version : 用户安装过程中 判断数据库名密码等是否存在
 * QQ:1096199590
 * 技术支持：铭飞科技
 * 官网：www.ming-soft.com
 *
 */
@SuppressWarnings("serial")
public class InstallJudgeServlet extends BaseServlet {

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		super.doPost(request, response);
		PrintWriter out = response.getWriter();
		// 获取表单中数据库主机
		String dbhost = request.getParameter("dbhost");
		// 获取表单中数据库名
		String dbname = request.getParameter("dbname");
		//更改c3p0的配置文件的用户名和密码
		String dbuser = request.getParameter("dbuser");
		String dbpwd = request.getParameter("dbpwd");
		String message = "";
		 ResutEntity re = new ResutEntity();
		if(dbhost.equals("")||dbhost==null){
			re.setCode(ResutEntity.INSTALL_DBHOST);
			re.setContent("数据库主机不为空");
		}else if(dbname.equals("")||dbname==null){
			re.setCode(ResutEntity.INSTALL_DBNAME);
			re.setContent("数据库名称不为空");
		}else if(dbuser.equals("")||dbhost==null){
			re.setCode(ResutEntity.INSTALL_DBUSER);
			re.setContent("数据库用户不为空");
		}else{
			try {
				Class.forName("com.mysql.jdbc.Driver").newInstance();
			} catch (InstantiationException e) {
				message = e.getMessage();
			} catch (IllegalAccessException e) {
				message = e.getMessage();
			} catch (ClassNotFoundException e) {
				message = e.getMessage();
			}
		    String url="jdbc:mysql://"+dbhost+":3306/"+dbname+"?characterEncoding=utf8";
		    try {
				@SuppressWarnings("unused")
				Connection conn= (Connection) DriverManager.getConnection(url,dbuser,dbpwd);
			} catch (SQLException e) {
				message = e.getMessage();
			}
		}
		if(message.contains("using password")){
			re.setCode(ResutEntity.INSTALL_DB_NOUSER);
			re.setContent("数据库用户名或密码错误");
		}else if(message.contains("Unknown database")){
			re.setCode(ResutEntity.INSTALL_DB_NODB);
			re.setContent("未找到您填写的数据库名称，请仔细检查本地数据库是否存在该数据库");
		}else if(message.contains("com.mysql.jdbc")){
			re.setCode(ResutEntity.INSTALL_DB_DRIVER);
			re.setContent("未找到数据库驱动");
		}else if(message.contains("Communications link failure")){
			re.setCode(ResutEntity.INSTALL_DB_JDBC);
			re.setContent("连接数据库失败，请检查数据库主机是否填写正确");
		}
		 out.print(JSONObject.fromObject(re).toString());
		 out.close();
	}

}
