KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > espada > bugtracker > persistence > DbConnectionBroker


1
2
3 package com.espada.bugtracker.persistence;
4
5 import java.io.*;
6 import java.sql.*;
7 import java.text.DateFormat JavaDoc;
8 import java.text.SimpleDateFormat JavaDoc;
9 import java.util.Date JavaDoc;
10
11 /**
12  *This class is based heavily on Marc Mnich's database connection broker.
13  *Thanks, Marc!
14  *
15  *@author Marc Mnich
16  */

17
18
19 public class DbConnectionBroker
20     implements Runnable JavaDoc
21 {
22
23     public void run()
24     {
25         boolean flag = true;
26         Statement statement = null;
27         Object JavaDoc obj = null;
28         while(flag)
29         {
30             try
31             {
32                 BufferedReader bufferedreader = new BufferedReader(new FileReader(logFileString + "pid"));
33                 String JavaDoc s = bufferedreader.readLine();
34                 if(!s.equals(pid))
35                 {
36                     log.close();
37                     for(int k = 0; k < currConnections; k++)
38                         try
39                         {
40                             connPool[k].close();
41                         }
42                         catch(SQLException sqlexception1) { }
43
44                     return;
45                 }
46                 bufferedreader.close();
47             }
48             catch(IOException ioexception)
49             {
50                 log.println("Can't read the file for pid info: " + logFileString + "pid");
51             }
52             for(int i = 0; i < currConnections; i++)
53                 try
54                 {
55                     currSQLWarning = connPool[i].getWarnings();
56                     if(currSQLWarning != null)
57                     {
58                         log.println("Warnings on connection " + String.valueOf(i) + " " + currSQLWarning);
59                         connPool[i].clearWarnings();
60                     }
61                 }
62                 catch(SQLException sqlexception)
63                 {
64                     log.println("Cannot access Warnings: " + sqlexception);
65                 }
66
67             for(int j = 0; j < currConnections; j++)
68             {
69                 long l = System.currentTimeMillis() - connCreateDate[j];
70                 synchronized(connStatus)
71                 {
72                     if(connStatus[j] > 0)
73                         continue;
74                     connStatus[j] = 2;
75                 }
76                 try
77                 {
78                     if(l > (long)maxConnMSec)
79                         throw new SQLException();
80                     statement = connPool[j].createStatement();
81                     connStatus[j] = 0;
82                     if(connPool[j].isClosed())
83                         throw new SQLException();
84                 }
85                 catch(SQLException sqlexception2)
86                 {
87                     try
88                     {
89                         log.println((new Date JavaDoc()).toString() + " ***** Recycling connection " + String.valueOf(j) + ":");
90                         connPool[j].close();
91                         createConn(j);
92                     }
93                     catch(SQLException sqlexception4)
94                     {
95                         log.println("Failed: " + sqlexception4);
96                         connStatus[j] = 0;
97                     }
98                 }
99                 finally
100                 {
101                     try
102                     {
103                         if(statement != null)
104                             statement.close();
105                     }
106                     catch(SQLException sqlexception3) { }
107                 }
108             }
109
110             try
111             {
112                 Thread.sleep(20000L);
113             }
114             catch(InterruptedException JavaDoc interruptedexception)
115             {
116                 return;
117             }
118         }
119     }
120
121     public Connection getConnection()
122     {
123         Connection connection = null;
124         if(available)
125         {
126             boolean flag = false;
127             for(int i = 1; i <= 10; i++)
128             {
129                 try
130                 {
131                     int j = 0;
132                     int k = connLast + 1;
133                     if(k >= currConnections)
134                         k = 0;
135                     do
136                         synchronized(connStatus)
137                         {
138                             if(connStatus[k] < 1 && !connPool[k].isClosed())
139                             {
140                                 connection = connPool[k];
141                                 connStatus[k] = 1;
142                                 connLockTime[k] = System.currentTimeMillis();
143                                 connLast = k;
144                                 flag = true;
145                                 break;
146                             }
147                             j++;
148                             if(++k >= currConnections)
149                                 k = 0;
150                         }
151                     while(!flag && j < currConnections);
152                 }
153                 catch(SQLException sqlexception) { }
154                 if(flag)
155                     break;
156                 synchronized(this)
157                 {
158                     if(currConnections < maxConns)
159                         try
160                         {
161                             createConn(currConnections);
162                             currConnections++;
163                         }
164                         catch(SQLException sqlexception1)
165                         {
166                             log.println("Unable to create new connection: " + sqlexception1);
167                         }
168                 }
169                 try
170                 {
171                     Thread.sleep(2000L);
172                 }
173                 catch(InterruptedException JavaDoc interruptedexception) { }
174                 log.println("-----> Connections Exhausted! Will wait and try again in loop " + String.valueOf(i));
175             }
176
177         } else
178         {
179             log.println("Unsuccessful getConnection() request during destroy()");
180         }
181         return connection;
182     }
183
184     public int idOfConnection(Connection connection)
185     {
186         String JavaDoc s;
187         try
188         {
189             s = connection.toString();
190         }
191         catch(NullPointerException JavaDoc nullpointerexception)
192         {
193             s = "none";
194         }
195         int i = -1;
196         for(int j = 0; j < currConnections; j++)
197         {
198             if(!connID[j].equals(s))
199                 continue;
200             i = j;
201             break;
202         }
203
204         return i;
205     }
206
207     public String JavaDoc freeConnection(Connection connection)
208     {
209         String JavaDoc s = "";
210         int i = idOfConnection(connection);
211         if(i >= 0)
212         {
213             connStatus[i] = 0;
214             s = "freed " + connection.toString();
215         } else
216         {
217             log.println("----> Could not free connection!!!");
218         }
219         return s;
220     }
221
222     public long getAge(Connection connection)
223     {
224         int i = idOfConnection(connection);
225         return System.currentTimeMillis() - connLockTime[i];
226     }
227
228     private void createConn(int i)
229         throws SQLException
230     {
231         Date JavaDoc date = new Date JavaDoc();
232         try
233         {
234             Class.forName(dbDriver);
235             connPool[i] = DriverManager.getConnection(dbServer, dbLogin, dbPassword);
236             connStatus[i] = 0;
237             connID[i] = connPool[i].toString();
238             connLockTime[i] = 0L;
239             connCreateDate[i] = date.getTime();
240         }
241         catch(ClassNotFoundException JavaDoc classnotfoundexception)
242         {
243             log.println(date.toString() + " Database driver not found ");
244         }
245         log.println(date.toString() + " Opening connection " + String.valueOf(i) + " " + connPool[i].toString() + ":");
246     }
247
248     public void destroy(int i)
249         throws SQLException
250     {
251         available = false;
252         runner.interrupt();
253         try
254         {
255             runner.join(i);
256         }
257         catch(InterruptedException JavaDoc interruptedexception) { }
258         int j;
259         for(long l = System.currentTimeMillis(); (j = getUseCount()) > 0 && System.currentTimeMillis() - l <= (long)i;)
260             try
261             {
262                 Thread.sleep(500L);
263             }
264             catch(InterruptedException JavaDoc interruptedexception1) { }
265
266         for(int k = 0; k < currConnections; k++)
267             try
268             {
269                 connPool[k].close();
270             }
271             catch(SQLException sqlexception)
272             {
273                 log.println("Cannot close connections on Destroy");
274             }
275
276         if(j > 0)
277         {
278             String JavaDoc s = "Unsafe shutdown: Had to close " + j + " active DB connections after " + i + "ms";
279             log.println(s);
280             log.close();
281             throw new SQLException(s);
282         } else
283         {
284             log.close();
285             return;
286         }
287     }
288
289     public void destroy()
290     {
291         try
292         {
293             destroy(10000);
294         }
295         catch(SQLException sqlexception) { }
296     }
297
298     public int getUseCount()
299     {
300         int i = 0;
301         synchronized(connStatus)
302         {
303             for(int j = 0; j < currConnections; j++)
304                 if(connStatus[j] > 0)
305                     i++;
306
307         }
308         return i;
309     }
310
311     public int getSize()
312     {
313         return currConnections;
314     }
315
316     public DbConnectionBroker(String JavaDoc s, String JavaDoc s1, String JavaDoc s2, String JavaDoc s3, int i, int j, String JavaDoc s4,
317             double d)
318         throws IOException
319     {
320         available = true;
321         connPool = new Connection[j];
322         connStatus = new int[j];
323         connLockTime = new long[j];
324         connCreateDate = new long[j];
325         connID = new String JavaDoc[j];
326         currConnections = i;
327         maxConns = j;
328         dbDriver = s;
329         dbServer = s1;
330         dbLogin = s2;
331         dbPassword = s3;
332         logFileString = s4;
333         maxConnMSec = (int)(d * 86400000D);
334         if(maxConnMSec < 30000)
335             maxConnMSec = 30000;
336         try
337         {
338             log = new PrintWriter(new FileOutputStream(s4), true);
339         }
340         catch(IOException ioexception)
341         {
342             try
343             {
344                 log = new PrintWriter(new FileOutputStream("DCB_" + System.currentTimeMillis() + ".log"), true);
345             }
346             catch(IOException ioexception1)
347             {
348                 throw new IOException("Can't open any log file");
349             }
350         }
351         SimpleDateFormat JavaDoc simpledateformat = new SimpleDateFormat JavaDoc("yyyy.MM.dd G 'at' hh:mm:ss a zzz");
352         Date JavaDoc date = new Date JavaDoc();
353         pid = simpledateformat.format(date);
354         BufferedWriter bufferedwriter = new BufferedWriter(new FileWriter(s4 + "pid"));
355         bufferedwriter.write(pid);
356         bufferedwriter.close();
357         log.println("Starting DbConnectionBroker Version 1.0.11:");
358         log.println("dbDriver = " + s);
359         log.println("dbServer = " + s1);
360         log.println("dbLogin = " + s2);
361         log.println("log file = " + s4);
362         log.println("minconnections = " + i);
363         log.println("maxconnections = " + j);
364         log.println("Total refresh interval = " + d + " days");
365         log.println("-----------------------------------------");
366         boolean flag = false;
367         byte byte0 = 20;
368         try
369         {
370             for(int k = 1; k < byte0;)
371                 try
372                 {
373                     for(int l = 0; l < currConnections; l++)
374                         createConn(l);
375
376                     flag = true;
377                     break;
378                 }
379                 catch(SQLException sqlexception)
380                 {
381                     log.println("--->Attempt (" + String.valueOf(k) + " of " + String.valueOf(byte0) + ") failed to create new connections set at startup: ");
382                     log.println(" " + sqlexception);
383                     log.println(" Will try again in 15 seconds...");
384                     try
385                     {
386                         Thread.sleep(15000L);
387                     }
388                     catch(InterruptedException JavaDoc interruptedexception) { }
389                     k++;
390                 }
391
392             if(!flag)
393             {
394                 log.println("\r\nAll attempts at connecting to Database exhausted");
395                 throw new IOException();
396             }
397         }
398         catch(Exception JavaDoc exception)
399         {
400             throw new IOException();
401         }
402         runner = new Thread JavaDoc(this);
403         runner.start();
404     }
405
406     private Thread JavaDoc runner;
407     private Connection connPool[];
408     private int connStatus[];
409     private long connLockTime[];
410     private long connCreateDate[];
411     private String JavaDoc connID[];
412     private String JavaDoc dbDriver;
413     private String JavaDoc dbServer;
414     private String JavaDoc dbLogin;
415     private String JavaDoc dbPassword;
416     private String JavaDoc logFileString;
417     private int currConnections;
418     private int connLast;
419     private int minConns;
420     private int maxConns;
421     private int maxConnMSec;
422     private boolean available;
423     private PrintWriter log;
424     private SQLWarning currSQLWarning;
425     private String JavaDoc pid;
426 }
427
Popular Tags