KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > edu > rice > rubis > servlets > RubisHttpServlet


1 /*
2  * RUBiS
3  * Copyright (C) 2002, 2003, 2004 French National Institute For Research In Computer
4  * 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, Julie Marguerite
22  * Contributor(s): Jeremy Philippe
23  */

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

45 public abstract class RubisHttpServlet extends HttpServlet JavaDoc
46 {
47   /** Controls connection pooling */
48   private static final boolean enablePooling = false;
49   /** Stack of available connections (pool) */
50   private Stack JavaDoc freeConnections = null;
51   private int poolSize;
52   private Properties JavaDoc dbProperties = null;
53
54   public abstract int getPoolSize(); // Get the pool size for this class
55

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

112   public synchronized void initializeConnections() throws SQLException JavaDoc
113   {
114     if (enablePooling)
115     for (int i = 0; i < poolSize; i++)
116     {
117       // Get connections to the database
118
freeConnections.push(
119       DriverManager.getConnection(
120       dbProperties.getProperty("datasource.url"),
121       dbProperties.getProperty("datasource.username"),
122       dbProperties.getProperty("datasource.password")));
123     }
124     
125   }
126
127   /**
128    * Closes a <code>Connection</code>.
129    *
130    * @param connection to close
131    */

132   public void closeConnection(Connection JavaDoc connection)
133   {
134     try
135     {
136       connection.close();
137     }
138     catch (Exception JavaDoc e)
139     {
140
141     }
142   }
143
144   /**
145    * Gets a connection from the pool (round-robin)
146    *
147    * @return a <code>Connection</code> or null if no connection is available
148    */

149   public synchronized Connection JavaDoc getConnection()
150   {
151     if (enablePooling)
152     {
153       try
154       {
155         // Wait for a connection to be available
156
while (freeConnections.isEmpty())
157         {
158           try
159           {
160             wait();
161           }
162           catch (InterruptedException JavaDoc e)
163           {
164            System.out.println("Connection pool wait interrupted.");
165           }
166          }
167       
168
169         Connection JavaDoc c = (Connection JavaDoc) freeConnections.pop();
170         return c;
171       }
172       catch (EmptyStackException JavaDoc e)
173       {
174        System.out.println("Out of connections.");
175         return null;
176       }
177     }
178      else
179      {
180        try
181        {
182         return DriverManager.getConnection(
183         dbProperties.getProperty("datasource.url"),
184         dbProperties.getProperty("datasource.username"),
185         dbProperties.getProperty("datasource.password"));
186        }
187        catch (SQLException JavaDoc ex)
188        {
189         return null;
190        }
191      }
192   }
193
194   /**
195    * Releases a connection to the pool.
196    *
197    * @param c the connection to release
198    */

199   public synchronized void releaseConnection(Connection JavaDoc c)
200   {
201     if (enablePooling)
202     {
203       boolean mustNotify = freeConnections.isEmpty();
204       freeConnections.push(c);
205       // Wake up one servlet waiting for a connection (if any)
206
if (mustNotify)
207       notifyAll();
208     }
209     else
210     {
211       closeConnection(c);
212     }
213     
214   }
215
216   /**
217    * Release all the connections to the database.
218    *
219    * @exception SQLException if an error occurs
220    */

221   public synchronized void finalizeConnections() throws SQLException JavaDoc
222   {
223     if (enablePooling)
224     {
225       Connection JavaDoc c = null;
226       while (!freeConnections.isEmpty())
227       {
228       c = (Connection JavaDoc) freeConnections.pop();
229       c.close();
230       }
231     }
232   }
233
234   /**
235    * Clean up database connections.
236    */

237   public void destroy()
238   {
239     try
240     {
241       finalizeConnections();
242     }
243     catch (SQLException JavaDoc e)
244     {
245     }
246   }
247
248 }
Popular Tags