KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > edu > rice > rubbos > servlets > RubbosHttpServlet


1 /**
2  * RUBBoS: Rice University Bulletin Board System.
3  * Copyright (C) 2001-2004 Rice University and French National Institute For
4  * Research In Computer Science And Control (INRIA).
5  * Contact: jmob@objectweb.org
6  *
7  * This library is free software; you can redistribute it and/or modify it
8  * under the terms of the GNU Lesser General Public License as published by the
9  * Free Software Foundation; either version 2.1 of the License, or any later
10  * version.
11  *
12  * This library is distributed in the hope that it will be useful, but WITHOUT
13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14  * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
15  * for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public License
18  * along with this library; if not, write to the Free Software Foundation,
19  * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
20  *
21  * Initial developer(s): Emmanuel Cecchet.
22  * Contributor(s): Niraj Tolia.
23  */

24
25 package edu.rice.rubbos.servlets;
26
27 import java.io.FileInputStream JavaDoc;
28 import java.io.FileNotFoundException JavaDoc;
29 import java.io.IOException JavaDoc;
30 import java.io.InputStream JavaDoc;
31 import java.sql.Connection JavaDoc;
32 import java.sql.DriverManager JavaDoc;
33 import java.sql.SQLException JavaDoc;
34 import java.util.EmptyStackException JavaDoc;
35 import java.util.Properties JavaDoc;
36 import java.util.Stack JavaDoc;
37
38 import javax.servlet.ServletException JavaDoc;
39 import javax.servlet.UnavailableException JavaDoc;
40 import javax.servlet.http.HttpServlet JavaDoc;
41 import javax.servlet.http.HttpServletRequest JavaDoc;
42 import javax.servlet.http.HttpServletResponse JavaDoc;
43
44 /**
45  * Provides the method to initialize connection to the database. All the
46  * servlets inherit from this class
47  */

48 public abstract class RubbosHttpServlet extends HttpServlet JavaDoc
49 {
50   /** Controls connection pooling */
51     private static final boolean enablePooling = true;
52   /** Stack of available connections (pool) */
53   private Stack JavaDoc freeConnections = null;
54   private int poolSize;
55   private int currentConn = 0;
56   private Properties JavaDoc dbProperties = null;
57
58   public abstract int getPoolSize(); // Get the pool size for this class
59

60   /** Load the driver and get a connection to the database */
61   public void init() throws ServletException JavaDoc
62   {
63     InputStream JavaDoc in = null;
64     poolSize = getPoolSize();
65     try
66     {
67       // Get the properties for the database connection
68
dbProperties = new Properties JavaDoc();
69       in = new FileInputStream JavaDoc(Config.DatabaseProperties);
70       dbProperties.load(in);
71       // load the driver
72
Class.forName(dbProperties.getProperty("datasource.classname"));
73
74       freeConnections = new Stack JavaDoc();
75       initializeConnections();
76     }
77     catch (FileNotFoundException JavaDoc f)
78     {
79       throw new UnavailableException JavaDoc(
80         "Couldn't find file mysql.properties: " + f + "<br>");
81     }
82     catch (IOException JavaDoc io)
83     {
84       throw new UnavailableException JavaDoc(
85         "Cannot open read mysql.properties: " + io + "<br>");
86     }
87     catch (ClassNotFoundException JavaDoc c)
88     {
89       throw new UnavailableException JavaDoc(
90         "Couldn't load database driver: " + c + "<br>");
91     }
92     catch (SQLException JavaDoc s)
93     {
94       throw new UnavailableException JavaDoc(
95         "Couldn't get database connection: " + s + "<br>");
96     }
97     finally
98     {
99       try
100       {
101         if (in != null)
102           in.close();
103       }
104       catch (Exception JavaDoc e)
105       {
106       }
107     }
108   }
109
110   /**
111    * Initialize the pool of connections to the database.
112    * The caller must ensure that the driver has already been
113    * loaded else an exception will be thrown.
114    *
115    * @exception SQLException if an error occurs
116    */

117   public synchronized void initializeConnections() throws SQLException JavaDoc
118   {
119     if (enablePooling)
120     {
121       for (int i = 0; i < poolSize; i++)
122       {
123         // Get connections to the database
124
freeConnections.push(
125         DriverManager.getConnection(
126           dbProperties.getProperty("datasource.url"),
127           dbProperties.getProperty("datasource.username"),
128           dbProperties.getProperty("datasource.password")));
129       }
130     }
131   }
132
133   // public Connection getConnection()
134
// {
135
// // currentConn = (currentConn + 1) % poolSize;
136
// // return conn[currentConn];
137
// try
138
// {
139
// return DriverManager.getConnection(
140
// dbProperties.getProperty("datasource.url"),
141
// dbProperties.getProperty("datasource.username"),
142
// dbProperties.getProperty("datasource.password"));
143
// }
144
// catch (SQLException e)
145
// {
146
// return null;
147
// }
148
//
149
// }
150

151
152   /**
153   * Closes a <code>Connection</code>.
154   * @param connection to close
155   */

156    private void closeConnection(Connection JavaDoc connection)
157    {
158      try
159      {
160        connection.close();
161      }
162      catch (Exception JavaDoc e)
163      {
164
165      }
166    }
167
168   /**
169    * Gets a connection from the pool (round-robin)
170    *
171    * @return a <code>Connection</code> or
172    * null if no connection is available
173    */

174   public synchronized Connection JavaDoc getConnection()
175   {
176     if (enablePooling)
177     {
178       try
179       {
180         // Wait for a connection to be available
181
while (freeConnections.isEmpty())
182         {
183           try
184           {
185             wait();
186           }
187           catch (InterruptedException JavaDoc e)
188           {
189             System.out.println("Connection pool wait interrupted.");
190           }
191         }
192
193         Connection JavaDoc c = (Connection JavaDoc) freeConnections.pop();
194         return c;
195       }
196
197       catch (EmptyStackException JavaDoc e)
198       {
199         System.out.println("Out of connections.");
200         return null;
201       }
202     }
203     else
204     {
205        try
206        {
207         return DriverManager.getConnection(
208         dbProperties.getProperty("datasource.url"),
209         dbProperties.getProperty("datasource.username"),
210         dbProperties.getProperty("datasource.password"));
211        }
212        catch (SQLException JavaDoc ex)
213        {
214         ex.printStackTrace();
215         return null;
216        }
217     }
218   }
219
220   /**
221    * Releases a connection to the pool.
222    *
223    * @param c the connection to release
224    */

225   public synchronized void releaseConnection(Connection JavaDoc c)
226   {
227     if (enablePooling)
228     {
229       boolean mustNotify = freeConnections.isEmpty();
230       freeConnections.push(c);
231       // Wake up one servlet waiting for a connection (if any)
232
if (mustNotify)
233        notifyAll();
234     }
235     else
236     {
237       closeConnection(c);
238     }
239   }
240
241   /**
242    * Release all the connections to the database.
243    *
244    * @exception SQLException if an error occurs
245    */

246   public synchronized void finalizeConnections() throws SQLException JavaDoc
247   {
248     if (enablePooling)
249     {
250       Connection JavaDoc c = null;
251       while (!freeConnections.isEmpty())
252       {
253         c = (Connection JavaDoc) freeConnections.pop();
254         c.close();
255       }
256     }
257   }
258
259   public void doGet(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response)
260     throws IOException JavaDoc, ServletException JavaDoc
261   {
262
263   }
264
265   public void doPost(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response)
266     throws IOException JavaDoc, ServletException JavaDoc
267   {
268
269   }
270
271   /**
272    * Clean up database connections.
273    */

274   public void destroy()
275   {
276     try
277     {
278       finalizeConnections();
279     }
280     catch (SQLException JavaDoc e)
281     {
282     }
283   }
284
285 }
286
Popular Tags