Debian Codegraph @

java-sdk/ietfldap/org/ietf/ldap/util/ConnectionPool.java

raw symbols SCIP
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
2 *
3 * ***** BEGIN LICENSE BLOCK *****
4 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
5 *
6 * The contents of this file are subject to the Mozilla Public License Version
7 * 1.1 (the "License"); you may not use this file except in compliance with
8 * the License. You may obtain a copy of the License at
9 * http://www.mozilla.org/MPL/
10 *
11 * Software distributed under the License is distributed on an "AS IS" basis,
12 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
13 * for the specific language governing rights and limitations under the
14 * License.
15 *
16 * The Original Code is mozilla.org code.
17 *
18 * The Initial Developer of the Original Code is
19 * Netscape Communications Corporation.
20 * Portions created by the Initial Developer are Copyright (C) 1999
21 * the Initial Developer. All Rights Reserved.
22 *
23 * Contributor(s):
24 *
25 * Alternatively, the contents of this file may be used under the terms of
26 * either the GNU General Public License Version 2 or later (the "GPL"), or
27 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
28 * in which case the provisions of the GPL or the LGPL are applicable instead
29 * of those above. If you wish to allow use of your version of this file only
30 * under the terms of either the GPL or the LGPL, and not to allow others to
31 * use your version of this file under the terms of the MPL, indicate your
32 * decision by deleting the provisions above and replace them with the notice
33 * and other provisions required by the GPL or the LGPL. If you do not delete
34 * the provisions above, a recipient may use your version of this file under
35 * the terms of any one of the MPL, the GPL or the LGPL.
36 *
37 * ***** END LICENSE BLOCK ***** */
38 package org.ietf.ldap.util;
39
40 import java.util.Date;
41
42 import org.ietf.ldap.LDAPConnection;
43 import org.ietf.ldap.LDAPException;
44
45 /**
46 * Class to maintain a pool of individual connections to the
47 * same server. Specify the initial size and the max size
48 * when constructing a pool. Call getConnection() to obtain
49 * a connection from the pool and close() to return it. If
50 * the pool is fully extended and there are no free connections,
51 * getConnection() blocks until a connection has been returned
52 * to the pool.<BR>
53 * Call destroy() to release all connections.
54 *<BR><BR>Example:<BR>
55 *<PRE>
56 * ConnectionPool pool = null;
57 * try {
58 * pool = new ConnectionPool( 10, 30,
59 * "foo.acme.com",389,
60 * "uid=me, o=acme.com",
61 * "password" );
62 * } catch ( LDAPException e ) {
63 * System.err.println( "Unable to create connection pool" );
64 * System.exit( 1 );
65 * }
66 * while ( clientsKnocking ) {
67 * String filter = getSearchFilter();
68 * LDAPConnection ld = pool.getConnection();
69 * try {
70 * LDAPSearchResults res = ld.search( BASE, ld.SCOPE_SUB,
71 * filter, attrs,
72 * false );
73 * pool.close( ld );
74 * while( res.hasMoreElements() ) {
75 * ...
76 *</PRE>
77 */
78
79 /**
80 * Connection pool, typically used by a server to avoid creating
81 * a new connection for each client
82 *
83 * @version 1.0
84 **/
85 public class ConnectionPool {
86
87 /**
88 * Constructor for specifying all parameters
89 *
90 * @param min initial number of connections
91 * @param max maximum number of connections
92 * @param host hostname of LDAP server
93 * @param port port number of LDAP server
94 * @param authdn DN to authenticate as
95 * @param authpw password for authentication
96 * @exception LDAPException on failure to create connections
97 */
98 public ConnectionPool( int min, int max,
99 String host, int port,
100 String authdn, byte[] authpw )
101 throws LDAPException {
102 this( min, max, host, port, authdn, authpw, null );
103 }
104
105 /**
106 * Constructor for specifying all parameters, anonymous
107 * identity
108 *
109 * @param min initial number of connections
110 * @param max maximum number of connections
111 * @param host hostname of LDAP server
112 * @param port port number of LDAP server
113 * @exception LDAPException on failure to create connections
114 */
115 public ConnectionPool( int min, int max,
116 String host, int port )
117 throws LDAPException {
118 this( min, max, host, port, "", new byte[0]);
119 }
120
121 /**
122 * Constructor for using default parameters, anonymous identity
123 *
124 * @param host hostname of LDAP server
125 * @param port port number of LDAP server
126 * @exception LDAPException on failure to create connections
127 */
128 public ConnectionPool( String host, int port )
129 throws LDAPException {
130 // poolsize=10,max=20,host,port,
131 // noauth,nopswd
132 this( 10, 20, host, port, "", new byte[0] );
133 }
134
135 /*
136 * Constructor for using an existing connection to clone
137 * from
138 *
139 * @param min initial number of connections
140 * @param max maximum number of connections
141 * @param ldc connection to clone
142 * @param authpwd password
143 * @exception LDAPException on failure to create connections
144 */
145 public ConnectionPool( int min, int max,
146 LDAPConnection ldc, byte[] authpwd )
147 throws LDAPException {
148 this( min, max, ldc.getHost(), ldc.getPort(),
149 ldc.getAuthenticationDN(), authpwd,
150 ldc );
151 }
152
153 /*
154 * Constructor for using an existing connection to clone
155 * from
156 *
157 * @param min initial number of connections
158 * @param max maximum number of connections
159 * @param host hostname of LDAP server
160 * @param port port number of LDAP server
161 * @param authdn DN to authenticate as
162 * @param authpw password for authentication
163 * @param ldc connection to clone
164 * @exception LDAPException on failure to create connections
165 */
166 private ConnectionPool( int min, int max,
167 String host, int port,
168 String authdn, byte[] authpw,
169 LDAPConnection ldc )
170 throws LDAPException {
171 this.poolSize = min;
172 this.poolMax = max;
173 this.host = host;
174 this.port = port;
175 this.authdn = authdn;
176 this.authpw = authpw;
177 this.ldc = ldc;
178 this.debugMode = false;
179 createPool();
180 }
181
182 /**
183 * Destroy the whole pool - called during a shutdown
184 */
185 public void destroy() {
186 for ( int i = 0; i < pool.size(); i++ ) {
187 disconnect(
188 pool.elementAt(i) );
189 }
190 pool.removeAllElements();
191 }
192
193 /**
194 * Gets a connection from the pool
195 *
196 * If no connections are available, the pool will be
197 * extended if the number of connections is less than
198 * the maximum; if the pool cannot be extended, the method
199 * blocks until a free connection becomes available.
200 *
201 * @return an active connection.
202 */
203 public LDAPConnection getConnection() {
204 LDAPConnection con;
205
206 while( (con = getConnFromPool()) == null ) {
207 synchronized( pool ) {
208 try {
209 pool.wait();
210 } catch ( InterruptedException e ) {
211 }
212 }
213 }
214 return con;
215 }
216
217 /**
218 * Gets a connection from the pool within a time limit.
219 *
220 * If no connections are available, the pool will be
221 * extended if the number of connections is less than
222 * the maximum; if the pool cannot be extended, the method
223 * blocks until a free connection becomes available or the
224 * time limit is exceeded.
225 *
226 * @param timeout timeout in milliseconds
227 * @return an active connection or <CODE>null</CODE> if timed out.
228 */
229 public LDAPConnection getConnection(int timeout) {
230 LDAPConnection con;
231
232 while( (con = getConnFromPool()) == null ) {
233 long t1, t0 = System.currentTimeMillis();
234
235 if (timeout <= 0) {
236 return con;
237 }
238
239 synchronized( pool ) {
240 try {
241 pool.wait(timeout);
242 } catch ( InterruptedException e ) {
243 return null;
244 }
245 }
246
247 t1 = System.currentTimeMillis();
248 timeout -= (t1 - t0);
249 }
250 return con;
251 }
252
253 /**
254 * Gets a connection from the pool
255 *
256 * If no connections are available, the pool will be
257 * extended if the number of connections is less than
258 * the maximum; if the pool cannot be extended, the method
259 * returns null.
260 *
261 * @return an active connection or null.
262 */
263 protected synchronized LDAPConnection getConnFromPool() {
264 LDAPConnection con = null;
265 LDAPConnectionObject ldapconnobj = null;
266
267 int pSize = pool.size();
268
269 // Get an available connection
270 for ( int i = 0; i < pSize; i++ ) {
271
272 // Get the ConnectionObject from the pool
273 LDAPConnectionObject co =
274 pool.elementAt(i);
275
276 if ( co.isAvailable() ) { // Conn available?
277 ldapconnobj = co;
278 break;
279 }
280 }
281
282 if ( ldapconnobj == null ) {
283 // If there there were no conns in pool, can we grow
284 // the pool?
285 if ( (poolMax < 0) ||
286 ( (poolMax > 0) &&
287 (pSize < poolMax)) ) {
288
289 // Yes we can grow it
290 int i = addConnection();
291
292 // If a new connection was created, use it
293 if ( i >= 0 ) {
294 ldapconnobj =
295 pool.elementAt(i);
296 }
297 } else {
298 debug("All pool connections in use");
299 }
300 }
301
302 if ( ldapconnobj != null ) {
303 ldapconnobj.setInUse( true ); // Mark as in use
304 con = ldapconnobj.getLDAPConn();
305 }
306 return con;
307 }
308
309 /**
310 * This is our soft close - all we do is mark
311 * the connection as available for others to use.
312 *
313 * @param ld a connection to return to the pool
314 */
315 public synchronized void close( LDAPConnection ld ) {
316
317 int index = find( ld );
318 if ( index != -1 ) {
319 LDAPConnectionObject co =
320 pool.elementAt(index);
321 co.setInUse( false ); // Mark as available
322 synchronized( pool ) {
323 pool.notifyAll();
324 }
325 }
326 }
327
328 /**
329 * Debug method to print the contents of the pool
330 */
331 public void printPool(){
332 System.out.println("--ConnectionPool--");
333 for ( int i = 0; i < pool.size(); i++ ) {
334 LDAPConnectionObject co =
335 pool.elementAt(i);
336 System.out.println( "" + i + "=" + co );
337 }
338 }
339
340 private void disconnect(
341 LDAPConnectionObject ldapconnObject ) {
342 if ( ldapconnObject != null ) {
343 if (ldapconnObject.isAvailable()) {
344 LDAPConnection ld = ldapconnObject.getLDAPConn();
345 if ( (ld != null) && (ld.isConnected()) ) {
346 try {
347 ld.disconnect();
348 } catch (LDAPException e) {
349 debug("disconnect: "+e.toString());
350 }
351 }
352 ldapconnObject.setLDAPConn(null); // Clear conn
353 }
354 }
355 }
356
357 private void createPool() throws LDAPException {
358 // Called by the constructors
359 if ( poolSize <= 0 ) {
360 throw new LDAPException("ConnectionPoolSize invalid");
361 }
362 if ( poolMax < poolSize ) {
363 debug("ConnectionPoolMax is invalid, set to " +
364 poolSize);
365 poolMax = poolSize;
366 }
367
368 debug("****Initializing LDAP Pool****");
369 debug("LDAP host = "+host+" on port "+port);
370 debug("Number of connections="+poolSize);
371 debug("Maximum number of connections="+poolMax);
372 debug("******");
373
374 pool = new java.util.Vector<>(); // Create pool vector
375 setUpPool( poolSize ); // Initialize it
376 }
377
378 private int addConnection() {
379 int index = -1;
380
381 debug("adding a connection to pool...");
382 try {
383 int size = pool.size() + 1; // Add one connection
384 setUpPool( size );
385
386 if ( size == pool.size() ) {
387 // New size is size requested?
388 index = size - 1;
389 }
390 } catch (Exception ex) {
391 debug("Adding a connection: "+ex.toString());
392 }
393 return index;
394 }
395
396 private synchronized void setUpPool( int size )
397 throws LDAPException {
398 // Loop on creating connections
399 while( pool.size() < size ) {
400 LDAPConnectionObject co =
401 new LDAPConnectionObject();
402 // Make LDAP connection, using template if available
403 LDAPConnection newConn =
404 (ldc != null) ? (LDAPConnection)ldc.clone() :
405 new LDAPConnection();
406 co.setLDAPConn(newConn);
407 try {
408 if ( newConn.isConnected() ) {
409 // If using a template, then reconnect
410 // to create a separate physical connection
411 newConn.reconnect();
412 } else {
413 // Not using a template, so connect with
414 // simple authentication
415 newConn.connect( host, port );
416 newConn.bind( 3, authdn, authpw );
417 }
418 } catch ( LDAPException le ) {
419 debug("Creating pool:"+le.toString());
420 debug("aborting....");
421 throw le;
422 }
423 co.setInUse( false ); // Mark not in use
424 pool.addElement( co );
425 }
426 }
427
428 private int find( LDAPConnection con ) {
429 // Find the matching Connection in the pool
430 if ( con != null ) {
431 for ( int i = 0; i < pool.size(); i++ ) {
432 LDAPConnectionObject co =
433 pool.elementAt(i);
434 if ( co.getLDAPConn() == con ) {
435 return i;
436 }
437 }
438 }
439 return -1;
440 }
441
442 /**
443 * Sets the debug printout mode.
444 *
445 * @param mode debug mode to use
446 */
447 public synchronized void setDebug( boolean mode ) {
448 debugMode = mode;
449 }
450
451 /**
452 * Reports the debug printout mode.
453 *
454 * @return debug mode in use.
455 */
456 public boolean getDebug() {
457 return debugMode;
458 }
459
460 private void debug( String s ) {
461 if ( debugMode )
462 System.out.println("ConnectionPool ("+
463 new Date()+") : " + s);
464 }
465
466 private void debug(String s, boolean severe) {
467 if ( debugMode || severe ) {
468 System.out.println("ConnectionPool ("+
469 new Date()+") : " + s);
470 }
471 }
472
473 /**
474 * Wrapper for LDAPConnection object in pool
475 */
476 class LDAPConnectionObject{
477
478 /**
479 * Returns the associated LDAPConnection.
480 *
481 * @return the LDAPConnection.
482 *
483 */
484 LDAPConnection getLDAPConn() {
485 return this.ld;
486 }
487
488 /**
489 * Sets the associated LDAPConnection
490 *
491 * @param ld the LDAPConnection
492 *
493 */
494 void setLDAPConn( LDAPConnection ld ) {
495 this.ld = ld;
496 }
497
498 /**
499 * Marks a connection in use or available
500 *
501 * @param inUse <code>true</code> to mark in use, <code>false</code> if available
502 *
503 */
504 void setInUse( boolean inUse ) {
505 this.inUse = inUse;
506 }
507
508 /**
509 * Returns whether the connection is available
510 * for use by another user.
511 *
512 * @return <code>true</code> if available.
513 */
514 boolean isAvailable() {
515 return !inUse;
516 }
517
518 /**
519 * Debug method
520 *
521 * @return s user-friendly rendering of the object.
522 */
523 public String toString() {
524 return "LDAPConnection=" + ld + ",inUse=" + inUse;
525 }
526
527 private LDAPConnection ld; // LDAP Connection
528 private boolean inUse; // In use? (true = yes)
529 }
530
531 private int poolSize; // Min pool size
532 private int poolMax; // Max pool size
533 private String host; // LDAP host
534 private int port; // Port to connect at
535 private String authdn; // Identity of connections
536 private byte[] authpw; // Password for authdn
537 private LDAPConnection ldc = null; // Connection to clone
538 private java.util.Vector<LDAPConnectionObject> pool; // the actual pool
539 private boolean debugMode;
540 }