Debian Codegraph @

java-sdk/ietfldap/org/ietf/ldap/LDAPMessageQueueImpl.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) 2001
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;
39
40 import java.io.Serializable;
41 import java.util.ArrayList;
42
43 /**
44 * A queue of response messsages from the server. Multiple requests
45 * can be multiplexed on the same queue. For synchronous LDAPConnection
46 * requests, there will be only one request per queue. For asynchronous
47 * LDAPConnection requests, the user can add multiple request to the
48 * same queue.
49 *
50 * Used as a delegate by LDAResponseListener and LDAPSearchListener
51 *
52 */
53 class LDAPMessageQueueImpl implements Serializable, LDAPMessageQueue {
54
55 static final long serialVersionUID = -7163312406176592277L;
56
57 /**
58 * Request entry encapsulates request parameters
59 */
60 private static class RequestEntry {
61 int id;
62 LDAPConnection connection;
63 LDAPConnThread connThread;
64 long timeToComplete;
65
66 RequestEntry( int id, LDAPConnection connection,
67 LDAPConnThread connThread, int timeLimit ) {
68 this.id = id;
69 this.connection = connection;
70 this.connThread = connThread;
71 this.timeToComplete = (timeLimit == 0) ?
72 Long.MAX_VALUE : (System.currentTimeMillis() + timeLimit);
73 }
74 }
75
76 /**
77 * Internal variables
78 */
79 protected ArrayList<LDAPMessage> _messageQueue = new ArrayList<>(1);
80 private ArrayList<RequestEntry> _requestList = new ArrayList<>(1);
81 private LDAPException _exception; /* For network errors */
82 private boolean _asynchOp;
83
84 // A flag to indicate if there are time constrained requests
85 private boolean _timeConstrained;
86
87 /**
88 * Constructor
89 *
90 * @param asynchOp <CODE>true</CODE> if the object is used
91 * for asynchronous LDAP operations
92 * @see org.ietf.ldap.LDAPAsynchronousConnection
93 */
94 LDAPMessageQueueImpl( boolean asynchOp ) {
95 _asynchOp = asynchOp;
96 }
97
98 /**
99 * Returns the count of queued messages
100 *
101 * @return message count
102 */
103 public int getMessageCount() {
104 return _messageQueue.size();
105 }
106
107 /**
108 * Returns a list of message IDs for all outstanding requests
109 *
110 * @return message ID array
111 */
112 synchronized public int[] getMessageIDs() {
113 int[] ids = new int[_requestList.size()];
114 for ( int i = 0; i < ids.length; i++ ) {
115 RequestEntry entry = _requestList.get(i);
116 ids[i] = entry.id;
117 }
118 return ids;
119 }
120
121 /**
122 * Blocks until a message is available or until all operations
123 * associated with the object have completed or been canceled
124 *
125 * @return LDAP message or null if there are no more outstanding requests
126 * @exception LDAPException Network error exception
127 * @exception LDAPInterruptedException The invoking thread was interrupted
128 */
129 public synchronized LDAPMessage getResponse() throws LDAPException {
130
131 while( true ) {
132 if ( !waitForSomething() ) {
133 return null; // No outstanding requests
134 }
135
136 // Dequeue the first entry
137 LDAPMessage msg = _messageQueue.get( 0 );
138 _messageQueue.remove( 0 );
139
140 // Has the operation completed?
141 if ( msg instanceof LDAPResponse ) {
142 removeRequest( msg.getMessageID() );
143 }
144 return msg;
145 }
146 }
147
148 /**
149 * Blocks until a message is available for a particular message ID, or
150 * until all operations associated with the message ID have completed or
151 * been canceled, and returns the response. If there is no outstanding
152 * operation for the message ID (or if it is zero or a negative number),
153 * IllegalArgumentException is thrown.
154 *
155 * @param msgid A particular message to query for responses available
156 * @return a response for an LDAP operation or null if there are no
157 * more outstanding requests.
158 * @exception LDAPException Network error exception
159 * @exception LDAPInterruptedException The invoking thread was interrupted
160 */
161
162 public synchronized LDAPMessage getResponse( int msgid )
163 throws LDAPException {
164
165 if ( !isValidMessageID( msgid ) ) {
166 throw new IllegalArgumentException( "Invalid msg ID: " + msgid );
167 }
168
169 LDAPMessage msg = null;
170 while( ( _requestList.size() != 0 ) &&
171 ( _exception == null ) &&
172 ( (msg = getMessageForID( msgid, true )) == null ) ) {
173 waitForMessage();
174 }
175
176 // Network exception occurred?
177 if ( _exception != null ) {
178 LDAPException ex = _exception;
179 _exception = null;
180 throw ex;
181 }
182
183 // Are there any outstanding requests left?
184 if ( _requestList.size() == 0 ) {
185 return null; // No outstanding requests
186 }
187
188 // Has the operation completed?
189 if ( msg instanceof LDAPResponse ) {
190 removeRequest( msg.getMessageID() );
191 }
192
193 return msg;
194 }
195
196 /**
197 * Checks if a response message has been received
198 *
199 * @return true or false
200 */
201 public boolean isResponseReceived() {
202 return ( _messageQueue.size() != 0 );
203 }
204
205 /**
206 * Reports true if a response has been received from the server for a
207 * particular message ID. If there is no outstanding operation for the
208 * message ID (or if it is zero or a negative number),
209 * IllegalArgumentException is thrown.
210 *
211 * @param msgid A particular message to query for responses available
212 * @return a flag indicating whether the response message queue is empty
213 */
214 public boolean isResponseReceived( int msgid ) {
215 if ( !isValidMessageID( msgid ) ) {
216 throw new IllegalArgumentException( "Invalid msg ID: " + msgid );
217 }
218
219 return ( getMessageForID( msgid, false ) != null );
220 }
221
222 /**
223 * Merge two message queues.
224 * Move/append the content from another message queue to this one.
225 *
226 * To be used for synchronization of asynchronous LDAP operations where
227 * requests are sent by one thread but processed by another one
228 *
229 * A client may be implemented in such a way that one thread makes LDAP
230 * requests and calls l.getMessageIDs(), while another thread is
231 * responsible for
232 * processing of responses (call l.getResponse()). Both threads are using
233 * the same listener objects. In such a case, a race
234 * condition may occur, where a LDAP response message is retrieved and
235 * the request terminated (request ID removed) before the first thread
236 * has a chance to execute l.getMessageIDs().
237 * The proper way to handle this scenario is to create a separate listener
238 * for each new request, and after l.getMessageIDs() has been invoked,
239 * merge the
240 * new request with the existing one.
241 * @param mq2 message queue to merge with this one
242 */
243 public void merge( LDAPMessageQueue mq2 ) {
244
245 // Yield just in case the LDAPConnThread is in the process of
246 // dispatching a message
247 Thread.yield();
248
249 synchronized( this ) {
250 LDAPMessageQueueImpl mq = (LDAPMessageQueueImpl)mq2;
251 synchronized( mq ) {
252 ArrayList<LDAPMessage> queue2 = mq.getAllMessages();
253 for( int i = 0; i < queue2.size(); i++ ) {
254 _messageQueue.add( queue2.get( i ) );
255 }
256 if ( mq.getException() != null ) {
257 _exception = mq.getException();
258 }
259 ArrayList<RequestEntry> list2 = mq.getAllRequests();
260 for( int i = 0; i < list2.size(); i++ ) {
261 RequestEntry entry = list2.get( i );
262 _requestList.add( entry );
263 // Notify LDAPConnThread to redirect mq2 designated
264 // responses to this mq
265 entry.connThread.changeQueue( entry.id, this );
266 }
267
268 mq.reset();
269 notifyAll(); // notify for mq2
270 }
271
272 notifyAll(); // notify this mq
273 }
274 }
275
276 /**
277 * Gets String representation of the object
278 *
279 * @return String representation of the object
280 */
281 synchronized public String toString() {
282 StringBuffer sb = new StringBuffer( "LDAPMessageQueueImpl:" );
283 sb.append(" requestIDs={");
284 for ( int i = 0; i < _requestList.size(); i++ ) {
285 if ( i > 0 ) {
286 sb.append( "," );
287 }
288 sb.append( _requestList.get(i).id );
289 }
290 sb.append( "} messageCount=" + _messageQueue.size() );
291
292 return sb.toString();
293 }
294
295 /**
296 * Retrieves the next response for a particular message ID, or null
297 * if there is none
298 *
299 * @param msgid A particular message to query for responses available
300 * @param remove <code>true</code> if the retrieved message is to be
301 * removed from the queue
302 * @return a flag indicating whether the response message queue is empty
303 */
304 synchronized LDAPMessage getMessageForID( int msgid, boolean remove ) {
305 LDAPMessage msg = null;
306 for ( int i = 0; i < _messageQueue.size(); i++ ) {
307 msg = _messageQueue.get(i);
308 if ( msg.getMessageID() == msgid ) {
309 if ( remove ) {
310 _messageQueue.remove( i );
311 }
312 break;
313 }
314 }
315 return msg;
316 }
317
318 /**
319 * Reports if the listener is used for asynchronous LDAP
320 * operations
321 *
322 * @return asynchronous operation flag.
323 * @see org.ietf.ldap.LDAPAsynchronousConnection
324 */
325 boolean isAsynchOp() {
326 return _asynchOp;
327 }
328
329 /**
330 * Waits for request to complete. This method blocks until a message of
331 * type LDAPResponse has been received. Used by synchronous search
332 * with batch size of zero (block until all results are received).
333 *
334 * @return LDAPResponse message or null if there are no more outstanding
335 * requests
336 * @exception LDAPException Network error exception
337 * @exception LDAPInterruptedException The invoking thread was interrupted
338 */
339 synchronized LDAPResponse completeRequest() throws LDAPException {
340 while ( true ) {
341 if ( !waitForSomething() ) {
342 return null; // No outstanding requests
343 }
344
345 // Search for an instance of LDAPResponse
346 for ( int i = _messageQueue.size()-1; i >= 0; i-- ) {
347 LDAPMessage msg = _messageQueue.get(i);
348 if ( msg instanceof LDAPResponse ) {
349
350 // Dequeue the entry and return
351 _messageQueue.remove( i );
352 return (LDAPResponse)msg;
353 }
354 }
355 // Not found, wait for the next message
356 }
357 }
358
359 /**
360 * Waits for any message. Processes interrupts and honors
361 * time limit if set for any request.
362 */
363 synchronized private void waitForMessage() throws LDAPException {
364 if ( !_timeConstrained ) {
365 try {
366 wait();
367 return;
368 } catch (InterruptedException e) {
369 throw new LDAPInterruptedException(
370 "Interrupted LDAP operation" );
371 }
372 }
373
374 /**
375 * Perform time constrained wait
376 */
377 long minTimeToComplete = Long.MAX_VALUE;
378 long now = System.currentTimeMillis();
379 for ( int i = 0; i < _requestList.size(); i++ ) {
380 RequestEntry entry = _requestList.get( i );
381
382 // time limit exceeded ?
383 if ( entry.timeToComplete <= now ) {
384 entry.connection.abandon( entry.id );
385 throw new LDAPException( "Time to complete operation exceeded",
386 LDAPException.LDAP_TIMEOUT );
387 }
388
389 if ( entry.timeToComplete < minTimeToComplete ) {
390 minTimeToComplete = entry.timeToComplete;
391 }
392 }
393
394 long timeLimit = ( minTimeToComplete == Long.MAX_VALUE ) ?
395 0 : ( minTimeToComplete - now );
396
397 try {
398 _timeConstrained = ( timeLimit != 0 );
399 wait( timeLimit );
400 } catch ( InterruptedException e ) {
401 throw new LDAPInterruptedException( "Interrupted LDAP operation" );
402 }
403 }
404
405 /**
406 * Waits for a message, for the request list to be empty, or for
407 * an exception
408 *
409 * @return <CODE>true</CODE> if the request list is not empty
410 * @exception LDAPException Network error
411 */
412 boolean waitForSomething() throws LDAPException {
413 while( (_requestList.size() != 0) &&
414 (_exception == null) &&
415 (_messageQueue.size() == 0) ) {
416 waitForMessage();
417 }
418
419 // Network exception occurred ?
420 if ( _exception != null ) {
421 LDAPException ex = _exception;
422 _exception = null;
423 throw ex;
424 }
425
426 // Are there any outstanding requests left
427 if ( _requestList.size() == 0 ) {
428 return false; // No outstanding requests
429 }
430
431 return true;
432 }
433
434
435 /**
436 * Retrieves all messages currently in the queue without blocking.
437 * The messages are removed from the queue.
438 *
439 * @return vector of messages
440 */
441 synchronized ArrayList<LDAPMessage> getAllMessages() {
442 ArrayList<LDAPMessage> result = _messageQueue;
443 _messageQueue = new ArrayList<>(1);
444 return result;
445 }
446
447 /**
448 * Retrieves all requests currently in the queue.
449 * The requests are removed from the queue.
450 *
451 * @return vector of requests
452 */
453 synchronized ArrayList<RequestEntry> getAllRequests() {
454 ArrayList<RequestEntry> result = _requestList;
455 _requestList = new ArrayList<>(1);
456 return result;
457 }
458
459 /**
460 * Queues the LDAP server's response. This causes anyone waiting
461 * in getResponse() to unblock.
462 *
463 * @param msg response message
464 */
465 synchronized void addMessage( LDAPMessage msg ) {
466 _messageQueue.add(msg);
467
468 // Mark conn as bound for asych bind operations
469 if ( isAsynchOp() &&
470 (msg.getType() == LDAPMessage.BIND_RESPONSE) ) {
471 if ( ((LDAPResponse)msg).getResultCode() == 0 ) {
472 getConnection( msg.getMessageID() ).markConnAsBound();
473 }
474 }
475
476 notifyAll();
477 }
478
479 /**
480 * Gets a possible exception from the queue
481 *
482 * @return a possibly null exception
483 */
484 LDAPException getException() {
485 return _exception;
486 }
487
488 /**
489 * Reports if the message ID is in the request list
490 *
491 * @param msgid The message ID to validate
492 * @return <CODE>true</CODE> if the message ID is in the request list
493 */
494 synchronized boolean isValidMessageID( int msgid ) {
495 return ( getRequestEntry( msgid ) != null );
496 }
497
498 /**
499 * Signals that a network exception occured while servicing the
500 * request. This exception will be throwm to any thread waiting
501 * in getResponse().
502 *
503 * @param connThread LDAPConnThread on which the exception occurred
504 * @param e exception
505 */
506 synchronized void setException( LDAPConnThread connThread,
507 LDAPException e ) {
508 _exception = e;
509 removeAllRequests( connThread );
510 notifyAll();
511 }
512
513 /**
514 * Remove all queued messages associated with the request ID.
515 * Called when an LDAP operation is abandoned.
516 *
517 * Not synchronized as it is private and can be called only by
518 * abandon() and removeAllRequests().
519 *
520 * @return count of removed messages
521 */
522 private int removeAllMessages( int id ) {
523 int removeCount = 0;
524 for ( int i = (_messageQueue.size()-1); i >= 0; i-- ) {
525 LDAPMessage msg = _messageQueue.get( i );
526 if ( msg.getMessageID() == id ) {
527 _messageQueue.remove( i );
528 removeCount++;
529 }
530 }
531 return removeCount;
532 }
533
534 /**
535 * Resets the state of this object so it can be recycled.
536 * Used by LDAPConnection synchronous operations.
537 *
538 * @see org.ietf.ldap.LDAPConnection#getResponseListener
539 * @see org.ietf.ldap.LDAPConnection#getSearchListener
540 */
541 void reset() {
542 _exception = null;
543 _messageQueue.clear();
544 _requestList.clear();
545 _timeConstrained = false;
546 }
547
548 /**
549 * Returns the connection associated with the specified request id
550 *
551 * @param id request id
552 * @return connection
553 */
554 synchronized LDAPConnection getConnection( int id ) {
555 RequestEntry entry = getRequestEntry( id );
556 if ( entry != null ) {
557 return entry.connection;
558 }
559 return null;
560 }
561
562 /**
563 * Returns the connection thread associated with the specified request id
564 *
565 * @param id request id
566 * @return connection thread
567 */
568 synchronized LDAPConnThread getConnThread( int id ) {
569 RequestEntry entry = getRequestEntry( id );
570 if ( entry != null ) {
571 return entry.connThread;
572 }
573 return null;
574 }
575
576 /**
577 * Returns the request entry associated with the specified request id
578 *
579 * @param id request id
580 * @return request entry or null
581 */
582 synchronized RequestEntry getRequestEntry( int id ) {
583 for ( int i = 0; i < _requestList.size(); i++ ) {
584 RequestEntry entry = _requestList.get( i );
585 if ( id == entry.id ) {
586 return entry;
587 }
588 }
589 return null;
590
591 }
592
593 /**
594 * Returns message ID of the last request
595 *
596 * @return message ID
597 */
598 synchronized int getMessageID() {
599 int reqCnt = _requestList.size();
600 if ( reqCnt == 0 ) {
601 return -1;
602 } else {
603 RequestEntry entry = _requestList.get( reqCnt-1 );
604 return entry.id;
605 }
606 }
607
608 /**
609 * Registers an LDAP request
610 *
611 * @param id LDAP request message ID
612 * @param connection LDAP Connection for the message ID
613 * @param connThread a physical connection to the server
614 * @param timeLimit the maximum number of milliseconds to wait for
615 * the request to complete
616 */
617 synchronized void addRequest( int id, LDAPConnection connection,
618 LDAPConnThread connThread, int timeLimit ) {
619
620 _requestList.add( new RequestEntry( id, connection,
621 connThread, timeLimit ) );
622 if ( timeLimit != 0 ) {
623 _timeConstrained = true;
624 }
625 notifyAll();
626 }
627
628 /**
629 * Returns the number of outstanding requests.
630 * @return outstanding request count.
631 */
632 public int getRequestCount() {
633 return _requestList.size();
634 }
635
636 /**
637 * Removes the request with the specified ID.
638 * Called when a LDAP operation is abandoned (called from
639 * LDAPConnThread), or terminated (called by getResponse() when
640 * LDAPResponse message is received).
641 *
642 * @return flag indicating if the request was removed
643 */
644 synchronized boolean removeRequest( int id ) {
645 for ( int i = 0; i < _requestList.size(); i++ ) {
646 RequestEntry entry = _requestList.get( i );
647 if ( id == entry.id ) {
648 _requestList.remove( i );
649 removeAllMessages( id );
650 notifyAll();
651 return true;
652 }
653 }
654 return false;
655 }
656
657 /**
658 * Removes all requests associated with the specified connThread.
659 * Called when a connThread has a network error.
660 *
661 * @return number of removed requests
662 */
663 synchronized int removeAllRequests( LDAPConnThread connThread ) {
664 int removeCount = 0;
665 for ( int i = (_requestList.size()-1); i >= 0; i-- ) {
666 RequestEntry entry = _requestList.get( i );
667 if ( connThread == entry.connThread ) {
668 _requestList.remove( i );
669 removeCount++;
670
671 // remove all queued messages as well
672 removeAllMessages( entry.id );
673 }
674 }
675 notifyAll();
676 return removeCount;
677 }
678 }