Debian Codegraph @

java-sdk/ietfldap/org/ietf/ldap/LDAPSearchResults.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.Comparator;
42 import java.util.Vector;
43
44 /**
45 * The results of an LDAP search operation, represented as an enumeration.
46 * Note that you can only iterate through this enumeration once: if you
47 * need to use these results more than once, make sure to save the
48 * results in a separate location.
49 * <P>
50 *
51 * You can also use the results of a search in progress to abandon that search
52 * operation.
53 * <P>
54 *
55 * @version 1.0
56 * @see org.ietf.ldap.LDAPConnection#search(java.lang.String, int, java.lang.String, java.lang.String[], boolean)
57 * @see org.ietf.ldap.LDAPConnection#abandon(org.ietf.ldap.LDAPSearchResults)
58 */
59 public class LDAPSearchResults implements Serializable {
60
61 static final long serialVersionUID = -501692208613904825L;
62 private Vector<Object> entries = null;
63 private LDAPSearchQueue resultSource;
64 private boolean searchComplete = false;
65 private LDAPConnection connectionToClose;
66 private LDAPConnection currConn;
67 private boolean persistentSearch = false;
68 private LDAPSearchConstraints currCons;
69 private String currBase;
70 private int currScope;
71 private String currFilter;
72 private String[] currAttrs;
73 private boolean currAttrsOnly;
74 private Vector<LDAPSearchResults> referralResults = new Vector<>();
75 private Vector<LDAPException> exceptions;
76 private int msgID = -1;
77
78 // only used for the persistent search
79 private boolean firstResult = false;
80
81 /**
82 * Constructs an enumeration of search results.
83 * Note that this does not actually generate the results;
84 * you need to call <CODE>LDAPConnection.search</CODE> to
85 * perform the search and get the results.
86 * @see org.ietf.ldap.LDAPConnection#search(java.lang.String, int, java.lang.String, java.lang.String[], boolean)
87 */
88 public LDAPSearchResults() {
89 entries = new Vector<Object>();
90 connectionToClose = null;
91 searchComplete = true;
92 currCons = new LDAPSearchConstraints();
93 }
94
95 LDAPSearchResults( LDAPConnection conn,
96 LDAPSearchConstraints cons,
97 String base,
98 int scope,
99 String filter,
100 String[] attrs,
101 boolean attrsOnly ) {
102 this();
103 currConn = conn;
104 currCons = cons;
105 currBase = base;
106 currScope = scope;
107 currFilter = filter;
108 currAttrs = attrs;
109 currAttrsOnly = attrsOnly;
110 }
111
112 /**
113 * Constructs an enumeration of search results. Used when returning results
114 * from a cache.
115 * @param v the vector containing LDAPEntries
116 * @see org.ietf.ldap.LDAPConnection#search(java.lang.String, int, java.lang.String, java.lang.String[], boolean)
117 */
118 LDAPSearchResults( Vector<Object> v ) {
119 this();
120 entries = (Vector<Object>)v.clone();
121
122 if ((entries != null) && (entries.size() >= 1)) {
123 // Each cache value is represented by a vector. The first element
124 // represents the size of all the LDAPEntries. This needs to be
125 // removed before we iterate through each LDAPEntry.
126 entries.removeElementAt(0);
127 }
128 }
129
130 LDAPSearchResults( Vector<Object> v,
131 LDAPConnection conn,
132 LDAPSearchConstraints cons,
133 String base,
134 int scope,
135 String filter,
136 String[] attrs,
137 boolean attrsOnly ) {
138 this( v );
139 currConn = conn;
140 currCons = cons;
141 currBase = base;
142 currScope = scope;
143 currFilter = filter;
144 currAttrs = attrs;
145 currAttrsOnly = attrsOnly;
146 }
147
148 /**
149 * Returns a count of queued search results immediately available for
150 * processing.
151 * A search result is either a search entry or an exception. If the
152 * search is asynchronous (batch size not 0), this reports the number
153 * of results received so far.
154 * @return count of search results immediatly available for processing
155 */
156 public int getCount() {
157
158 while (resultSource != null && resultSource.getMessageCount() > 0) {
159 fetchResult();
160 }
161
162 int count = entries.size();
163
164 for ( int i = 0; i < referralResults.size(); i++ ) {
165 LDAPSearchResults res = referralResults.elementAt(i);
166 count += res.getCount();
167 }
168
169 if ( exceptions != null ) {
170 count += exceptions.size();
171 }
172
173 return count;
174 }
175
176 /**
177 * Returns the controls returned with this search result. If any control
178 * is registered with <CODE>LDAPControl</CODE>, an attempt is made to
179 * instantiate the control. If the instantiation fails, the control is
180 * returned as a basic <CODE>LDAPControl</CODE>.
181 * @return an array of type <CODE>LDAPControl</CODE>.
182 * @see org.ietf.ldap.LDAPControl#register
183 */
184 public LDAPControl[] getResponseControls() {
185 return currConn.getResponseControls(msgID);
186 }
187
188 /**
189 * Returns <CODE>true</CODE> if there are more search results
190 * to be returned. You can use this method in conjunction with the
191 * <CODE>next</CODE> or <CODE>next</CODE> methods to iterate
192 * through each entry in the results. For example:
193 * <PRE>
194 * LDAPSearchResults res = ld.search( MY_SEARCHBASE,
195 * LDAPConnection.SCOPE_BASE, MY_FILTER,
196 * null, false );
197 * while ( res.hasMore() ) {
198 * LDAPEntry findEntry = res.next();
199 * ...
200 * }
201 * </PRE>
202 * @return <CODE>true</CODE> if there are more search results.
203 * @see org.ietf.ldap.LDAPSearchResults#next()
204 */
205 public boolean hasMore() {
206
207 while ((entries.size() == 0) && (!searchComplete)) {
208 fetchResult();
209 }
210
211 if ((entries.size() == 0) &&
212 ((exceptions == null) || (exceptions.size() == 0))) {
213 while (referralResults.size() > 0) {
214 LDAPSearchResults res =
215 referralResults.elementAt(0);
216 if (res.hasMore())
217 return true;
218 else
219 referralResults.removeElementAt(0);
220 }
221 }
222
223 return ((entries.size() > 0) ||
224 ((exceptions != null) && (exceptions.size() > 0)));
225 }
226
227 /**
228 * Returns the next LDAP entry from the search results
229 * and throws an exception if the next result is a referral, or
230 * if a sizelimit or timelimit error occurred.
231 * <P>
232 *
233 * You can use this method in conjunction with the
234 * <CODE>hasMore</CODE> method to iterate through
235 * each entry in the search results. For example:
236 * <PRE>
237 * LDAPSearchResults res = ld.search( MY_SEARCHBASE,
238 * LDAPConnection.SCOPE_BASE, MY_FILTER,
239 * null, false );
240 * while ( res.has() ) {
241 * try {
242 * LDAPEntry findEntry = res.next();
243 * } catch ( LDAPReferralException e ) {
244 * String refUrls[] = e.getReferrals();
245 * for ( int i = 0; i < refUrls.length; i++ ) {
246 * // Your code for handling referrals
247 * }
248 * continue;
249 * } catch ( LDAPException e ) {
250 * // Your code for handling errors on limits exceeded
251 * continue;
252 * }
253 * ...
254 * }
255 * </PRE>
256 * @return the next LDAP entry in the search results.
257 * @exception LDAPReferralException A referral (thrown
258 * if the next result is a referral), or LDAPException
259 * if a limit on the number of entries or the time was
260 * exceeded.
261 * @see org.ietf.ldap.LDAPSearchResults#hasMore()
262 */
263 public LDAPEntry next() throws LDAPException {
264 Object o = nextElement();
265 if ((o instanceof LDAPReferralException) ||
266 (o instanceof LDAPException)) {
267 throw (LDAPException)o;
268 }
269 if (o instanceof LDAPEntry) {
270 return (LDAPEntry)o;
271 }
272 return null;
273 }
274
275 /**
276 * Sorts the search results.
277 * <P>
278 *
279 * The comparator determines the sort order used. For example, if the
280 * comparator uses the <CODE>uid</CODE>
281 * attribute for comparison, the search results are sorted according to
282 * <CODE>uid</CODE>.
283 * <P>
284 *
285 * The following section of code sorts results in ascending order,
286 * first by surname and then by common name.
287 *
288 * <PRE>
289 * String[] sortAttrs = {"sn", "cn"};
290 * boolean[] ascending = {true, true};
291 *
292 * LDAPConnection ld = new LDAPConnection();
293 * ld.connect( ... );
294 * LDAPSearchResults res = ld.search( ... );
295 * res.sort( new LDAPCompareAttrNames(sortAttrs, ascending) );
296 * </PRE>
297 * NOTE: If the search results arrive asynchronously, the <CODE>sort</CODE>
298 * method blocks until all the results are returned.
299 * <P>
300 *
301 * If some of the elements of the Enumeration have already been fetched,
302 * the cursor is reset to the (new) first element.
303 * <P>
304 *
305 * @param compare comparator used to determine the sort order of the results
306 * @see LDAPCompareAttrNames
307 */
308 public synchronized void sort(Comparator<LDAPEntry> compare) {
309
310 // if automatic referral, then add to the entries, otherwise, dont do it
311 // since the elements in referralResults are LDAPReferralException.
312 if (currCons.getReferralFollowing()) {
313 while (referralResults.size() > 0) {
314 Object obj = null;
315 if ((obj=nextReferralElement()) != null) {
316 if (obj instanceof LDAPException) {
317 add((LDAPException)obj); // put it back
318 }
319 else {
320 entries.addElement(obj);
321 }
322 }
323 }
324 }
325
326 int numEntries = entries.size();
327 if (numEntries <= 0) {
328 return;
329 }
330
331 LDAPEntry[] toSort = new LDAPEntry[numEntries];
332 entries.copyInto (toSort);
333
334 if (toSort.length > 1) {
335 quicksort (toSort, compare, 0, numEntries-1);
336 }
337
338 entries.removeAllElements();
339 for (int i = 0; i < numEntries; i++) {
340 entries.addElement (toSort[i]);
341 }
342 }
343
344 /**
345 * Adds a search entry or referral
346 *
347 * @param msg LDAPSearchResult or LDAPsearchResultReference
348 */
349 void add( LDAPMessage msg ) {
350 if ( msg instanceof LDAPSearchResult ) {
351 entries.addElement( ((LDAPSearchResult)msg).getEntry());
352 } else if ( msg instanceof LDAPSearchResultReference ) {
353 /* convert to LDAPReferralException */
354 String urls[] = ((LDAPSearchResultReference)msg).getReferrals();
355 if ( urls != null ) {
356 if (exceptions == null) {
357 exceptions = new Vector<>();
358 }
359 exceptions.addElement(
360 new LDAPReferralException(null, 0, urls) );
361 }
362 }
363 }
364
365 /**
366 * Adds and exception
367 * @param e exception
368 */
369 void add( LDAPException e ) {
370 if ( exceptions == null ) {
371 exceptions = new Vector<>();
372 }
373 exceptions.addElement( e );
374 }
375
376 /**
377 * Prepares to return asynchronous results from a search
378 *
379 * @param l Listener which will provide results
380 */
381 void associate( LDAPSearchQueue l ) {
382 resultSource = l;
383 searchComplete = false;
384 }
385
386 void associatePersistentSearch( LDAPSearchQueue l) {
387 resultSource = l;
388 persistentSearch = true;
389 searchComplete = false;
390 firstResult = true;
391 }
392
393 void addReferralEntries( LDAPSearchResults res ) {
394 referralResults.addElement( res );
395 }
396
397 /**
398 * For asynchronous search, this mechanism allows the programmer to
399 * close a connection whenever the search completes.
400 * @param toClose connection to close when the search terminates
401 */
402 void closeOnCompletion( LDAPConnection toClose ) {
403 if ( searchComplete ) {
404 try {
405 toClose.disconnect();
406 } catch( LDAPException e ) {
407 }
408 } else {
409 connectionToClose = toClose;
410 }
411 }
412
413
414 /**
415 * Basic quicksort algorithm.
416 */
417 void quicksort ( LDAPEntry[] toSort, Comparator<LDAPEntry> compare,
418 int low, int high ) {
419 if (low >= high) {
420 return;
421 }
422
423 LDAPEntry pivot = toSort[low];
424 int slow = low-1, shigh = high+1;
425
426 while (true) {
427 do {
428 shigh--;
429 } while ( compare.compare(toSort[shigh], pivot) > 0 );
430 do {
431 slow++;
432 } while ( compare.compare(pivot, toSort[slow]) > 0 );
433
434 if (slow >= shigh) {
435 break;
436 }
437
438 LDAPEntry temp = toSort[slow];
439 toSort[slow] = toSort[shigh];
440 toSort[shigh] = temp;
441 }
442
443 quicksort (toSort, compare, low, shigh);
444 quicksort (toSort, compare, shigh+1, high);
445 }
446
447 /**
448 * Sets the message ID for this search request. msgID is used
449 * to retrieve response controls.
450 * @param msgID Message ID for this search request
451 */
452 void setMsgID( int msgID ) {
453 this.msgID = msgID;
454 }
455
456 /**
457 * Returns the next result from a search. You can use this method
458 * in conjunction with the <CODE>hasMore</CODE> method to
459 * iterate through all elements in the search results.
460 * <P>
461 *
462 * Make sure to cast the
463 * returned element as the correct type. For example:
464 * <PRE>
465 * LDAPSearchResults res = ld.search( MY_SEARCHBASE,
466 * LDAPConnection.SCOPE_BASE, MY_FILTER,
467 * null, false );
468 * while ( res.hasMore() ) {
469 * Object o = res.next();
470 * if ( o instanceof LDAPEntry ) {
471 * LDAPEntry findEntry = (LDAPEntry)o;
472 * ...
473 * } else if ( o instanceof LDAPReferralException ) {
474 * LDAPReferralException e = (LDAPReferralException)o;
475 * String refUrls[] = e.getReferrals();
476 * ...
477 * } else if ( o instanceof LDAPException ) {
478 * LDAPException e = (LDAPException)o;
479 * ...
480 * }
481 * }
482 * </PRE>
483 * @return the next element in the search results.
484 * @see org.ietf.ldap.LDAPSearchResults#hasMore()
485 */
486 Object nextElement() {
487 if ( entries.size() > 0 ) {
488 Object obj = entries.elementAt(0);
489 entries.removeElementAt(0);
490 return obj;
491 }
492
493 if (referralResults.size() > 0) {
494 return nextReferralElement();
495 }
496
497 if ((exceptions != null) && (exceptions.size() > 0)) {
498 LDAPException obj = exceptions.elementAt(0);
499 exceptions.removeElementAt(0);
500 return obj;
501 }
502
503 return null;
504 }
505
506 Object nextReferralElement() {
507 LDAPSearchResults res = referralResults.elementAt(0);
508 if ((!res.persistentSearch && res.hasMore()) ||
509 (res.persistentSearch)) {
510 Object obj = res.nextElement();
511 if (obj != null) {
512 return obj;
513 }
514
515 if ((obj == null) || (!res.hasMore())) {
516 referralResults.removeElementAt(0);
517 }
518 } else {
519 referralResults.removeElementAt(0);
520 }
521
522 return null;
523 }
524
525 /**
526 * Returns message ID.
527 * @return Message ID.
528 */
529 int getMessageID() {
530 if ( resultSource == null ) {
531 return -1;
532 }
533 return resultSource.getMessageID();
534 }
535
536 /**
537 * Fetchs the next result, for asynchronous searches.
538 */
539 private synchronized void fetchResult() {
540
541 /* Asynchronous case */
542 if ( resultSource != null ) {
543 synchronized( this ) {
544 if (searchComplete || firstResult) {
545 firstResult = false;
546 return;
547 }
548
549 LDAPMessage msg = null;
550 try {
551 msg = resultSource.getResponse();
552 } catch (LDAPException e) {
553 add(e);
554 currConn.releaseSearchListener(resultSource);
555 searchComplete = true;
556 return;
557 }
558
559
560 if (msg == null) { // Request abandoned
561 searchComplete = true;
562 currConn.releaseSearchListener(resultSource);
563 return;
564
565 } else if (msg instanceof LDAPResponse) {
566 try {
567 // check response and see if we need to do referral
568 // v2: referral stored in the JDAPResult
569 currConn.checkSearchMsg(this, msg, currCons,
570 currBase, currScope, currFilter,
571 currAttrs, currAttrsOnly);
572 } catch (LDAPException e) {
573 System.err.println("LDAPSearchResults.fetchResult: "+e);
574 } finally {
575 currConn.releaseSearchListener(resultSource);
576 }
577 searchComplete = true;
578 if (connectionToClose != null) {
579 try {
580 connectionToClose.disconnect ();
581 } catch (LDAPException e) {
582 }
583 connectionToClose = null;
584 }
585 return;
586 } else {
587 try {
588 currConn.checkSearchMsg(this, msg, currCons,
589 currBase, currScope, currFilter, currAttrs, currAttrsOnly);
590 } catch (LDAPException e) {
591 System.err.println("Exception: "+e);
592 }
593 }
594 }
595 }
596 }
597 }