Controller.java

 /* Controller.java */

= = = = = = = =  = = = = = = = =  = = = = = = = = 

package bean.general;
import bean.UsrQy;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;

public class Controller extends HttpServlet
{
    private Properties actionProp = null;
    private Properties functionProp = null;
    protected static UsrQy usrqy;
    protected static Config config;
    protected static String projectPath;
    protected static String projectName;


    public Controller() {}

    public void init() {
 usrqy = new UsrQy();
        config = new Config();
 actionProp = new Properties();
 functionProp = new Properties();
 readConf();
    }

    public void readConf() {
        String action = config.getIni("Action");
        String function = config.getIni("Action");

 try {
  actionProp.load(new FileInputStream(action));
  functionProp.load(new FileInputStream(function));
        } catch(IOException e) { System.out.println(e); }
    }

    public void destroy() {
 super.destroy();
    }

    public void doGet(HttpServletRequest request,HttpServletResponse response)
 throws ServletException, IOException
    {
        response.setContentType("text/html");
        String action = (String)request.getParameter("action");
        // System.out.println("get, action="+action);
 if(action == null) return;
 HttpSession session = request.getSession(true);
        String user=(String)session.getAttribute("username");
        // System.out.println("get, user="+user);
        if(user==null)action="reject";
 forwardAction(action, request, response);
    }

    public void doPost (HttpServletRequest request, HttpServletResponse response)
 throws ServletException, IOException
    {
        response.setContentType("text/html");

 String action = (String)request.getParameter("action");
 if(action == null) return;
        if(action.endsWith("-ByUrl")) {
           action = action.substring(0, action.length()-6);
           String check = checkUser(request);
           if(check.equals("login"));
           else action = check;
           forwardAction(action, request, response);
           return;
        }
     
        if(action.equals("login") || action.equals("restart"))
                action = checkUser(request);

        forwardAction(action, request, response);
    }

    public void forwardAction(String action, HttpServletRequest request,
 HttpServletResponse response) throws ServletException, IOException
    {
 // Send the user on to the main screen
 ServletContext context = getServletContext();
 if(context != null) {
  String dispatch = actionProp.getProperty(action);
  if(dispatch == null) return;
         RequestDispatcher rdis = context.getRequestDispatcher(dispatch);
         rdis.forward(request, response);
 }
    }
    public String checkUser(HttpServletRequest request)
 throws ServletException, IOException
    {
 HttpSession session = request.getSession(true);
 if(session == null) { return "relogin"; }

 // Get the user name and password from the login/restart form
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        // System.out.println("chkUser, username="+username+" password="+password);

 if(username == null || username.length() < 1) {
     session.setAttribute("rejectReason", "No Username");
     return "reject";
        }
        if(password == null || password.length() < 1) {
     session.setAttribute("rejectReason", "No Password");
     return "reject";
        }
 
 // validate database connection
        // dba.validate();
        //if(username.length()==5 && username.substring(0,1).equals("P"))
        if(username.substring(0,1).equals("P"))
           username="OSF"+username;

        username=username.trim();

        if(username.equals("GUEST") || username.substring(0,5).equals("NOTES")){
           // if login with GUEST, no need to check password
        } else if(!usrqy.chkPasswd(username, password)) {
            //System.out.println("OSF USER="+username+"  "+password);
     session.setAttribute("rejectReason", "Wrong Password");
     return "reject";
        }
 // create a user to use this session

     session.setAttribute("username", username);
     session.setAttribute("password", password);

       
        Vector v = new Vector();
        if(username.equals("GUEST")){
           v.add("GUEST");
           v.add("GUEST");
           v.add("elaine_chen@promos.com.tw");
           v.add("");
    } else if(username.substring(0,5).equals("NOTES")){
           v.add(username);
           v.add(password);
           v.add("elaine_chen@promos.com.tw");
           v.add("");
 } else if(username.substring(0,3).equals("ESF")){
           v.add(username);
           v.add(password);
           v.add("elaine_chen@promos.com.tw");
           v.add("");
 } else {
     v = usrqy.getInfo(username);
        }
 setCache(v, session);  
 setFunc(functionProp, session);
 return "login";
    }

    static void setCache(Vector v, HttpSession session)
    { 
 session.setAttribute("username", (String)v.elementAt(0));
 session.setAttribute("password", (String)v.elementAt(1));
 session.setAttribute("email", (String)v.elementAt(2));
 session.setAttribute("authority", (String)v.elementAt(3));
    }
    static void setFunc(Properties p, HttpSession session)
    {
 Enumeration enu = p.propertyNames();
 String key, value;
        while(enu.hasMoreElements()) {
                key = (String)enu.nextElement();
                value = p.getProperty(key);
  session.setAttribute(value, key);
        }
    }

    public static String setUrl(HttpServletRequest request,
                HttpServletResponse response, String action)
        {
                String url = null;
                // String path = "/osfweb/servlet/Controller";
   String path = "/"+config.getProjectName()+"/servlet/Controller";
                String host = request.getHeader("host");

                /* Elaine 2005-03-23 set no cache */
                response.setHeader("Pragma","no-cache");
                response.setHeader("Cache-Control","no-cache");
                response.setDateHeader("Expires", 0);

                HttpSession session = request.getSession(true);
                if(session == null){
                      // System.out.println("session is null");
                      url = "http://" +host+ response.encodeURL(path)+"?action=" +"reject";
                }else{
                      // url = "http://" +host+ response.encodeURL(path)
                      url = "http://" +host+ response.encodeURL(path)+"?action=" +action;
                }
                return url;
        }


= = = = = = = =  = = = = = = = =  = = = = = = = =  = = = = = = = =  = = = = = = = =  = = = = = = = = 

展示jsp如何執行動作的

---------------------------

addEOCAP.jsp

-------------------------

<%//@ page contentType="text/html;charset=big5"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="GBK"%>
<%@ page import="java.util.*, java.io.*, java.net.URL" %>
<%@ page import="bean.general.Controller" %>


<html>
<body>
<jsp:useBean id="EOCAPQy" scope="page" class="bean.oqc.EOCAPQy"/>
<jsp:useBean id="usrQy" scope="page" class="bean.UsrQy"/>
<jsp:useBean id="layout" scope="page" class="bean.main.component.Layout" />
<jsp:useBean id="forward" scope="page" class="bean.main.component.ActionUrl" />

<LINK href="../css/all.css" rel=stylesheet type=text/css>
<LINK href="../css/td.css" rel=stylesheet type=text/css>
<LINK href="../css/Input.css" rel=stylesheet type=text/css>
<style>
.C1 {font-family: Arial; font-size:9pt;color:red}
</style>
<%
// *********************** Check Privilege  ********************************* 
 String username = (String)request.getSession().getAttribute("username");
 String password = (String)request.getSession().getAttribute("password");
 //boolean flag = usrqy.getAuthority(username,password,"MODHOLDTOOL");
 
 if(username == null) {
  String reurl=  Controller.setUrl(request,response ,"illegalPage");
  response.sendRedirect(reurl);
 }
// **************************** Get Controller  ********************************* 
 String url=  Controller.setUrl(request,response ,"addEOCAP");
 String saveurl=  Controller.setUrl(request,response ,"addEOCAPSave");
 String qryurl=Controller.setUrl(request,response ,"qryMEOCAP");
 
 String RECPID= (String)request.getSession().getAttribute("RECPID");
 String DEPTNO= (String)request.getSession().getAttribute("DEPTNO");
 String ROOTCAUSE="";
 String DISPOSITION="";
 
%>

<jsp:include page = "../osfmenu.jsp" />

<form name="displayForm" method="post">

<script language="javascript">
 function doupload()
 {
  document.displayForm.action="<%=url%>";
  document.displayForm.submit();
 }
 function resetPage()
 {
  document.displayForm.reset();
 }
 function donewroot(){
  var rootin = prompt('Please input new RootCause !!','');
  if(rootin == null || rootin =="null" || rootin =="") document.displayForm.ROOTCAUSE.value = "";
  else{
   var Upperin = rootin;
   var no = new Option();
         no.value = Upperin;
         no.text = Upperin; 
   var len=document.displayForm.ROOTCAUSE.options.length;
         document.displayForm.ROOTCAUSE.options[len] = no;
         document.displayForm.ROOTCAUSE.options[len].selected=true;
  }// else
  
 }// function donewroot()
 function check()
 {
  if(document.displayForm.ROOTCAUSE.value==null || document.displayForm.ROOTCAUSE.value==""){
   alert("Please Input EVENT !!")
   document.displayForm.ROOTCAUSE.focus();
   return;
  }
  if(document.displayForm.DISPOSITION.value==null || document.displayForm.DISPOSITION.value==""){
   alert("Please Input DISPOSITION !!")
   document.displayForm.DISPOSITION.focus();
   return;
  }
    
  if(!confirm("Are you sure to add ?")){
   return;
  }
  document.displayForm.action="<%=saveurl%>";
  document.displayForm.submit();
 }// check()
 
 function qry(){
         window.location="<%=qryurl%>&backCRI=Y";
    }  
</script>
<%
// **************************Display Title  *********************************
String title = "E-OCAP MAINTAIN -- Add";
layout.titleDate(out, title, username, " 80%" );

%>
<table cellspacing="0" cellpadding="0" border="0" align="center" width="80%">
<tr><td height="4" class="th2"></td></tr>
<tr align="right">
<td><a href="javascript:qry()"><img src="../images/button/pic-1.gif"" border="0"><font class="button1">Query</font></a>
</td></tr>
</table>
<br>

<table width="80%" border="0" cellpadding="0" cellpadding="0" align="center">
<tr><td>
</td></tr>
<table cellspacing="0" cellpadding="0" border="0" align="center" width="80%">
<tr><td width=10% align="left" class="head1">RECPID</td>
<td width=30% align="left">
<input type="text" name="RECPID" value="<%=RECPID%>" class="light3" readonly>
</td></tr>
<tr><td width=10% align="left">EVENT</td>
<td width=25% align="left">
<select name="ROOTCAUSE" class="opted">
<%if(ROOTCAUSE!=null && !ROOTCAUSE.equals(""))  {%>
   <option value="<%=ROOTCAUSE%>"><%=ROOTCAUSE%></option>
<%}%>
<% Vector v_ROOTCAUSE =EOCAPQy.getrootcause(RECPID);
if(v_ROOTCAUSE!=null && v_ROOTCAUSE.size()>0){
    for(int i=0; i<v_ROOTCAUSE.size(); i++){
       out.println("<option value="+v_ROOTCAUSE.elementAt(i)+">"+v_ROOTCAUSE.elementAt(i)+"</option>");
    } // for
}// if v_ROOTCAUSE
%>
</select>
</td></tr>
<tr><td width=20%></td>
<td width=80%>If other EVENT needed, please press <a href="javascript:donewroot();"><IMG src="../images/base/ico-add.gif" border="0" width="18" height="18" alt="Press here to new a module."></a> to new a EVENT .</td>
</tr>
<tr><td width=10% align="left">DISPOSITION</td>
<td width=70% colspan="3">
<input type="text" name="DISPOSITION" value="<%=DISPOSITION%>" class="light1" maxlength="96">
</td></tr>
<tr><td width=20%></td>
<td class="C1" width=80%>Chinese and %,  /,  ',  ",  >,  < characters are unacceptable.</td>
</tr>

</table>
</td>
<tr>
<td align="center">
<% // **************************** Display Buttons  ***************************************
  String ckbox="run";
  layout.buttonRSCheckScript( out, "50%", ckbox , "resetPage", "check" );
%>
</td></tr>
</table>

</form>
</body>
</html>

----------------------------------

EOCAPQy.java

----------------------------------

package bean.oqc;

import bean.general.Logfile;
import bean.HouseSql;
import bean.DreamsSql;
import java.io.*;
import java.util.*;
import java.sql.*;

public class EOCAPQy {
 protected static DreamsSql dreams;
 protected static Logfile log;
 protected static String selectAll;
 protected static String table;
 protected static String his_tab;
 protected static String hist_col;
 protected static String col;
 protected static String col2;
 
 public EOCAPQy()
 {
  if(dreams==null) dreams = new DreamsSql();
  if(log==null) log = new Logfile("EOCAP");
  if(table==null) table = "EOCAP";
  if(col==null)
   col = " RECPID,ROOTCAUSE,DISPOSITION,OCAPNO,DEPTNO,FLAG,UPDUSER,UPDTIME ";
 }
 public Vector getSql(String RECPID,String OCAPNO)
 {
  String s_recpid = RECPID;
  String s_ocapno = OCAPNO;
  if(RECPID==null) s_recpid="";
  if(OCAPNO==null) s_ocapno="";
  String select = " SELECT RECPID,ROOTCAUSE,DISPOSITION,OCAPNO,DEPTNO,UPDUSER,UPDTIME from ";
  String where = " WHERE RECPID = '"+s_recpid+"' AND OCAPNO='"+s_ocapno+"' order by ROOTCAUSE,DISPOSITION";
  log.writeLog("getsql="+select+table+where);
  String sql = select+table+where;
  Vector v = dreams.getSelect(sql);
  return v;
 }
 public Vector getSqlWait(String recpid)
 {
  String s_recpid = recpid;
  if(recpid==null) s_recpid="";
  String select = " SELECT RECPID,ROOTCAUSE,DISPOSITION,nvl(OCAPNO,'-') OCAPNO,DEPTNO,UPDUSER,UPDTIME from ";
  String where = " WHERE RECPID = '"+s_recpid.trim()+"' AND FLAG='WAIT' order by ROOTCAUSE,DISPOSITION";
  log.writeLog("getsqlWait="+select+table+where);
  String sql = select+table+where;
  Vector v = dreams.getSelect(sql);
  return v;
 }
 public Vector getrootcause(String recpid)
 {
  String s_recpid = recpid;
  if(recpid==null) s_recpid="";
  String where = " RECPID = '"+s_recpid.trim()+"' group by ROOTCAUSE";
  log.writeLog("getrootcause="+table+where);
  Vector v = dreams.getDistinct("ROOTCAUSE",table,where);
  return v;
 }
 public String addrecord(String recpid,String rootcause,String disposition,String deptno,String username)
 {
  String sql = "insert into "+table+"(recpid,rootcause,disposition,deptno,flag,upduser,updtime)";      
  sql += " values('"+recpid.trim()+"','"+rootcause.trim()+"','"+disposition.trim()+"','"+deptno.trim()+"','WAIT','"+username.trim()+"',sysdate)";
  System.out.println("add sql="+sql);
  log.writeLog("addsql="+sql);
  int success = dreams.execSql(sql);
  log.writeLog("add success="+success);
  if(success==-1){
            return "Fail. Add EOCAP data error.";
          }
        if(success==0){
            return "Fail. data unique constraint violated.";
          }
  return "OK";
 }
 public String delete(String recpid,String rootcause,String disposition)
 {
  if(recpid == null || recpid.equals("")) return "0";
  if(rootcause == null || rootcause.equals("")) return "0";
  if(disposition == null || disposition.equals("")) return "0";  
  String sql = "delete from "+table+" where recpid='"+recpid+"' and trim(rootcause)='"+rootcause.trim()+"' and TRIM(disposition)='"+disposition.trim()+"' AND FLAG='WAIT'";
  System.out.println("delete sql="+sql);
  log.writeLog("del sql="+sql);
  int success = dreams.execSql(sql);
  log.writeLog("del success="+success);
  if(success==-1){
            return "Fail. Delete EOCAP data error.";
          }
  return "OK";
 }
 public String copy(String recpid,String deptno,String username)
 {
  if(recpid == null || recpid.equals("")) return "0";
  String sql = "INSERT INTO EOCAP(RECPID,ROOTCAUSE,DISPOSITION,DEPTNO,UPDUSER,FLAG)";
        sql += " (SELECT RECPID,ROOTCAUSE,DISPOSITION,'"+deptno.trim()+"','"+username.trim()+"','WAIT' FROM EOCAP";
        sql += " WHERE RECPID='"+recpid+"' AND FLAG='ACT')";
  System.out.println("copy sql="+sql);
  log.writeLog("copy sql="+sql);
  int success = dreams.execSql(sql);
  log.writeLog("copy success="+success);
  if(success==-1){
            return "Fail. Copy EOCAP data error.";
          }
        if(success==0){
            return "Fail. No data in current version.";
          }
  return "OK";
 }
 public String update(String recpid,String rootcause,String old_disposition,String new_disposition,String username,String deptno)
 {
  if(recpid == null || recpid.equals("")) return "0";
  if(rootcause == null || rootcause.equals("")) return "0";
  if(old_disposition == null || old_disposition.equals("")) return "0";
  if(new_disposition == null || new_disposition.equals("")) return "0";
  String sql = "update "+table+" set disposition='"+new_disposition.trim()+"',updtime=sysdate,upduser='"+username.trim()+"',deptno='"+deptno+"'";
  sql += " where recpid='"+recpid+"' and trim(rootcause)='"+rootcause+"' and trim(disposition)='"+old_disposition.trim()+"' AND FLAG='WAIT'";
  System.out.println("update sql="+sql);
     log.writeLog("updsql="+sql);
  int success = dreams.execSql(sql);
  log.writeLog("update success="+success);
  if(success==-1){
            return "Fail. Update EOCAP data error.";
          }
        if(success==0){
            return "Fail. data unique constraint violated.";
          }
  return "OK";
 }
 
 public static void main(String args[])
 {
  EOCAPQy qy = new EOCAPQy();

 }
}

-------------------------------------

DreamsSql.java

-------------------------------------

package bean;
import bean.DbControllerP;
import bean.general.Logfile;
import bean.general.Config;
import java.util.*;
import java.text.*;
import java.sql.*;
import java.io.*;

/* 2004-09-06
if copy the program to excess another DB,
please update 2 spots.
1. alais --> one DB one alias, ex: prs, prstest
2. dbfile = config.getDbconf("dbfile"); --> It depends on the project.ini setup.
*/


public class DreamsSql
{
    private DbControllerP dba;
    private static Config config;
    private static Logfile log;
    private String projectfile = "/project.ini";
    private String ProjectPath = null;
    private static String alias="osfweb";
    private static String dbfile;
    private static final int sqlTimeout = 90;


    public DreamsSql() {

        if(log==null) log = new Logfile("dreamsSql");
        if(config==null) config = new Config();
        if(ProjectPath==null) ProjectPath = config.getHome();
        if(dbfile==null) dbfile = config.getDbconf("dbfile");

        if(dba==null) dba=DbControllerP.getInstance(dbfile,alias);
    }

    public String getJtSum(String s,String s2,String s1)
    {
        Connection conn = dba.getConnection();
        Statement statement = null;
        String s4 = "";
        try
        {
            statement = conn.createStatement();
            Vector vector = new Vector();
            String s3 = "select sum(" + s + ") from " + s2;
            if(s1 != null)
                s3 = s3 + " where " + s1;
            ResultSet rs = statement.executeQuery(s3);
            if(rs.next()) {
              s4 = rs.getString(1);
            } else {
              throw new SQLException("Unable to get Sum");
            }
        } catch(Exception e) {System.out.print(e);}
        finally
        {
            if(statement != null)
                try
                {
                    statement.close();
                }
                catch(Exception exception1) {System.out.println(exception1); }
            if(conn!=null){
                try {
      dba.destroy(conn);
      //conn.close();
                }catch(Exception exception2) {System.out.println(exception2); }
     }
        }
        if (s4==null) return "0";
        else return s4;
    }

    public Vector getSql(String s, String t, String s1)
    {
        Connection conn = dba.getConnection();
        Vector tmpVec = new Vector();
        Vector retVec = new Vector();
        Statement statement = null;
        String s3="";
        try
        {
            statement = conn.createStatement();
            statement.setQueryTimeout(sqlTimeout);
            s3 = "select " + s + " from " + t;
            if(s1 != null) s3 = s3 + " where " + s1;

            ResultSet rs = statement.executeQuery(s3);
            ResultSetMetaData rsmd=rs.getMetaData();
           
            while(rs.next()){
                for(int i=1;i<=rsmd.getColumnCount();i++){
     tmpVec.addElement(rs.getString(i));
                }
                retVec.add(tmpVec.clone());
                tmpVec.clear();
            }
     conn.commit();
        }catch(Exception e) {
               System.out.print(s3+" "+e);
               log.writeLog(s3+" "+e.toString());
               if(e.toString().indexOf("ORA-01013")>0){
                 tmpVec.addElement("<script>alert('QUERY TIMEOUT !!')</script>");
                 retVec.add(tmpVec.clone());
                 tmpVec.clear();
               }

 }
        finally
        {
            if(statement != null)
                try {
                    statement.close();
                } catch(Exception exception1) { }
            if(conn!=null){
                try {
      dba.destroy(conn);
      //conn.close();
                }catch(Exception exception2) {System.out.println(exception2); }
     }

        }
        return retVec;
    }

    public int delete(String s,String s1)
    {
        Connection conn = dba.getConnection();
        Statement statement = null;
        String sql = "Delete " + s + " where " + s1;
        int rows = 0;
        try
        {
            statement = conn.createStatement();
     rows = statement.executeUpdate(sql);
        } catch(Exception e) {System.out.print(sql);}
        finally
        {
            if(statement != null)
                try
                {
                    statement.close();
                }
                catch(Exception exception1) { }
            if(conn!=null){
                try {
      dba.destroy(conn);
      //conn.close();
                }catch(Exception exception2) {System.out.println(exception2); }
     }
        }
       
        return rows;
    }           
   
    public int update(String s)
    {
        Connection conn = dba.getConnection();
        Statement statement = null;
        // String sql = "Delete " + s + " where " + s1;
        String sql =  s ;
        int rows = 0;
        try
        {
            statement = conn.createStatement();
     rows = statement.executeUpdate(sql);
        } catch(Exception e) {
            System.out.print(sql);
            log.writeLog(sql+" "+e.toString());
 }
        finally
        {
            if(statement != null)
                try
                {
                    statement.close();
                }
                catch(Exception exception1) { }
            if(conn!=null){
                try {
      dba.destroy(conn);
      //conn.close();
                }catch(Exception exception2) {System.out.println(exception2); }
     }
        }
       
        return rows;
    }           

 

    public int execSql(String s)
    {
        Connection conn = dba.getConnection();
        Statement statement = null;
        String sql =  s ;
        int rows = 0;
        try
        {
            statement = conn.createStatement();
     rows = statement.executeUpdate(sql);
        } catch(Exception e) {
            System.out.println(sql+" "+e.toString());
            log.writeLog(sql+" "+e.toString());
        }
        finally
        {
            if(statement != null)
                try
                {
                    statement.close();
                }
                catch(Exception exception1) { }
            if(conn!=null){
                try {
      dba.destroy(conn);
      //conn.close();
                }catch(Exception exception2) {System.out.println(exception2); }
     }
        }
       
        return rows;
    }           


    public int getCount(String s,String s1) //throws SQLException
    {
        Connection conn = dba.getConnection();
        Statement statement = null;
 Vector tmpVec = new Vector();
 Vector retVec = new Vector();

        int i=0;
        String sql = "select count(*) from " + s ;
        if(s1!=null && !s1.equals(""))
           sql += " where " + s1;
       
        // System.out.println("sql = " + sql);
       
        try
        {
            statement = conn.createStatement();
            statement.setQueryTimeout(sqlTimeout);
            ResultSet resultset = statement.executeQuery(sql);
            if(resultset.next())
            {
                i = resultset.getInt(1);
            } else
            {
                System.out.println(resultset.getWarnings());
                throw new SQLException("Unable to get count number");
            }
     conn.commit();
    
        }
        catch(Exception e) {
        System.out.println(sql+" "+e);
               log.writeLog(sql+" "+e.toString());
 }
        finally
        {
            if(statement != null)
                try
                {
                    statement.close();
                }
                catch(Exception exception1) {System.out.println(exception1); }
            if(conn!=null){
                try {
      dba.destroy(conn);
      //conn.close();
                }catch(Exception exception2) {System.out.println(exception2); }
     }
        }       
        return i;
    }
    public Vector getDistinct(String f,String s,String s1) //throws SQLException
    {
        Connection conn = dba.getConnection();
        Statement statement = null;
        Vector v=new Vector();
        String sql = "select distinct " + f + " from " + s ;

        if(s1!=null && !s1.equals("")) sql += " where " + s1;
       
        // System.out.println("sql = " + sql);
       
        try
        {
            statement = conn.createStatement();
            statement.setQueryTimeout(sqlTimeout);
            ResultSet resultset = statement.executeQuery(sql);
            while(resultset.next()) {
                v.add(resultset.getString(1));
            }
     conn.commit();
        }
        catch(Exception e) {
        System.out.println(sql+" "+e);
               log.writeLog(sql+" "+e.toString());
               if(e.toString().indexOf("ORA-01013")>0){
                   v.addElement("<script>alert('QUERY TIMEOUT !!')</script>");
               }

 }
        finally
        {
            if(statement != null)
                try
                {
                    statement.close();
                }
                catch(Exception exception1) {System.out.println(exception1); }
            if(conn!=null){
                try {
      dba.destroy(conn);
      //conn.close();
                }catch(Exception exception2) {System.out.println(exception2); }
     }
        }       
        return v;
    }

    public int insert(String s,String s1)
    {
        Connection conn = dba.getConnection();
        Statement statement = null;
        String sql = "insert into " + s +" values (" + s1 + ")";
        int rows = 0;
        try
        {
            statement = conn.createStatement();
     rows = statement.executeUpdate(sql);
        } catch(Exception e) {System.out.println(sql+" "+e);}
        finally
        {
            if(statement != null)
                try
                {
                    statement.close();
                }
                catch(Exception exception1) { }
            if(conn!=null){
                try {
      dba.destroy(conn);
      //conn.close();
                }catch(Exception exception2) {System.out.println(exception2); }
     }
        }
       
        return rows;
    }           

    public Vector getSelect(String s)
    {
        Connection conn = dba.getConnection();
        Vector tmpVec = new Vector();
        Vector retVec = new Vector();
        Statement statement = null;
        ResultSet rs = null;
        try
        {
            statement = conn.createStatement();
            statement.setQueryTimeout(sqlTimeout);
            rs = statement.executeQuery(s);
            ResultSetMetaData rsmd=rs.getMetaData();
           
            while(rs.next()){
                for(int i=1;i<=rsmd.getColumnCount();i++){
     tmpVec.addElement(rs.getString(i));
                }
                retVec.add(tmpVec.clone());
                tmpVec.clear();
            }
     conn.commit();
        }catch(Exception e) {
        System.out.println(s+" "+e);
               if(e.toString().indexOf("ORA-01013")>0){
                 tmpVec.addElement("<script>alert('QUERY TIMEOUT !!')</script>");
                 retVec.add(tmpVec.clone());
                 tmpVec.clear();
               }
 }
        finally
        {
            if(statement != null)
                try {
                    statement.close();
                } catch(Exception exception1) { }
            if(rs != null)
                try {
                    rs.close();
                } catch(Exception exception2) { }
            if(conn!=null){
                try {
      dba.destroy(conn);
      //conn.close();
                }catch(Exception exception3){System.out.println(exception3); }
     }

        }
        return retVec;
    }

    public String execBatchSql(Vector s) //throws SQLException
    {
        if(s==null && s.size()==0) return "fail";

        Connection conn = dba.getConnection();
        Statement stmt = null;
        String retS="";
        int sum = 0;
        try
        {
              conn.setAutoCommit(false);
              stmt = conn.createStatement();
              for(int p=0; p<s.size(); p++)
                  stmt.addBatch((String)s.elementAt(p));

              int[] cnt = stmt.executeBatch();
              for(int k=0; k<cnt.length; k++) sum+=cnt[k];
              if(sum!=s.size()){
                conn.rollback();
         retS="FAIL. Count should be "+s.size()+",but it is="+sum;
              }else{
                conn.commit();
         retS="OK.";
       }
        }
        catch(Exception e) {
             try {
                  conn.rollback();
                  conn.setAutoCommit(true);
             }catch(Exception ce){System.out.println("setAutoCommit fail");}

             retS += e.toString();
             System.out.println("dreams execBatchSql Exception:"+e);
             log.writeLog(e.toString());
             for(int p=0; p<s.size(); p++) log.writeLog((String)s.elementAt(p));
 }
        finally
        {
            if(stmt != null)
                try {
                    stmt.close();
                }catch(Exception exception1) {System.out.println(exception1); }
            if(conn!=null){
                try {
                    conn.setAutoCommit(true);
      dba.destroy(conn);
                }catch(Exception exception2) {System.out.println(exception2); }
     }
        }       
        return retS;
    }

    // Elaine added 2005-05-05
    public String execBatchSql_nocheck(Vector s) //throws SQLException
    {
        if(s==null && s.size()==0) return "fail";

        Connection conn = dba.getConnection();
        Statement stmt = null;
        String retS="";
        try
        {
              conn.setAutoCommit(false);
              stmt = conn.createStatement();
              for(int p=0; p<s.size(); p++)
                  stmt.addBatch((String)s.elementAt(p));

              int[] cnt = stmt.executeBatch();
              conn.commit();
              conn.setAutoCommit(true);
       retS="OK.";
        }
        catch(Exception e) {
             try {
                  conn.rollback();
                  conn.setAutoCommit(true);
             }catch(Exception ce){System.out.println("setAutoCommit fail");}

             retS += e.toString();
             System.out.print(e);
             log.writeLog(e.toString());
             for(int p=0; p<s.size(); p++) log.writeLog((String)s.elementAt(p));
 }
        finally
        {
            if(stmt != null)
                try {
                    stmt.close();
                }catch(Exception exception1) {System.out.println(exception1); }
            if(conn!=null){
                try {
      dba.destroy(conn);
                }catch(Exception exception2) {System.out.println(exception2); }
     }
        }       
        return retS;
    }

  public void removeconn(){
        dba.releaseAllConn();
  }

}

--------------------------

DbControllerP.java

--------------------------

// Decompiled by Jad v1.5.7g. Copyright 2000 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/SiliconValley/Bridge/8617/jad.html
// Decompiler options: packimports(3) fieldsfirst ansi
// Source File Name:   DbControllerP.java

package bean;

import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.*;
import oracle.jdbc.driver.OracleDriver;

public class DbControllerP
{

    private DbControllerP instance;
    private static Hashtable pools;
    private Properties p;
    private Hashtable poolconn_hash;
    private int max_conn;
    private int min_conn;
    private String dbUrl;
    private String dbUsr;
    private String dbPw;
    private String dbconf;
    private String logfile;
    private static PrintWriter log;

    public static synchronized DbControllerP getInstance(String s, String s1)
    {
        if(pools == null)
            pools = new Hashtable();
        if(pools.size() > 0 && pools.get(s1) != null)
        {
            return (DbControllerP)pools.get(s1);
        } else
        {
            DbControllerP dbcontrollerp = new DbControllerP(s);
            pools.put(s1, dbcontrollerp);
            return dbcontrollerp;
        }
    }

    private DbControllerP(String s)
    {
        max_conn = 5;
        min_conn = 3;
        log = null;
        setDbProperties(s);
        if(poolconn_hash == null)
            poolconn_hash = new Hashtable();
    }

    public void setMaxConn(int i)
    {
        max_conn = i;
    }

    public void setMinConn(int i)
    {
        min_conn = i;
    }

    public Properties getProperties()
    {
        try
        {
            p = new Properties();
            p.load(new FileInputStream(dbconf));
        }
        catch(IOException ioexception)
        {
            log(ioexception, "get properties exception." + ioexception);
        }
        return p;
    }

    public void setDbProperties(String s)
    {
        dbconf = s;
        p = getProperties();
        dbUrl = "jdbc:oracle:thin:@" + p.get("server") + ":" + p.get("port") + ":" + p.get("database");
        dbUsr = p.getProperty("user");
        dbPw = p.getProperty("password");
        max_conn = Integer.parseInt(p.getProperty("max_conn"));
        min_conn = Integer.parseInt(p.getProperty("min_conn"));
        logfile = p.getProperty("logfile");
        setLog(logfile == null ? "connection.log" : logfile);
        log(dbUrl + " " + dbUsr + " " + max_conn);
    }

    public void setLog(String s)
    {
        try
        {
            log = new PrintWriter(new FileWriter(s, true), true);
        }
        catch(IOException ioexception)
        {
            System.err.println("Can't open the log file: " + s);
            log = new PrintWriter(System.err);
        }
    }

    public void createnewConnection()
    {
        try
        {
            if(poolconn_hash.size() < max_conn)
            {
                DriverManager.registerDriver(new OracleDriver());
                Connection connection = DriverManager.getConnection(dbUrl, dbUsr, dbPw);
                poolconn_hash.put(connection, "true");
            } else
            {
                log("conn > " + max_conn);
            }
        }
        catch(Exception exception)
        {
            log(exception, "DbConnection.createnewConnction " + exception);
        }
    }

    public void createConnectionPool(String s, String s1, String s2)
    {
        dbUrl = s;
        dbUsr = s1;
        dbPw = s2;
        try
        {
            if(poolconn_hash == null)
            {
                poolconn_hash = new Hashtable();
                DriverManager.registerDriver(new OracleDriver());
                Connection connection = DriverManager.getConnection(dbUrl, dbUsr, dbPw);
                poolconn_hash.put(connection, "true");
            }
        }
        catch(Exception exception)
        {
            log(exception, "Unable to open Datasource.");
        }
    }

    public void releaseAllConn()
    {
        try
        {
            if(poolconn_hash != null)
            {
                Connection connection;
                for(Enumeration enumeration = poolconn_hash.keys(); enumeration.hasMoreElements(); connection.close())
                {
                    connection = (Connection)enumeration.nextElement();
                    poolconn_hash.remove(connection);
                }

                if(poolconn_hash.size() > 0)
                    log("my fault , i don't know what happened");
            } else
            {
                poolconn_hash = new Hashtable();
            }
        }
        catch(Exception exception)
        {
            log("DbControllerp.releaseAllConn " + exception);
        }
    }

    public void createConnectionPool()
    {
        if(dbUrl == null || "".equals(dbUrl))
            dbUrl = "jdbc:oracle:thin:@192.168.16.27:1521:pps";
        if(dbUsr == null || "".equals(dbUsr))
            dbUsr = "prstest";
        if(dbPw == null || "".equals(dbPw))
            dbPw = "prstest";
        createConnectionPool(dbUrl, dbUsr, dbPw);
    }

    public synchronized Connection getConnection()
    {
        try
        {
            log("this is connpool size=" + poolconn_hash.size());
            if(poolconn_hash.size() == 0 || !poolconn_hash.contains("true"))
                createnewConnection();
            for(Enumeration enumeration = poolconn_hash.keys(); enumeration.hasMoreElements();)
            {
                Connection connection = (Connection)enumeration.nextElement();
                if("true".equals((String)poolconn_hash.get(connection)))
                {
                    poolconn_hash.remove(connection);
                    poolconn_hash.put(connection, "lock");
                    log("found...");
                    return connection;
                }
            }

            return null;
        }
        catch(Exception exception)
        {
            log(exception, "DbControllerP.getConnection " + exception);
        }
        return null;
    }

    public synchronized void releaseConnection(Connection connection)
    {
        if(connection != null)
            try
            {
                if(poolconn_hash.size() > min_conn)
                {
                    poolconn_hash.remove(connection);
                    connection.close();
                    connection = null;
                } else
                {
                    poolconn_hash.remove(connection);
                    poolconn_hash.put(connection, "true");
                }
            }
            catch(Exception exception)
            {
                log(exception, "DbControllerP.releaseConnection " + exception.toString());
            }
    }

    public void destroy(Connection connection)
    {
        releaseConnection(connection);
    }

    private void log(String s)
    {
        if(log != null)
            log.println(new Date() + ": " + s);
    }

    private void log(Throwable throwable, String s)
    {
        if(log != null)
        {
            log.println(new Date() + ": " + s);
            throwable.printStackTrace(log);
        }
    }
}
------------------------

logfile.java

-----------------------

/* Logfile.java */

package bean.general;
import java.io.*;
import java.util.*;

public class Logfile {
    public static final String HOME  = "/export/home/osfweb";
    String filename;

 public Logfile(String file) {
      try{
             filename = HOME+"/logs/"+file+".log"; 
         }catch(Exception e){
              System.err.println(e.toString());
         }
 }

 public void writeLog(String result) {
    try {
  File file  = new File(filename);
  PrintWriter pw;
  if(file.exists())
   pw = new PrintWriter(new FileOutputStream(filename, true));
  else
   pw = new PrintWriter(new FileOutputStream(filename, false));
  String time = "["+ new Date() + "] ";
  pw.println(time+result);
  pw.flush();
  pw.close();
    } catch(Exception ex){
  System.out.println("Unable to write log file !" + ex.getMessage());
           }
 }
}

= = = = = = = = = = = = = = = = = = = = = = == = = == = = ==  = = = ==  =  = = = = = = = =  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值