Debian Codegraph @

java-sdk/ietfldap/org/ietf/ldap/LDAPConnection.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.BufferedOutputStream;
41 import java.io.FileOutputStream;
42 import java.io.IOException;
43 import java.io.InputStream;
44 import java.io.OutputStream;
45 import java.io.Serializable;
46 import java.util.Enumeration;
47 import java.util.Hashtable;
48 import java.util.Iterator;
49 import java.util.Map;
50 import java.util.Properties;
51 import java.util.StringTokenizer;
52 import java.util.Vector;
53
54 import javax.security.auth.callback.CallbackHandler;
55
56 import org.ietf.ldap.client.JDAPAVA;
57 import org.ietf.ldap.client.opers.JDAPAbandonRequest;
58 import org.ietf.ldap.client.opers.JDAPAddRequest;
59 import org.ietf.ldap.client.opers.JDAPBindRequest;
60 import org.ietf.ldap.client.opers.JDAPCompareRequest;
61 import org.ietf.ldap.client.opers.JDAPDeleteRequest;
62 import org.ietf.ldap.client.opers.JDAPExtendedRequest;
63 import org.ietf.ldap.client.opers.JDAPExtendedResponse;
64 import org.ietf.ldap.client.opers.JDAPModifyRDNRequest;
65 import org.ietf.ldap.client.opers.JDAPModifyRequest;
66 import org.ietf.ldap.client.opers.JDAPProtocolOp;
67 import org.ietf.ldap.client.opers.JDAPResult;
68 import org.ietf.ldap.client.opers.JDAPSearchRequest;
69 import org.ietf.ldap.client.opers.JDAPSearchResultReference;
70
71 /**
72 * Represents a connection to an LDAP server. <P>
73 *
74 * Use objects of this class to perform LDAP operations (such as
75 * search, modify, and add) on an LDAP server. <P>
76 *
77 * To perform an LDAP operation on a server, you need to follow
78 * these steps: <P>
79 *
80 * <OL>
81 * <LI>Create a new <CODE>LDAPConnection</CODE> object.
82 * <LI>Use the <CODE>connect</CODE> method to connect to the
83 * LDAP server.
84 * <LI>Use the <CODE>authenticate</CODE> method to authenticate
85 * to server.
86 * <LI>Perform the LDAP operation.
87 * <LI>Use the <CODE>disconnect</CODE> method to disconnect from
88 * the server when done.
89 * </OL>
90 * <P>
91 *
92 * All operations block until completion (with the exception of
93 * the search method in which the results may not all return at
94 * the same time).
95 * <P>
96 *
97 * This class also specifies a default set of constraints
98 * (such as the maximum length of time to allow for an operation before timing out)
99 * which apply to all operations. To get and set these constraints,
100 * use the <CODE>getOption</CODE> and <CODE>setOption</CODE> methods.
101 * To override these constraints for an individual operation,
102 * define a new set of constraints by creating a <CODE>LDAPConstraints</CODE>
103 * object and pass the object to the method for the operation. For search
104 * operations, additional constraints are defined in <CODE>LDAPSearchConstraints</CODE>
105 * (a subclass of <CODE>LDAPConstraints</CODE>). To override the default search
106 * constraints, create an <CODE>LDAPSearchConstraints</CODE> object and pass it
107 * to the <CODE>search</CODE> method.
108 * <P>
109 *
110 * If you set up your client to follow referrals automatically,
111 * an operation that results in a referral will create a new connection
112 * to the LDAP server identified in the referral. In order to have
113 * your client authenticate to that LDAP server automatically, you need
114 * to define a class that implements the <CODE>LDAPAuthHandler</CODE> interface.
115 * In your definition of the class, you need to define a
116 * <CODE>getAuthProvider</CODE> method that creates an <CODE>LDAPAuthProvider</CODE>
117 * object containing the distinguished name and password to use for reauthentication.
118 * <P>
119 *
120 * Most errors that occur raise the same exception (<CODE>LDAPException</CODE>).
121 * In order to determine the exact problem that occurred, you can retrieve the
122 * result code from this exception and compare its value against a set of defined
123 * result codes.
124 * <P>
125 *
126 * @version 1.0
127 * @see org.ietf.ldap.LDAPConstraints
128 * @see org.ietf.ldap.LDAPSearchConstraints
129 * @see org.ietf.ldap.LDAPAuthHandler
130 * @see org.ietf.ldap.LDAPAuthProvider
131 * @see org.ietf.ldap.LDAPException
132 */
133 public class LDAPConnection implements Cloneable, Serializable {
134
135 static final long serialVersionUID = -8698420087475771144L;
136
137 /**
138 * Version of the LDAP protocol used by default.
139 * <CODE>LDAP_VERSION</CODE> is 2, so your client will
140 * attempt to authenticate to LDAP servers as an LDAP v2 client.
141 * The following is an example of some code that prints the
142 * value of this variable:
143 * <P>
144 *
145 * <PRE>
146 * LDAPConnection ld = new LDAPConnection();
147 * System.out.println( "The default LDAP protocol version used is "
148 * ld.LDAP_VERSION );
149 * </PRE>
150 *
151 * If you want to authenticate as an LDAP v3 client,
152 * use the <A HREF="#bind(int, java.lang.String, byte[])"><CODE>bind(int version, String dn, byte[] passwd)</CODE></A> method.
153 * For example:
154 * <P>
155 *
156 * <PRE>
157 * ld.bind( 3, myDN, myPW );
158 * </PRE>
159 *
160 * @see org.ietf.ldap.LDAPConnection#bind(int, java.lang.String, byte[])
161 */
162 public final static int LDAP_VERSION = 2;
163 /**
164 * Name of the property specifying the version of the SDK. <P>
165 *
166 * To get the version number, pass this name to the
167 * <CODE>getProperty</CODE> method. The SDK version number
168 * is of the type <CODE>Float</CODE>. For example:<P>
169 * <PRE>
170 * ...
171 * Float sdkVersion = ( Float )myConn.getProperty( myConn.LDAP_PROPERTY_SDK );
172 * System.out.println( "SDK version: " + sdkVersion );
173 * ... </PRE>
174 * @see org.ietf.ldap.LDAPConnection#getProperty(java.lang.String)
175 */
176 public final static String LDAP_PROPERTY_SDK = "version.sdk";
177 /**
178 * Name of the property specifying the highest supported version of
179 * the LDAP protocol. <P>
180 *
181 * To get the version number, pass this name to the
182 * <CODE>getProperty</CODE> method. The LDAP protocol version number
183 * is of the type <CODE>Float</CODE>. For example:<P>
184 * <PRE>
185 * ...
186 * Float LDAPVersion = ( Float )myConn.getProperty( myConn.LDAP_PROPERTY_PROTOCOL );
187 * System.out.println( "Highest supported LDAP protocol version: " + LDAPVersion );
188 * ... </PRE>
189 * @see org.ietf.ldap.LDAPConnection#getProperty(java.lang.String)
190 */
191 public final static String LDAP_PROPERTY_PROTOCOL = "version.protocol";
192 /**
193 * Name of the property specifying the types of authentication allowed by this
194 * API (for example, anonymous authentication and simple authentication). <P>
195 *
196 * To get the supported types, pass this name to the
197 * <CODE>getProperty</CODE> method. The value of this property is
198 * of the type <CODE>String</CODE>. For example:<P>
199 * <PRE>
200 * ...
201 * String authTypes = ( String )myConn.getProperty( myConn.LDAP_PROPERTY_SECURITY );
202 * System.out.println( "Supported authentication types: " + authTypes );
203 * ... </PRE>
204 * @see org.ietf.ldap.LDAPConnection#getProperty(java.lang.String)
205 */
206 public final static String LDAP_PROPERTY_SECURITY = "version.security";
207
208 /**
209 * Name of the property to enable/disable LDAP message trace. <P>
210 *
211 * The property can be specified either as a system property
212 * (java -D command line option), or programmatically with the
213 * <CODE>setProperty</CODE> method.
214 * <P>
215 * When -D command line option is used, defining the property with
216 * no value will send the trace output to the standard error. If the
217 * value is defined, it is assumed to be the name of an output file.
218 * If the file name is prefixed with a '+' character, the file is
219 * opened in append mode.
220 * <P>
221 * When the property is set with the <CODE>setProperty</CODE> method,
222 * the property value must be either a String (represents a file name)
223 * an OutputStream or an instance of LDAPTraceWriter. To stop tracing,
224 * <CODE>null</CODE> should be passed as the property value.
225 *
226 * @see org.ietf.ldap.LDAPConnection#setProperty(java.lang.String, java.lang.Object)
227 */
228 public final static String TRACE_PROPERTY = "com.org.ietf.ldap.trace";
229
230 /**
231 * Specifies the serial connection setup policy when a list of hosts is
232 * passed to the <CODE>connect</CODE> method.
233 * @see org.ietf.ldap.LDAPConnection#setConnSetupDelay(int)
234 */
235 public final static int NODELAY_SERIAL = -1;
236 /**
237 * Specifies the parallel connection setup policy with no delay when a
238 * list of hosts is passed to the <CODE>connect</CODE> method.
239 * For each host in the list, a separate thread is created to attempt
240 * to connect to the host. All threads are started simultaneously.
241 * @see org.ietf.ldap.LDAPConnection#setConnSetupDelay(int)
242 */
243 public final static int NODELAY_PARALLEL = 0;
244
245 /**
246 * Constants
247 */
248 private final static String defaultFilter = "(objectClass=*)";
249 private final static LDAPConstraints readConstraints = new
250 LDAPSearchConstraints();
251
252 /**
253 * The default port number for LDAP servers. You can specify
254 * this identifier when calling the <CODE>LDAPConnection.connect</CODE>
255 * method to connect to an LDAP server.
256 * @see org.ietf.ldap.LDAPConnection#connect
257 */
258 public final static int DEFAULT_PORT = 389;
259
260 /**
261 * Option specifying how aliases are dereferenced.
262 * <P>
263 *
264 * This option can have one of the following values:
265 * <UL>
266 * <LI><A HREF="#DEREF_NEVER"><CODE>DEREF_NEVER</CODE></A>
267 * <LI><A HREF="#DEREF_FINDING"><CODE>DEREF_FINDING</CODE></A>
268 * <LI><A HREF="#DEREF_SEARCHING"><CODE>DEREF_SEARCHING</CODE></A>
269 * <LI><A HREF="#DEREF_ALWAYS"><CODE>DEREF_ALWAYS</CODE></A>
270 * </UL>
271 * <P>
272 *
273 * @see org.ietf.ldap.LDAPConnection#getOption
274 * @see org.ietf.ldap.LDAPConnection#setOption
275 */
276 public static final int DEREF = 2;
277
278 /**
279 * Option specifying the maximum number of search results to
280 * return.
281 * <P>
282 *
283 * @see org.ietf.ldap.LDAPConnection#getOption
284 * @see org.ietf.ldap.LDAPConnection#setOption
285 */
286 public static final int SIZELIMIT = 3;
287
288 /**
289 * Option specifying the maximum number of milliseconds to
290 * wait for an operation to complete.
291 * @see org.ietf.ldap.LDAPConnection#getOption
292 * @see org.ietf.ldap.LDAPConnection#setOption
293 */
294 public static final int TIMELIMIT = 4;
295
296 /**
297 * Option specifying the maximum number of milliseconds the
298 * server should spend returning search results before aborting
299 * the search.
300 * @see org.ietf.ldap.LDAPConnection#getOption
301 * @see org.ietf.ldap.LDAPConnection#setOption
302 */
303 public static final int SERVER_TIMELIMIT = 5;
304
305 /**
306 * Option specifying whether or not referrals to other LDAP
307 * servers are followed automatically.
308 * @see org.ietf.ldap.LDAPConnection#getOption
309 * @see org.ietf.ldap.LDAPConnection#setOption
310 * @see org.ietf.ldap.LDAPAuthHandler
311 * @see org.ietf.ldap.LDAPAuthProvider
312 */
313 public static final int REFERRALS = 8;
314
315 /**
316 * Option specifying the object containing the method for
317 * getting authentication information (the distinguished name
318 * and password) used during a referral. For example, when
319 * referred to another LDAP server, your client uses this object
320 * to obtain the DN and password. Your client authenticates to
321 * the LDAP server using this DN and password.
322 * @see org.ietf.ldap.LDAPConnection#getOption
323 * @see org.ietf.ldap.LDAPConnection#setOption
324 * @see org.ietf.ldap.LDAPAuthHandler
325 * @see org.ietf.ldap.LDAPAuthProvider
326 */
327 public static final int REFERRALS_REBIND_PROC = 9;
328
329 /**
330 * Option specifying the maximum number of referrals to follow
331 * in a sequence when requesting an LDAP operation.
332 * @see org.ietf.ldap.LDAPConnection#getOption
333 * @see org.ietf.ldap.LDAPConnection#setOption
334 */
335 public static final int REFERRALS_HOP_LIMIT = 10;
336
337 /**
338 * Option specifying the object containing the method for
339 * authenticating to the server.
340 * @see org.ietf.ldap.LDAPConnection#getOption
341 * @see org.ietf.ldap.LDAPConnection#setOption
342 * @see org.ietf.ldap.LDAPBindHandler
343 */
344 public static final int BIND = 13;
345
346 /**
347 * Option specifying the version of the LDAP protocol
348 * used by your client when interacting with the LDAP server.
349 * If no version is set, the default version is 2. If you
350 * are planning to use LDAP v3 features (such as controls
351 * or extended operations), you should set this version to 3
352 * or specify version 3 as an argument to the <CODE>authenticate</CODE>
353 * method of the <CODE>LDAPConnection</CODE> object.
354 * @see org.ietf.ldap.LDAPConnection#getOption
355 * @see org.ietf.ldap.LDAPConnection#setOption
356 * @see org.ietf.ldap.LDAPConnection#bind(int, java.lang.String, byte[])
357 */
358 public static final int PROTOCOL_VERSION = 17;
359
360 /**
361 * Option specifying the number of results to return at a time.
362 * @see org.ietf.ldap.LDAPConnection#getOption
363 * @see org.ietf.ldap.LDAPConnection#setOption
364 */
365 public static final int BATCHSIZE = 20;
366
367
368 /*
369 * Valid options for Scope
370 */
371
372 /**
373 * Specifies that the scope of a search includes
374 * only the base DN (distinguished name).
375 * @see org.ietf.ldap.LDAPConnection#search(java.lang.String, int, java.lang.String, java.lang.String[], boolean, org.ietf.ldap.LDAPSearchConstraints)
376 */
377 public static final int SCOPE_BASE = 0;
378
379 /**
380 * Specifies that the scope of a search includes
381 * only the entries one level below the base DN (distinguished name).
382 * @see org.ietf.ldap.LDAPConnection#search(java.lang.String, int, java.lang.String, java.lang.String[], boolean, org.ietf.ldap.LDAPSearchConstraints) */
383 public static final int SCOPE_ONE = 1;
384
385 /**
386 * Specifies that the scope of a search includes
387 * the base DN (distinguished name) and all entries at all levels
388 * beneath that base.
389 * @see org.ietf.ldap.LDAPConnection#search(java.lang.String, int, java.lang.String, java.lang.String[], boolean, org.ietf.ldap.LDAPSearchConstraints) */
390 public static final int SCOPE_SUB = 2;
391
392
393 /*
394 * Valid options for Dereference
395 */
396
397 /**
398 * Specifies that aliases are never dereferenced.
399 * @see org.ietf.ldap.LDAPConnection#getOption
400 * @see org.ietf.ldap.LDAPConnection#setOption
401 */
402 public static final int DEREF_NEVER = 0;
403
404 /**
405 * Specifies that aliases are dereferenced when searching the
406 * entries beneath the starting point of the search (but
407 * not when finding the starting entry).
408 * @see org.ietf.ldap.LDAPConnection#getOption
409 * @see org.ietf.ldap.LDAPConnection#setOption
410 */
411 public static final int DEREF_SEARCHING = 1;
412
413 /**
414 * Specifies that aliases are dereferenced when finding the
415 * starting point for the search (but not when searching
416 * under that starting entry).
417 * @see org.ietf.ldap.LDAPConnection#getOption
418 * @see org.ietf.ldap.LDAPConnection#setOption
419 */
420 public static final int DEREF_FINDING = 2;
421
422 /**
423 * Specifies that aliases are always dereferenced.
424 * @see org.ietf.ldap.LDAPConnection#getOption
425 * @see org.ietf.ldap.LDAPConnection#setOption
426 */
427 public static final int DEREF_ALWAYS = 3;
428
429 /**
430 * Option specifying server controls for LDAP operations. These
431 * controls are passed to the LDAP server. They may also be returned by
432 * the server.
433 * @see org.ietf.ldap.LDAPControl
434 * @see org.ietf.ldap.LDAPConnection#getOption
435 * @see org.ietf.ldap.LDAPConnection#setOption
436 */
437 public static final int SERVERCONTROLS = 12;
438
439 /**
440 * Attribute type that you can specify in the LDAPConnection
441 * search method if you don't want to retrieve any of the
442 * attribute types for entries found by the search.
443 * @see org.ietf.ldap.LDAPConnection#search
444 */
445 public static final String NO_ATTRS = "1.1";
446
447 /**
448 * Attribute type that you can specify in the LDAPConnection
449 * search method if you want to retrieve all attribute types.
450 * You can use this if you want to retrieve all attributes in
451 * addition to an operational attribute. For example:
452 * <P>
453 *
454 * <PRE>
455 * ...
456 * String [] MY_ATTRS = { LDAPConnection.ALL_USER_ATTRS, "modifiersName",
457 * "modifyTimestamp" };
458 * LDAPSearchResults res = ld.search( MY_SEARCHBASE,
459 * LDAPConnection.SCOPE_SUB, MY_FILTER, MY_ATTRS, false, cons );
460 * ...
461 * </PRE>
462 * @see org.ietf.ldap.LDAPConnection#search
463 */
464 public static final String ALL_USER_ATTRS = "*";
465
466 /**
467 * Internal variables
468 */
469 private LDAPSearchConstraints _defaultConstraints =
470 new LDAPSearchConstraints();
471
472 // A clone of constraints for the successful bind. Used by
473 // "smart failover" for the automatic rebind
474 private LDAPConstraints _rebindConstraints;
475
476 private Vector<LDAPResponseQueue> _responseListeners;
477 private Vector<LDAPSearchQueue> _searchListeners;
478 private boolean _bound;
479 private String _prevBoundDN;
480 private byte[] _prevBoundPasswd;
481 private String _boundDN;
482 private byte[] _boundPasswd;
483 private int _protocolVersion = LDAP_VERSION;
484 private LDAPConnSetupMgr _connMgr;
485 private int _connSetupDelay = -1;
486 private int _connectTimeout = 0;
487 private LDAPSocketFactory _factory;
488 /* _thread does all socket i/o for the object and any clones */
489 private transient LDAPConnThread _thread = null;
490 /* To manage received server controls on a per-thread basis,
491 we keep a table of active threads and a table of controls,
492 indexed by thread */
493 private Vector<LDAPConnThread> _attachedList = new Vector<>();
494 private Hashtable<LDAPConnThread, Vector<LDAPResponseControl>> _responseControlTable = new Hashtable<>();
495 private LDAPCache _cache = null;
496 static Hashtable<LDAPConnThread, Vector<LDAPConnection>> _threadConnTable = new Hashtable<>();
497
498 // This handles the case when the client lost the connection to the
499 // server. After the client reconnects with the server, the bound resets
500 // to false. If the client used to have anonymous bind, then this boolean
501 // will take care of the case whether the client should send anonymous bind
502 // request to the server.
503 private boolean _anonymousBound = false;
504
505 private LDAPSaslBind _saslBinder = null;
506 private CallbackHandler _saslCallbackHandler = null;
507 private Properties _securityProperties;
508 private Hashtable<String, Object> _properties = new Hashtable<>();
509 private LDAPConnection _referralConnection;
510 private String _authMethod = "none";
511
512 /**
513 * Properties
514 */
515 private final static Float SdkVersion = 4.14f;
516 private final static Float ProtocolVersion = 3.0f;
517 private final static String SecurityVersion = new String("none,simple,sasl");
518 private final static Float MajorVersion = 4.0f;
519 private final static Float MinorVersion = 0.14f;
520 private final static String DELIM = "#";
521 private final static String PersistSearchPackageName =
522 "org.ietf.ldap.controls.LDAPPersistSearchControl";
523 final static String EXTERNAL_MECHANISM = "external";
524 private final static String EXTERNAL_MECHANISM_PACKAGE =
525 "com.netscape.sasl";
526 final static String DEFAULT_SASL_PACKAGE =
527 "com.netscape.sasl";
528 final static String SCHEMA_BUG_PROPERTY =
529 "com.org.ietf.ldap.schema.quoting";
530 final static String SASL_PACKAGE_PROPERTY =
531 "com.org.ietf.ldap.saslpackage";
532
533 /**
534 * Constructs a new <CODE>LDAPConnection</CODE> object,
535 * which represents a connection to an LDAP server. <P>
536 *
537 * Calling the constructor does not actually establish
538 * the connection. To connect to the LDAP server, use the
539 * <CODE>connect</CODE> method.
540 *
541 * @see org.ietf.ldap.LDAPConnection#connect(java.lang.String, int)
542 * @see org.ietf.ldap.LDAPConnection#bind(int, java.lang.String, byte[])
543 */
544 public LDAPConnection() {
545 super();
546 _factory = null;
547
548 _properties.put(LDAP_PROPERTY_SDK, SdkVersion);
549 _properties.put(LDAP_PROPERTY_PROTOCOL, ProtocolVersion);
550 _properties.put(LDAP_PROPERTY_SECURITY, SecurityVersion);
551 _properties.put("version.major", MajorVersion);
552 _properties.put("version.minor", MinorVersion);
553 }
554
555 /**
556 * Constructs a new <CODE>LDAPConnection</CODE> object that
557 * will use the specified socket factory class to create
558 * socket connections. The socket factory class must implement
559 * the <CODE>LDAPSocketFactory</CODE> interface. <BR>
560 * (For example, the <CODE>LDAPSSLSocketFactory</CODE>
561 * class implements this interface.)
562 * <P>
563 *
564 * Note that calling the <CODE>LDAPConnection</CODE> constructor
565 * does not actually establish a connection to an LDAP server.
566 * To connect to an LDAP server, use the
567 * <CODE>connect</CODE> method. The socket connection will be
568 * constructed when this method is called.
569 * <P>
570 *
571 * @see org.ietf.ldap.LDAPSocketFactory
572 * @see org.ietf.ldap.LDAPSSLSocketFactory
573 * @see org.ietf.ldap.LDAPConnection#connect(java.lang.String, int)
574 * @see org.ietf.ldap.LDAPConnection#bind(int, java.lang.String, byte[])
575 * @see org.ietf.ldap.LDAPConnection#getSocketFactory
576 * @see org.ietf.ldap.LDAPConnection#setSocketFactory(org.ietf.ldap.LDAPSocketFactory)
577 */
578 public LDAPConnection( LDAPSocketFactory factory ) {
579 this();
580 _factory = factory;
581 }
582
583 /**
584 * Abandons a current search operation, notifying the server not
585 * to send additional search results.
586 *
587 * @param searchResults the search results returned when the search
588 * was started
589 * @exception LDAPException Failed to notify the LDAP server.
590 * @see org.ietf.ldap.LDAPConnection#search(java.lang.String, int, java.lang.String, java.lang.String[], boolean, org.ietf.ldap.LDAPSearchConstraints)
591 * @see org.ietf.ldap.LDAPSearchResults
592 */
593 public void abandon( LDAPSearchResults searchResults )
594 throws LDAPException {
595 abandon( searchResults, _defaultConstraints );
596 }
597
598 /**
599 * Abandons a current search operation, notifying the server not
600 * to send additional search results.
601 *
602 * @param searchResults the search results returned when the search
603 * was started
604 * @param cons preferences for the operation
605 * @exception LDAPException Failed to notify the LDAP server.
606 * @see org.ietf.ldap.LDAPConnection#search(java.lang.String, int, java.lang.String, java.lang.String[], boolean, org.ietf.ldap.LDAPSearchConstraints)
607 * @see org.ietf.ldap.LDAPSearchResults
608 */
609 public void abandon( LDAPSearchResults searchResults,
610 LDAPConstraints cons )
611 throws LDAPException {
612 if ( (!isConnected()) || (searchResults == null) ) {
613 return;
614 }
615
616 int id = searchResults.getMessageID();
617 if ( id != -1 ) {
618 abandon( id );
619 }
620 }
621
622 /**
623 * Cancels the ldap request with the specified id and discards
624 * any results already received.
625 *
626 * @param id an LDAP request id
627 * @exception LDAPException Failed to send request.
628 */
629 public void abandon( int id ) throws LDAPException {
630 abandon( id, _defaultConstraints );
631 }
632
633 /**
634 * Cancels the ldap request with the specified id and discards
635 * any results already received.
636 *
637 * @param id an LDAP request id
638 * @param cons preferences for the operation
639 * @exception LDAPException Failed to send request.
640 */
641 public void abandon( int id,
642 LDAPConstraints cons ) throws LDAPException {
643 if (!isConnected()) {
644 return;
645 }
646
647 for (int i=0; i<3; i++) {
648 try {
649 /* Tell listener thread to discard results */
650 _thread.abandon( id );
651
652 /* Tell server to stop sending results */
653 _thread.sendRequest(null, new JDAPAbandonRequest(id), null, _defaultConstraints);
654
655 /* No response is forthcoming */
656 break;
657 } catch (NullPointerException ne) {
658 // do nothing
659 }
660 }
661 if (_thread == null) {
662 throw new LDAPException("Failed to send abandon request to the server.",
663 LDAPException.OTHER);
664 }
665 }
666
667 /**
668 * Cancels all outstanding search requests associated with this
669 * LDAPSearchQueue object and discards any results already received.
670 *
671 * @param searchlistener a search listener returned from a search
672 * @exception LDAPException Failed to send request.
673 */
674 public void abandon( LDAPSearchQueue searchlistener )
675 throws LDAPException {
676 abandon( searchlistener, _defaultConstraints );
677 }
678
679 /**
680 * Cancels all outstanding search requests associated with this
681 * LDAPSearchQueue object and discards any results already received.
682 *
683 * @param searchlistener a search listener returned from a search
684 * @param cons preferences for the operation
685 * @exception LDAPException Failed to send request.
686 */
687 public void abandon( LDAPSearchQueue searchlistener,
688 LDAPConstraints cons )
689 throws LDAPException {
690 int[] ids = searchlistener.getMessageIDs();
691 for (int i=0; i < ids.length; i++) {
692 searchlistener.removeRequest(ids[i]);
693 abandon(ids[i]);
694 }
695 }
696
697 /**
698 * Adds an entry to the directory. <P>
699 *
700 * Before using this method, you need to create an
701 * <CODE>LDAPEntry</CODE> object and use it to specify the
702 * distinguished name and attributes of the new entry. Make sure
703 * to specify values for all required attributes in the
704 * entry. If all required attributes are not specified and the LDAP server
705 * checks the entry against the schema, an <CODE>LDAPException</CODE>
706 * may be thrown (where the LDAP result code is
707 * <CODE>OBJECT_CLASS_VIOLATION</CODE>).<P>
708 *
709 * For example, the following section of code creates an
710 * <CODE>LDAPEntry</CODE> object for a new entry and uses the object
711 * to add the new entry to the directory. Because the definition of
712 * the LDAP <CODE>inetOrgPerson</CODE> class specifies that the
713 * <CODE>cn</CODE>, <CODE>sn</CODE>, and <CODE>objectclass</CODE>
714 * attributes are required, these attributes are specified as part
715 * of the new entry. (<CODE>mail</CODE> is not required but is shown
716 * here as an example of specifying additional attributes.)
717 * <P>
718 *
719 * <PRE>
720 * ...
721 * String myDN = "cn=Barbara Jensen,ou=Product Development,o=Ace Industry,c=US";
722 *
723 * LDAPAttribute attr1 = new LDAPAttribute( "cn", "Barbara Jensen" );
724 * LDAPAttribute attr2 = new LDAPAttribute( "sn", "Jensen" );
725 * LDAPAttribute attr3 = new LDAPAttribute( "objectclass", "top" );
726 * LDAPAttribute attr4 = new LDAPAttribute( "objectclass", "person" );
727 * LDAPAttribute attr5 = new LDAPAttribute( "objectclass", "organizationalPerson" );
728 * LDAPAttribute attr6 = new LDAPAttribute( "objectclass", "inetOrgPerson" );
729 * LDAPAttribute attr7 = new LDAPAttribute( "mail", "[email protected]" );
730 *
731 * LDAPAttributeSet myAttrs = new LDAPAttributeSet();
732 * myAttrs.add( attr1 );
733 * myAttrs.add( attr2 );
734 * myAttrs.add( attr3 );
735 * myAttrs.add( attr4 );
736 * myAttrs.add( attr5 );
737 * myAttrs.add( attr6 );
738 * myAttrs.add( attr7 );
739 *
740 * LDAPEntry myEntry = new LDAPEntry( myDN, myAttrs );
741 *
742 * myConn.add( myEntry );
743 * ... </PRE>
744 *
745 * @param entry LDAPEntry object specifying the distinguished name and
746 * attributes of the new entry
747 * @exception LDAPException Failed to add the specified entry to the
748 * directory.
749 * @see org.ietf.ldap.LDAPEntry
750 */
751 public void add( LDAPEntry entry ) throws LDAPException {
752 add(entry, _defaultConstraints);
753 }
754
755 /**
756 * Adds an entry to the directory and allows you to specify preferences
757 * for this LDAP add operation by using an
758 * <CODE>LDAPConstraints</CODE> object. For
759 * example, you can specify whether or not to follow referrals.
760 * You can also apply LDAP v3 controls to the operation.
761 * <P>
762 *
763 * @param entry LDAPEntry object specifying the distinguished name and
764 * attributes of the new entry
765 * @param cons the set of preferences to apply to this operation
766 * @exception LDAPException Failed to add the specified entry to the
767 * directory.
768 * @see org.ietf.ldap.LDAPEntry
769 * @see org.ietf.ldap.LDAPConstraints
770 */
771 public void add( LDAPEntry entry, LDAPConstraints cons )
772 throws LDAPException {
773 internalBind (cons);
774
775 LDAPResponseQueue myListener = getResponseListener ();
776 LDAPAttributeSet attrs = entry.getAttributeSet ();
777 LDAPAttribute[] attrList = new LDAPAttribute[attrs.size()];
778 Iterator<LDAPAttribute> it = attrs.iterator();
779 for( int i = 0; i < attrs.size(); i++ ) {
780 attrList[i] = it.next();
781 }
782 int attrPosition = 0;
783 LDAPMessage response;
784 try {
785 sendRequest (new JDAPAddRequest (entry.getDN(), attrList),
786 myListener, cons);
787 response = myListener.getResponse();
788 checkMsg (response);
789 } catch (LDAPReferralException e) {
790 performReferrals(e, cons, JDAPProtocolOp.ADD_REQUEST,
791 null, 0, null, null, false, null, entry, null, null);
792 } finally {
793 releaseResponseListener (myListener);
794 }
795 }
796
797 /**
798 * Adds an entry to the directory.
799 *
800 * @param entry LDAPEntry object specifying the distinguished name and
801 * attributes of the new entry
802 * @param listener handler for messages returned from a server in response
803 * to this request. If it is null, a listener object is created internally.
804 * @param cons constraints specific to the operation
805 * @return LDAPResponseQueue handler for messages returned from a server
806 * in response to this request.
807 * @exception LDAPException Failed to send request.
808 * @see org.ietf.ldap.LDAPEntry
809 * @see org.ietf.ldap.LDAPResponseQueue
810 */
811 public LDAPResponseQueue add( LDAPEntry entry,
812 LDAPResponseQueue listener )
813 throws LDAPException{
814 return add( entry, listener, _defaultConstraints );
815 }
816
817 /**
818 * Adds an entry to the directory and allows you to specify constraints
819 * for this LDAP add operation by using an <CODE>LDAPConstraints</CODE>
820 * object. For example, you can specify whether or not to follow referrals.
821 * You can also apply LDAP v3 controls to the operation.
822 * <P>
823 *
824 * @param entry LDAPEntry object specifying the distinguished name and
825 * attributes of the new entry
826 * @param listener handler for messages returned from a server in response
827 * to this request. If it is null, a listener object is created internally.
828 * @param cons constraints specific to the operation
829 * @return LDAPResponseQueue handler for messages returned from a server
830 * in response to this request
831 * @exception LDAPException Failed to send request.
832 * @see org.ietf.ldap.LDAPEntry
833 * @see org.ietf.ldap.LDAPResponseQueue
834 * @see org.ietf.ldap.LDAPConstraints
835 */
836 public LDAPResponseQueue add( LDAPEntry entry,
837 LDAPResponseQueue listener,
838 LDAPConstraints cons )
839 throws LDAPException{
840
841 if (cons == null) {
842 cons = _defaultConstraints;
843 }
844
845 internalBind (cons);
846
847 if (listener == null) {
848 listener = new LDAPResponseQueue(/*asynchOp=*/true);
849 }
850
851 LDAPAttributeSet attrs = entry.getAttributeSet ();
852 LDAPAttribute[] attrList = new LDAPAttribute[attrs.size()];
853 Iterator<LDAPAttribute> it = attrs.iterator();
854 for( int i = 0; i < attrs.size(); i++ ) {
855 attrList[i] = it.next();
856 }
857 int attrPosition = 0;
858
859 sendRequest (new JDAPAddRequest (entry.getDN(), attrList),
860 listener, cons);
861
862 return listener;
863 }
864
865 /**
866 * Registers an object to be notified on arrival of an unsolicited
867 * message from a server
868 *
869 * @param listener An object to be notified on arrival of an
870 * unsolicited message from a server
871 */
872 public void addUnsolicitedNotificationListener(
873 LDAPUnsolicitedNotificationListener listener ) {
874 }
875
876 /**
877 * Authenticates to the LDAP server (to which you are currently
878 * connected) using the specified name and password.
879 * If you are not already connected to the LDAP server, this
880 * method attempts to reconnect to the server.
881 * <P>
882 *
883 * For example, the following section of code authenticates the
884 * client as Barbara Jensen. The code assumes that the client
885 * has already established a connection with an LDAP server.
886 * <P>
887 *
888 * <PRE>
889 * String myDN = "cn=Barbara Jensen,ou=Product Development,o=Ace Industry,c=US";
890 * String myPW = "hifalutin";
891 * try {
892 * myConn.bind( myDN, myPW.getBytes() );
893 * } catch ( LDAPException e ) {
894 * switch( e.getResultCode() ) {
895 * case e.NO_SUCH_OBJECT:
896 * System.out.println( "The specified user does not exist." );
897 * break;
898 * case e.INVALID_CREDENTIALS:
899 * System.out.println( "Invalid password." );
900 * break;
901 * default:
902 * System.out.println( "Error number: " + e.getResultCode() );
903 * System.out.println( "Failed to authentice as " + myDN );
904 * break;
905 * }
906 * return;
907 * }
908 * System.out.println( "Authenticated as " + myDN );
909 * </PRE>
910 *
911 * @param dn distinguished name used for authentication
912 * @param passwd password used for authentication
913 * @exception LDAPException Failed to authenticate to the LDAP server.
914 */
915 private void bind( String dn, byte[] passwd) throws LDAPException {
916 bind( _protocolVersion, dn, passwd, _defaultConstraints );
917 }
918
919 /**
920 * Authenticates to the LDAP server (to which you are currently
921 * connected) using the specified name and password. The
922 * default protocol version (version 2) is used. If the server
923 * doesn't support the default version, an LDAPException is thrown
924 * with the error code PROTOCOL_ERROR. This method allows the
925 * user to specify the preferences for the bind operation.
926 *
927 * @param dn distinguished name used for authentication
928 * @param passwd password used for authentication
929 * @param cons preferences for the bind operation
930 * @exception LDAPException Failed to authenticate to the LDAP server.
931 */
932 private void bind( String dn, byte[] passwd,
933 LDAPConstraints cons ) throws LDAPException {
934 bind( _protocolVersion, dn, passwd, cons );
935 }
936
937 /**
938 * Authenticates to the LDAP server (to which you are currently
939 * connected) using the specified name and password, and
940 * requests that the server use at least the specified
941 * protocol version. If the server doesn't support that
942 * level, an LDAPException is thrown with the error code
943 * PROTOCOL_ERROR.
944 *
945 * @param version required LDAP protocol version
946 * @param dn distinguished name used for authentication
947 * @param passwd password used for authentication
948 * @exception LDAPException Failed to authenticate to the LDAP server.
949 */
950 public void bind( int version, String dn, byte[] passwd )
951 throws LDAPException {
952 bind( version, dn, passwd, _defaultConstraints );
953 }
954
955 /**
956 * Authenticates to the LDAP server (to which you are currently
957 * connected) using the specified name and password, and
958 * requesting that the server use at least the specified
959 * protocol version. If the server doesn't support that
960 * level, an LDAPException is thrown with the error code
961 * PROTOCOL_ERROR. This method allows the user to specify the
962 * preferences for the bind operation.
963 *
964 * @param version required LDAP protocol version
965 * @param dn distinguished name used for authentication
966 * @param passwd password used for authentication
967 * @param cons preferences for the bind operation
968 * @exception LDAPException Failed to authenticate to the LDAP server.
969 */
970 public void bind( int version, String dn, byte[] passwd,
971 LDAPConstraints cons ) throws LDAPException {
972 _prevBoundDN = _boundDN;
973 _prevBoundPasswd = _boundPasswd;
974 _boundDN = dn;
975 _boundPasswd = passwd;
976
977 _anonymousBound =
978 ((_prevBoundDN == null) || (_prevBoundPasswd == null));
979
980 internalBind (version, true, cons);
981 }
982
983 /**
984 * Authenticates to the LDAP server (to which the object is currently
985 * connected) using the specified name and whatever SASL mechanisms
986 * are supported by the server. Each supported mechanism in turn
987 * is tried until authentication succeeds or an exception is thrown.
988 * If the object has been disconnected from an LDAP server, this
989 * method attempts to reconnect to the server. If the object had
990 * already authenticated, the old authentication is discarded.
991 *
992 * @param dn if non-null and non-empty, specifies that the connection and
993 * all operations through it should authenticate with dn as the
994 * distinguished name
995 * @param authzid If not null and not empty, an LDAP authzID [AUTH]
996 * to be passed to the SASL layer. If null or empty,
997 * the authzId will be treated as an empty string
998 * and processed as per RFC 2222 [SASL].
999 * @param props Optional qualifiers for the authentication session
1000 * @param cbh a class which the SASL framework can call to
1001 * obtain additional required information
1002 * @exception LDAPException Failed to authenticate to the LDAP server.
1003 */
1004 public void bind( String dn,
1005 String authzid,
1006 Map<String, String> props,
1007 CallbackHandler cbh )
1008 throws LDAPException {
1009 bind( dn, authzid, props, cbh, _defaultConstraints );
1010 }
1011
1012 /**
1013 * Authenticates to the LDAP server (to which the object is currently
1014 * connected) using the specified name and whatever SASL mechanisms
1015 * are supported by the server. Each supported mechanism in turn
1016 * is tried until authentication succeeds or an exception is thrown.
1017 * If the object has been disconnected from an LDAP server, this
1018 * method attempts to reconnect to the server. If the object had
1019 * already authenticated, the old authentication is discarded.
1020 *
1021 * @param dn if non-null and non-empty, specifies that the connection and
1022 * all operations through it should authenticate with dn as the
1023 * distinguished name
1024 * @param authzid If not null and not empty, an LDAP authzID [AUTH]
1025 * to be passed to the SASL layer. If null or empty,
1026 * the authzId will be treated as an empty string
1027 * and processed as per RFC 2222 [SASL].
1028 * @param props Optional qualifiers for the authentication session
1029 * @param cbh a class which the SASL framework can call to
1030 * obtain additional required information
1031 * @param cons preferences for the bind operation
1032 * @exception LDAPException Failed to authenticate to the LDAP server.
1033 */
1034 public void bind( String dn,
1035 String authzid,
1036 Map<String, String> props,
1037 CallbackHandler cbh,
1038 LDAPConstraints cons )
1039 throws LDAPException {
1040 if ( !isConnected() ) {
1041 connect();
1042 }
1043 // Get the list of mechanisms from the server
1044 String[] attrs = { "supportedSaslMechanisms" };
1045 LDAPEntry entry = read( "", attrs );
1046 LDAPAttribute attr = entry.getAttribute( attrs[0] );
1047 if ( attr == null ) {
1048 throw new LDAPException( "Not found in root DSE: " +
1049 attrs[0],
1050 LDAPException.NO_SUCH_ATTRIBUTE );
1051 }
1052 bind( dn, authzid, attr.getStringValueArray(), props, cbh, cons );
1053 }
1054
1055 /**
1056 * Authenticates to the LDAP server (to which the object is currently
1057 * connected) using the specified name and a specified SASL mechanism
1058 * or set of mechanisms. If the requested SASL mechanism is not
1059 * available, an exception is thrown. If the object has been
1060 * disconnected from an LDAP server, this method attempts to reconnect
1061 * to the server. If the object had already authenticated, the old
1062 * authentication is discarded.
1063 *
1064 * @param dn if non-null and non-empty, specifies that the connection and
1065 * all operations through it should authenticate with dn as the
1066 * distinguished name
1067 * @param authzid If not null and not empty, an LDAP authzID [AUTH]
1068 * to be passed to the SASL layer. If null or empty,
1069 * the authzId will be treated as an empty string
1070 * and processed as per RFC 2222 [SASL].
1071 * @param props Optional qualifiers for the authentication session
1072 * @param mechanisms a list of acceptable mechanisms. The first one
1073 * for which a Mechanism Driver can be instantiated is returned.
1074 * @param cbh a class which the SASL framework can call to
1075 * obtain additional required information
1076 * @exception LDAPException Failed to authenticate to the LDAP server.
1077 * @see org.ietf.ldap.LDAPConnection#bind(String, String, Map,
1078 * CallbackHandler)
1079 */
1080 public void bind( String dn,
1081 String authzid,
1082 String[] mechanisms,
1083 Map<String, String> props,
1084 CallbackHandler cbh )
1085 throws LDAPException {
1086 bind( dn, authzid, mechanisms, props, cbh, _defaultConstraints );
1087 }
1088
1089 /**
1090 * Authenticates to the LDAP server (to which the object is currently
1091 * connected) using the specified name and a specified SASL mechanism
1092 * or set of mechanisms. If the requested SASL mechanism is not
1093 * available, an exception is thrown. If the object has been
1094 * disconnected from an LDAP server, this method attempts to reconnect
1095 * to the server. If the object had already authenticated, the old
1096 * authentication is discarded.
1097 *
1098 * @param dn if non-null and non-empty, specifies that the connection and
1099 * all operations through it should authenticate with dn as the
1100 * distinguished name
1101 * @param authzid If not null and not empty, an LDAP authzID [AUTH]
1102 * to be passed to the SASL layer. If null or empty,
1103 * the authzId will be treated as an empty string
1104 * and processed as per RFC 2222 [SASL].
1105 * @param props Optional qualifiers for the authentication session
1106 * @param mechanisms a list of acceptable mechanisms. The first one
1107 * for which a Mechanism Driver can be instantiated is returned.
1108 * @param cbh a class which the SASL framework can call to
1109 * obtain additional required information
1110 * @param cons preferences for the bind operation
1111 * @exception LDAPException Failed to authenticate to the LDAP server.
1112 * @see org.ietf.ldap.LDAPConnection#bind(String, String, Map,
1113 * CallbackHandler, LDAPConstraints)
1114 */
1115 public void bind( String dn,
1116 String authzid,
1117 String[] mechanisms,
1118 Map<String, String> props,
1119 CallbackHandler cbh,
1120 LDAPConstraints cons )
1121 throws LDAPException {
1122
1123 if ( !isConnected() ) {
1124 connect();
1125 } else {
1126 // If the thread has more than one LDAPConnection, then
1127 // we should disconnect first. Otherwise,
1128 // we can reuse the same thread for the rebind.
1129 if (_thread.getClientCount() > 1) {
1130 disconnect();
1131 connect();
1132 }
1133 }
1134 _boundDN = null;
1135 _protocolVersion = 3; // Must be 3 for SASL
1136 if ( props == null ) {
1137 props = new Hashtable<>();
1138 }
1139 _saslBinder = new LDAPSaslBind( dn, mechanisms,
1140 props, cbh );
1141 _saslCallbackHandler = cbh;
1142 _saslBinder.bind( this );
1143 _authMethod = "sasl";
1144 _boundDN = dn;
1145 }
1146
1147 /**
1148 * Authenticates to the LDAP server (to which the object is currently
1149 * connected) using the specified name and password. If the object
1150 * has been disconnected from an LDAP server, this method attempts to
1151 * reconnect to the server. If the object had already authenticated, the
1152 * old authentication is discarded.
1153 *
1154 * @param version required LDAP protocol version
1155 * @param dn if non-null and non-empty, specifies that the connection
1156 * and all operations through it should authenticate with dn as the
1157 * distinguished name
1158 * @param passwd if non-null and non-empty, specifies that the connection
1159 * and all operations through it should authenticate with dn as the
1160 * distinguished name and passwd as password
1161 * @param listener handler for messages returned from a server in response
1162 * to this request. If it is null, a listener object is created internally.
1163 * @return LDAPResponseQueue handler for messages returned from a server
1164 * in response to this request.
1165 * @exception LDAPException Failed to send request.
1166 * @see org.ietf.ldap.LDAPResponseQueue
1167 */
1168 public LDAPResponseQueue bind( int version,
1169 String dn,
1170 byte[] passwd,
1171 LDAPResponseQueue listener )
1172 throws LDAPException{
1173 return bind( version, dn, passwd, listener, _defaultConstraints );
1174 }
1175
1176 /**
1177 * Authenticates to the LDAP server (to which the object is currently
1178 * connected) using the specified name and password. If the object
1179 * has been disconnected from an LDAP server, this method attempts to
1180 * reconnect to the server. If the object had already authenticated, the
1181 * old authentication is discarded.
1182 *
1183 * @param dn if non-null and non-empty, specifies that the connection
1184 * and all operations through it should authenticate with dn as the
1185 * distinguished name
1186 * @param passwd if non-null and non-empty, specifies that the connection
1187 * and all operations through it should authenticate with dn as the
1188 * distinguished name and passwd as password
1189 * @param listener handler for messages returned from a server in response
1190 * to this request. If it is null, a listener object is created internally.
1191 * @return LDAPResponseQueue handler for messages returned from a server
1192 * in response to this request.
1193 * @exception LDAPException Failed to send request.
1194 * @see org.ietf.ldap.LDAPResponseQueue
1195 */
1196 private LDAPResponseQueue bind( String dn,
1197 byte[] passwd,
1198 LDAPResponseQueue listener)
1199 throws LDAPException{
1200 return bind( _protocolVersion, dn, passwd, listener,
1201 _defaultConstraints );
1202 }
1203
1204 /**
1205 * Authenticates to the LDAP server (to which the object is currently
1206 * connected) using the specified name and password and allows you
1207 * to specify constraints for this LDAP add operation by using an
1208 * <CODE>LDAPConstraints</CODE> object. If the object
1209 * has been disconnected from an LDAP server, this method attempts to
1210 * reconnect to the server. If the object had already authenticated, the
1211 * old authentication is discarded.
1212 *
1213 * @param dn if non-null and non-empty, specifies that the connection
1214 * and all operations through it should authenticate with dn as the
1215 * distinguished name
1216 * @param passwd if non-null and non-empty, specifies that the connection
1217 * and all operations through it should authenticate with dn as the
1218 * distinguished name and passwd as password
1219 * @param listener handler for messages returned from a server in response
1220 * to this request. If it is null, a listener object is created internally.
1221 * @param cons constraints specific to the operation
1222 * @return LDAPResponseQueue handler for messages returned from a server
1223 * in response to this request.
1224 * @exception LDAPException Failed to send request.
1225 * @see org.ietf.ldap.LDAPResponseQueue
1226 * @see org.ietf.ldap.LDAPConstraints
1227 */
1228 private LDAPResponseQueue bind( String dn,
1229 byte[] passwd,
1230 LDAPResponseQueue listener,
1231 LDAPConstraints cons )
1232 throws LDAPException{
1233 return bind( _protocolVersion, dn, passwd, listener, cons );
1234 }
1235
1236 /**
1237 * Authenticates to the LDAP server (to which the object is currently
1238 * connected) using the specified name and password and allows you
1239 * to specify constraints for this LDAP add operation by using an
1240 * <CODE>LDAPConstraints</CODE> object. If the object
1241 * has been disconnected from an LDAP server, this method attempts to
1242 * reconnect to the server. If the object had already authenticated, the
1243 * old authentication is discarded.
1244 *
1245 * @param version required LDAP protocol version
1246 * @param dn if non-null and non-empty, specifies that the connection
1247 * and all operations through it should authenticate with dn as the
1248 * distinguished name
1249 * @param passwd if non-null and non-empty, specifies that the connection
1250 * and all operations through it should authenticate with dn as the
1251 * distinguished name and passwd as password
1252 * @param listener handler for messages returned from a server in response
1253 * to this request. If it is null, a listener object is created internally.
1254 * @param cons constraints specific to the operation
1255 * @return LDAPResponseQueue handler for messages returned from a server
1256 * in response to this request.
1257 * @exception LDAPException Failed to send request.
1258 * @see org.ietf.ldap.LDAPResponseQueue
1259 * @see org.ietf.ldap.LDAPConstraints
1260 */
1261 public LDAPResponseQueue bind( int version,
1262 String dn,
1263 byte[] passwd,
1264 LDAPResponseQueue listener,
1265 LDAPConstraints cons )
1266 throws LDAPException{
1267 if (cons == null) {
1268 cons = _defaultConstraints;
1269 }
1270
1271 _prevBoundDN = _boundDN;
1272 _prevBoundPasswd = _boundPasswd;
1273 _boundDN = dn;
1274 _boundPasswd = passwd;
1275 _protocolVersion = version;
1276
1277 if (_thread == null) {
1278 connect();
1279 }
1280 else if (_thread.getClientCount() > 1) {
1281 disconnect();
1282 connect();
1283 }
1284
1285 if (listener == null) {
1286 listener = new LDAPResponseQueue(/*asynchOp=*/true);
1287 }
1288
1289 sendRequest(new JDAPBindRequest(version, _boundDN, _boundPasswd),
1290 listener, cons);
1291
1292 return listener;
1293 }
1294
1295 /**
1296 * Authenticates to the LDAP server (to which the object is currently
1297 * connected) using the specified name and a specified SASL mechanism
1298 * or set of mechanisms. If the requested SASL mechanism is not
1299 * available, an exception is thrown. If the object has been
1300 * disconnected from an LDAP server, this method attempts to reconnect
1301 * to the server. If the object had already authenticated, the old
1302 * authentication is discarded.
1303 *
1304 * @param dn if non-null and non-empty, specifies that the connection and
1305 * all operations through it should authenticate with dn as the
1306 * distinguished name
1307 * @param authzid If not null and not empty, an LDAP authzID [AUTH]
1308 * to be passed to the SASL layer. If null or empty,
1309 * the authzId will be treated as an empty string
1310 * and processed as per RFC 2222 [SASL].
1311 * @param mechanisms a list of acceptable mechanisms. The first one
1312 * for which a Mechanism Driver can be instantiated is returned.
1313 * @param packageName a package containing a SASL ClientFactory,
1314 * e.g. "myclasses.SASL". If null, a system default is used.
1315 * @param cbh a class which the SASL framework can call to
1316 * obtain additional required information
1317 * @exception LDAPException Failed to authenticate to the LDAP server.
1318 * @deprecated Please use authenticate without packageName
1319 * instead.
1320 */
1321 public void bind( String dn,
1322 String authzid,
1323 String[] mechanisms,
1324 String packageName,
1325 Map<String, String> props,
1326 CallbackHandler cbh,
1327 LDAPConstraints cons )
1328 throws LDAPException {
1329 if ( props == null ) {
1330 props = new Hashtable<>();
1331 }
1332 props.put( LDAPSaslBind.CLIENTPKGS, packageName );
1333 bind( dn, authzid, mechanisms, props, cbh, cons );
1334 }
1335
1336 /**
1337 * Creates and returns a copy of the object. The new
1338 * <CODE>LDAPConnection</CODE> object contains the same information as
1339 * the original connection, including:
1340 * <UL>
1341 * <LI>the default search constraints
1342 * <LI>host name and port number of the LDAP server
1343 * <LI>the DN and password used to authenticate to the LDAP server
1344 * </UL>
1345 * <P>
1346 * @return the <CODE>LDAPconnection</CODE> object representing the
1347 * new object.
1348 */
1349 public synchronized Object clone() {
1350 try {
1351 LDAPConnection c = (LDAPConnection)super.clone();
1352
1353 if (!isConnected()) {
1354 this.internalBind(_defaultConstraints);
1355 }
1356
1357 c._defaultConstraints =
1358 (LDAPSearchConstraints)_defaultConstraints.clone();
1359 c._responseListeners = null;
1360 c._searchListeners = null;
1361 c._bound = this._bound;
1362 c._connMgr = _connMgr;
1363 c._connSetupDelay = _connSetupDelay;
1364 c._boundDN = this._boundDN;
1365 c._boundPasswd = this._boundPasswd;
1366 c._prevBoundDN = this._prevBoundDN;
1367 c._prevBoundPasswd = this._prevBoundPasswd;
1368 c._anonymousBound = this._anonymousBound;
1369 c.setCache(this._cache); // increments cache reference cnt
1370 c._factory = this._factory;
1371 c._thread = this._thread; /* share current connection thread */
1372
1373 synchronized (_threadConnTable) {
1374 Vector<LDAPConnection> v = _threadConnTable.get(this._thread);
1375 if (v != null) {
1376 v.addElement(c);
1377 } else {
1378 printDebug("Failed to clone");
1379 return null;
1380 }
1381 }
1382
1383 c._thread.register(c);
1384 return c;
1385 } catch (Exception e) {
1386 }
1387 return null;
1388 }
1389
1390 /**
1391 * Checks to see if an entry contains an attribute with a specified value.
1392 * Returns <CODE>true</CODE> if the entry has the value. Returns
1393 * <CODE>false</CODE> if the entry does not have the value or the
1394 * attribute. To represent the value that you want compared, you need
1395 * to create an <CODE>LDAPAttribute</CODE> object.<P>
1396 *
1397 * Note that only string values can be compared. <P>
1398 *
1399 * For example, the following section of code checks to see if the entry
1400 * "cn=Barbara Jensen,ou=Product Development,o=Ace Industry,c=US" contains
1401 * the attribute "mail" with the value "[email protected]".
1402 *
1403 * <PRE>
1404 * ...
1405 * LDAPConnection myConn = new LDAPConnection();
1406 * ...
1407 * String myDN = "cn=Barbara Jensen,ou=Product Development,o=Ace Industry,c=US";
1408 * String nameOfAttr = "mail";
1409 * String valOfAttr = "[email protected]";
1410 * LDAPAttribute cmpThisAttr = new LDAPAttribute( nameOfAttr, valOfAttr );
1411 * boolean hasValue = myConn.compare( myDN, cmpThisAttr );
1412 * if ( hasValue ) {
1413 * System.out.println( "Attribute and value found in entry." );
1414 * } else {
1415 * System.out.println( "Attribute and value not found in entry." );
1416 * }
1417 * ...</PRE>
1418 *
1419 * @param DN the distinguished name of the entry to use in
1420 * the comparison
1421 * @param attr the attribute to compare against the entry.
1422 * (The method checks to see if the entry has an attribute with the same name
1423 * and value as this attribute.)
1424 * @return true if the entry contains the specified attribute and value.
1425 * @exception LDAPException Failed to perform the comparison.
1426 * @see org.ietf.ldap.LDAPAttribute
1427 */
1428 public boolean compare( String DN, LDAPAttribute attr )
1429 throws LDAPException {
1430 return compare( DN, attr, _defaultConstraints );
1431 }
1432
1433 public boolean compare( String DN, LDAPAttribute attr,
1434 LDAPConstraints cons ) throws LDAPException {
1435 internalBind(cons);
1436
1437 LDAPResponseQueue myListener = getResponseListener ();
1438 Enumeration<String> en = attr.getStringValues();
1439 String val = en.nextElement();
1440 JDAPAVA ass = new JDAPAVA(attr.getName(), val);
1441
1442 LDAPMessage response;
1443 try {
1444 sendRequest (new JDAPCompareRequest (DN, ass), myListener, cons);
1445 response = myListener.getResponse ();
1446
1447 int resultCode = ((JDAPResult)response.getProtocolOp()).getResultCode();
1448 if (resultCode == JDAPResult.COMPARE_FALSE) {
1449 return false;
1450 }
1451 if (resultCode == JDAPResult.COMPARE_TRUE) {
1452 return true;
1453 }
1454
1455 checkMsg (response);
1456
1457 } catch (LDAPReferralException e) {
1458 Vector<Object> res = new Vector<>();
1459 performReferrals(e, cons, JDAPProtocolOp.COMPARE_REQUEST,
1460 DN, 0, null, null, false, null, null, attr, res);
1461 boolean bool = false;
1462 if (res.size() > 0) {
1463 bool = ((Boolean)res.elementAt(0)).booleanValue();
1464 }
1465 return bool;
1466 } finally {
1467 releaseResponseListener (myListener);
1468 }
1469 return false; /* this should never be executed */
1470 }
1471
1472 /**
1473 * @deprecated Please use the method signature where <CODE>cons</CODE> is
1474 * <CODE>LDAPConstraints</CODE> instead of <CODE>LDAPSearchConstraints</CODE>
1475 */
1476 public boolean compare( String DN,
1477 LDAPAttribute attr,
1478 LDAPSearchConstraints cons ) throws LDAPException {
1479 return compare( DN, attr, (LDAPConstraints)cons );
1480 }
1481
1482 /**
1483 * Compare an attribute value with one in the directory. The result can
1484 * be obtained by calling <CODE>getResultCode</CODE> on the
1485 * <CODE>LDAPResponse</CODE> from the <CODE>LDAPResponseQueue</CODE>.
1486 * The code will be <CODE>LDAPException.COMPARE_TRUE</CODE> or
1487 * <CODE>LDAPException.COMPARE_FALSE</CODE>.
1488 *
1489 * @param dn distinguished name of the entry to compare
1490 * @param attr attribute with a value to compare
1491 * @param listener handler for messages returned from a server in response
1492 * to this request. If it is null, a listener object is created internally.
1493 * @return LDAPResponseQueue handler for messages returned from a server
1494 * in response to this request.
1495 * @exception LDAPException Failed to send request.
1496 */
1497 public LDAPResponseQueue compare( String dn,
1498 LDAPAttribute attr,
1499 LDAPResponseQueue listener )
1500 throws LDAPException {
1501
1502 return compare( dn, attr, listener, _defaultConstraints );
1503 }
1504
1505 /**
1506 * Compare an attribute value with one in the directory. The result can
1507 * be obtained by calling <CODE>getResultCode</CODE> on the
1508 * <CODE>LDAPResponse</CODE> from the <CODE>LDAPResponseQueue</CODE>.
1509 * The code will be <CODE>LDAPException.COMPARE_TRUE</CODE> or
1510 * <CODE>LDAPException.COMPARE_FALSE</CODE>.
1511 *
1512 * @param dn distinguished name of the entry to compare
1513 * @param attr attribute with a value to compare
1514 * @param listener handler for messages returned from a server in response
1515 * to this request. If it is null, a listener object is created internally.
1516 * @param cons constraints specific to this operation
1517 * @return LDAPResponseQueue handler for messages returned from a server
1518 * in response to this request.
1519 * @exception LDAPException Failed to send request.
1520 */
1521 public LDAPResponseQueue compare( String dn,
1522 LDAPAttribute attr,
1523 LDAPResponseQueue listener,
1524 LDAPConstraints cons )
1525 throws LDAPException {
1526 if (cons == null) {
1527 cons = _defaultConstraints;
1528 }
1529
1530 internalBind (cons);
1531
1532 if (listener == null) {
1533 listener = new LDAPResponseQueue(/*asynchOp=*/true);
1534 }
1535
1536 Enumeration<String> en = attr.getStringValues();
1537 String val = en.nextElement();
1538 JDAPAVA ava = new JDAPAVA(attr.getName(), val);
1539
1540 sendRequest (new JDAPCompareRequest (dn, ava), listener, cons);
1541 return listener;
1542 }
1543
1544 /**
1545 * Connects to the specified host and port. If this LDAPConnection object
1546 * represents an open connection, the connection is closed first
1547 * before the new connection is opened.
1548 * <P>
1549 *
1550 * For example, the following section of code establishes a connection with
1551 * the LDAP server running on the host ldap.netscape.com and the port 389.
1552 * <P>
1553 *
1554 * <PRE>
1555 * String ldapHost = "ldap.netscape.com";
1556 * int ldapPort = 389;
1557 * LDAPConnection myConn = new LDAPConnection();
1558 * try {
1559 * myConn.connect( ldapHost, ldapPort );
1560 * } catch ( LDAPException e ) {
1561 * System.out.println( "Unable to connect to " + ldapHost +
1562 * " at port " + ldapPort );
1563 * return;
1564 * }
1565 * System.out.println( "Connected to " + ldapHost + " at port " + ldapPort )
1566 * </PRE>
1567 *<P>
1568 * You can limit the time spent waiting for the connection to be established
1569 * by calling <CODE>setConnectTimeout</CODE> before <CODE>connect</CODE>.
1570 * <P>
1571 * @param host host name of the LDAP server to which you want to connect.
1572 * This value can also be a space-delimited list of hostnames or
1573 * hostnames and port numbers (using the syntax
1574 * <I>hostname:portnumber</I>). For example, you can specify
1575 * the following values for the <CODE>host</CODE> argument:<BR>
1576 *<PRE>
1577 * myhost
1578 * myhost hishost:389 herhost:5000 whathost
1579 * myhost:686 myhost:389 hishost:5000 whathost:1024
1580 *</PRE>
1581 * If multiple servers are specified in the <CODE>host</CODE> list, the connection
1582 * setup policy specified with the <CODE>ConnSetupDelay</CODE> property controls
1583 * whether connection attempts are made serially or concurrently.
1584 * <P>
1585 * @param port port number of the LDAP server to which you want to connect.
1586 * This parameter is ignored for any host in the <CODE>host</CODE>
1587 * parameter which includes a colon and port number.
1588 * @exception LDAPException The connection failed.
1589 * @see org.ietf.ldap.LDAPConnection#setConnSetupDelay
1590 * @see org.ietf.ldap.LDAPConnection#setConnectTimeout
1591 */
1592 public void connect(String host, int port) throws LDAPException {
1593 connect( host, port, null, null, _defaultConstraints, false );
1594 }
1595
1596 /**
1597 * Connects to the specified host and port and uses the specified DN and
1598 * password to authenticate to the server. If this LDAPConnection object
1599 * represents an open connection, the connection is closed first
1600 * before the new connection is opened.
1601 * <P>
1602 *
1603 * For example, the following section of code establishes a connection
1604 * with the LDAP server running on ldap.netscape.com at port 389. The
1605 * example also attempts to authenticate the client as Barbara Jensen.
1606 * <P>
1607 *
1608 * <PRE>
1609 * String ldapHost = "ldap.netscape.com";
1610 * int ldapPort = 389;
1611 * String myDN = "cn=Barbara Jensen,ou=Product Development,o=Ace Industry,c=US";
1612 * String myPW = "hifalutin";
1613 * LDAPConnection myConn = new LDAPConnection();
1614 * try {
1615 * myConn.connect( ldapHost, ldapPort, myDN, myPW );
1616 * } catch ( LDAPException e ) {
1617 * switch( e.getResultCode() ) {
1618 * case e.NO_SUCH_OBJECT:
1619 * System.out.println( "The specified user does not exist." );
1620 * break;
1621 * case e.INVALID_CREDENTIALS:
1622 * System.out.println( "Invalid password." );
1623 * break;
1624 * default:
1625 * System.out.println( "Error number: " + e.getResultCode() );
1626 * System.out.println( "Failed to connect to " + ldapHost + " at port " + ldapPort );
1627 * break;
1628 * }
1629 * return;
1630 * }
1631 * System.out.println( "Connected to " + ldapHost + " at port " + ldapPort );
1632 * </PRE>
1633 *<P>
1634 * You can limit the time spent waiting for the connection to be established
1635 * by calling <CODE>setConnectTimeout</CODE> before <CODE>connect</CODE>.
1636 * <P>
1637 * @param host host name of the LDAP server to which you want to connect.
1638 * This value can also be a space-delimited list of hostnames or
1639 * hostnames and port numbers (using the syntax
1640 * <I>hostname:portnumber</I>). For example, you can specify
1641 * the following values for the <CODE>host</CODE> argument:<BR>
1642 *<PRE>
1643 * myhost
1644 * myhost hishost:389 herhost:5000 whathost
1645 * myhost:686 myhost:389 hishost:5000 whathost:1024
1646 *</PRE>
1647 * If multiple servers are specified in the <CODE>host</CODE> list, the connection
1648 * setup policy specified with the <CODE>ConnSetupDelay</CODE> property controls
1649 * whether connection attempts are made serially or concurrently.
1650 * <P>
1651 * @param port port number of the LDAP server to which you want to connect.
1652 * This parameter is ignored for any host in the <CODE>host</CODE>
1653 * parameter which includes a colon and port number.
1654 * @param dn distinguished name used for authentication
1655 * @param passwd password used for authentication
1656 * @exception LDAPException The connection or authentication failed.
1657 * @see org.ietf.ldap.LDAPConnection#setConnSetupDelay
1658 * @see org.ietf.ldap.LDAPConnection#setConnectTimeout
1659 */
1660 private void connect(String host, int port, String dn, byte[] passwd)
1661 throws LDAPException {
1662 connect(host, port, dn, passwd, _defaultConstraints, true);
1663 }
1664
1665 /**
1666 * Connects to the specified host and port and uses the specified DN and
1667 * password to authenticate to the server. If this LDAPConnection object
1668 * represents an open connection, the connection is closed first
1669 * before the new connection is opened. This method allows the user to
1670 * specify the preferences for the bind operation.
1671 *<P>
1672 * You can limit the time spent waiting for the connection to be established
1673 * by calling <CODE>setConnectTimeout</CODE> before <CODE>connect</CODE>.
1674 * <P>
1675 * @param host host name of the LDAP server to which you want to connect.
1676 * This value can also be a space-delimited list of hostnames or
1677 * hostnames and port numbers (using the syntax
1678 * <I>hostname:portnumber</I>). For example, you can specify
1679 * the following values for the <CODE>host</CODE> argument:<BR>
1680 *<PRE>
1681 * myhost
1682 * myhost hishost:389 herhost:5000 whathost
1683 * myhost:686 myhost:389 hishost:5000 whathost:1024
1684 *</PRE>
1685 * If multiple servers are specified in the <CODE>host</CODE> list, the connection
1686 * setup policy specified with the <CODE>ConnSetupDelay</CODE> property controls
1687 * whether connection attempts are made serially or concurrently.
1688 * <P>
1689 * @param port port number of the LDAP server to which you want to connect.
1690 * This parameter is ignored for any host in the <CODE>host</CODE>
1691 * parameter which includes a colon and port number.
1692 * @param dn distinguished name used for authentication
1693 * @param passwd password used for authentication
1694 * @param cons preferences for the bind operation
1695 * @exception LDAPException The connection or authentication failed.
1696 * @see org.ietf.ldap.LDAPConnection#setConnSetupDelay
1697 * @see org.ietf.ldap.LDAPConnection#setConnectTimeout
1698 */
1699 private void connect(String host, int port, String dn, byte[] passwd,
1700 LDAPConstraints cons) throws LDAPException {
1701 connect(host, port, dn, passwd, cons, true);
1702 }
1703
1704 private void connect(String host, int port, String dn, byte[] passwd,
1705 LDAPConstraints cons, boolean doAuthenticate)
1706 throws LDAPException {
1707 if ( isConnected() ) {
1708 disconnect ();
1709 }
1710 if ((host == null) || (host.equals(""))) {
1711 throw new LDAPException ( "no host for connection",
1712 LDAPException.PARAM_ERROR );
1713 }
1714
1715 /* Parse the list of hosts */
1716 int defaultPort = port;
1717 StringTokenizer st = new StringTokenizer( host );
1718 String hostList[] = new String[st.countTokens()];
1719 int portList[] = new int[st.countTokens()];
1720 int i = 0;
1721 while( st.hasMoreTokens() ) {
1722 String s = st.nextToken();
1723 int colon = s.indexOf( ':' );
1724 if ( colon > 0 ) {
1725 hostList[i] = s.substring( 0, colon );
1726 portList[i] = Integer.parseInt( s.substring( colon+1 ) );
1727 } else {
1728 hostList[i] = s;
1729 portList[i] = defaultPort;
1730 }
1731 i++;
1732 }
1733
1734 /* Create the Connection Setup Manager */
1735 _connMgr = new LDAPConnSetupMgr(hostList, portList, _factory);
1736 _connMgr.setConnSetupDelay(_connSetupDelay);
1737 _connMgr.setConnectTimeout(_connectTimeout);
1738
1739 connect();
1740
1741 if ( doAuthenticate ) {
1742 bind( dn, passwd, cons );
1743 }
1744 }
1745
1746 /**
1747 * Connects to the specified host and port and uses the specified DN and
1748 * password to authenticate to the server, with the specified LDAP
1749 * protocol version. If the server does not support the requested
1750 * protocol version, an exception is thrown. If this LDAPConnection
1751 * object represents an open connection, the connection is closed first
1752 * before the new connection is opened. This is equivalent to
1753 * <CODE>connect(host, port)</CODE> followed by <CODE>bind(version, dn, passwd)</CODE>.<P>
1754 *
1755 * @param version requested version of LDAP: currently 2 or 3
1756 * @param host a hostname to which to connect or a dotted string representing
1757 * the IP address of this host.
1758 * Alternatively, this can be a space-delimited list of host names.
1759 * Each host name may include a trailing colon and port number. In the
1760 * case where more than one host name is specified, the connection setup
1761 * policy specified with the <CODE>ConnSetupDelay</CODE> property controls
1762 * whether connection attempts are made serially or concurrently.<P>
1763 *
1764 * <PRE>
1765 * Examples:
1766 * "directory.knowledge.com"
1767 * "199.254.1.2"
1768 * "directory.knowledge.com:1050 people.catalog.com 199.254.1.2"
1769 * </PRE>
1770 * @param port the TCP or UDP port number to which to connect or contact.
1771 * The default LDAP port is 389. "port" is ignored for any host name which
1772 * includes a colon and port number.
1773 * @param dn if non-null and non-empty, specifies that the connection and
1774 * all operations through it should authenticate with dn as the
1775 * distinguished name
1776 * @param passwd if non-null and non-empty, specifies that the connection and
1777 * all operations through it should authenticate with dn as the
1778 * distinguished name and passwd as password.
1779 * @exception LDAPException The connection or authentication failed.
1780 * @see org.ietf.ldap.LDAPConnection#setConnSetupDelay
1781 */
1782 private void connect(int version, String host, int port, String dn,
1783 byte[] passwd) throws LDAPException {
1784
1785 connect(version, host, port, dn, passwd, _defaultConstraints);
1786 }
1787
1788 /**
1789 * Connects to the specified host and port and uses the specified DN and
1790 * password to authenticate to the server, with the specified LDAP
1791 * protocol version. If the server does not support the requested
1792 * protocol version, an exception is thrown. This method allows the user
1793 * to specify preferences for the bind operation. If this LDAPConnection
1794 * object represents an open connection, the connection is closed first
1795 * before the new connection is opened. This is equivalent to
1796 * <CODE>connect(host, port)</CODE> followed by <CODE>bind(version, dn, passwd)</CODE>.<P>
1797 *
1798 * @param version requested version of LDAP: currently 2 or 3
1799 * @param host a hostname to which to connect or a dotted string representing
1800 * the IP address of this host.
1801 * Alternatively, this can be a space-delimited list of host names.
1802 * Each host name may include a trailing colon and port number. In the
1803 * case where more than one host name is specified, the connection setup
1804 * policy specified with the <CODE>ConnSetupDelay</CODE> property controls
1805 * whether connection attempts are made serially or concurrently.<P>
1806 *
1807 * <PRE>
1808 * Examples:
1809 * "directory.knowledge.com"
1810 * "199.254.1.2"
1811 * "directory.knowledge.com:1050 people.catalog.com 199.254.1.2"
1812 * </PRE>
1813 * @param port the TCP or UDP port number to which to connect or contact.
1814 * The default LDAP port is 389. "port" is ignored for any host name which
1815 * includes a colon and port number.
1816 * @param dn if non-null and non-empty, specifies that the connection and
1817 * all operations through it should authenticate with dn as the
1818 * distinguished name
1819 * @param passwd if non-null and non-empty, specifies that the connection and
1820 * all operations through it should authenticate with dn as the
1821 * distinguished name and passwd as password
1822 * @param cons preferences for the bind operation
1823 * @exception LDAPException The connection or authentication failed.
1824 * @see org.ietf.ldap.LDAPConnection#setConnSetupDelay
1825 */
1826 private void connect(int version, String host, int port, String dn,
1827 byte[] passwd, LDAPConstraints cons) throws LDAPException {
1828
1829 setProtocolVersion(version);
1830 connect(host, port, dn, passwd, cons);
1831 }
1832
1833 /**
1834 * @deprecated Please use the method signature where <CODE>cons</CODE> is
1835 * <CODE>LDAPConstraints</CODE> instead of <CODE>LDAPSearchConstraints</CODE>
1836 */
1837 private void connect(int version, String host, int port, String dn,
1838 byte[] passwd, LDAPSearchConstraints cons) throws LDAPException {
1839
1840 connect(version, host, port, dn, passwd, (LDAPConstraints)cons);
1841 }
1842
1843 /**
1844 * Internal routine to connect with internal params
1845 * @exception LDAPException failed to connect
1846 */
1847 private synchronized void connect () throws LDAPException {
1848 if ( isConnected() ) {
1849 return;
1850 }
1851
1852 if (_connMgr == null) {
1853 throw new LDAPException ( "no connection parameters",
1854 LDAPException.PARAM_ERROR );
1855 }
1856
1857 _connMgr.openConnection();
1858 _thread = getNewThread(_connMgr, _cache);
1859 authenticateSSLConnection();
1860 }
1861
1862 /**
1863 * Deletes the entry for the specified DN from the directory. <P>
1864 *
1865 * For example, the following section of code deletes the entry for
1866 * Barbara Jensen from the directory. <P>
1867 *
1868 * <PRE>
1869 * ...
1870 * String myEntryDN = "cn=Barbara Jensen,ou=Product Development,o=Ace Industry,c=US";
1871 * myConn.delete( myEntryDN );
1872 * ... </PRE>
1873 *
1874 * @param DN distinguished name identifying the entry
1875 * to remove from the directory
1876 * @exception LDAPException Failed to delete the specified entry from
1877 * the directory.
1878 */
1879 public void delete( String DN ) throws LDAPException {
1880 delete(DN, _defaultConstraints);
1881 }
1882
1883 /**
1884 * Deletes the entry for the specified DN from the directory and
1885 * allows you to specify preferences for this LDAP delete operation
1886 * by using an <CODE>LDAPConstraints</CODE> object. For
1887 * example, you can specify whether or not to follow referrals.
1888 * You can also apply LDAP v3 controls to the operation.
1889 * <P>
1890 *
1891 * @param DN distinguished name identifying the entry
1892 * to remove from the directory
1893 * @param cons the set of preferences to apply to this operation
1894 * @exception LDAPException Failed to delete the specified entry from
1895 * the directory.
1896 * @see org.ietf.ldap.LDAPConstraints
1897 */
1898 public void delete( String DN, LDAPConstraints cons )
1899 throws LDAPException {
1900 internalBind (cons);
1901
1902 LDAPResponseQueue myListener = getResponseListener ();
1903 LDAPMessage response;
1904 try {
1905 sendRequest (new JDAPDeleteRequest (DN), myListener, cons);
1906 response = myListener.getResponse();
1907 checkMsg (response);
1908 } catch (LDAPReferralException e) {
1909 performReferrals(e, cons, JDAPProtocolOp.DEL_REQUEST,
1910 DN, 0, null, null, false, null, null, null, null);
1911 } finally {
1912 releaseResponseListener (myListener);
1913 }
1914 }
1915
1916 /**
1917 * Deletes the entry for the specified DN from the directory.
1918 *
1919 * @param dn distinguished name of the entry to delete
1920 * @param listener handler for messages returned from a server in response
1921 * to this request. If it is null, a listener object is created internally.
1922 * @return LDAPResponseQueue handler for messages returned from a server
1923 * in response to this request.
1924 * @exception LDAPException Failed to send request.
1925 * @see org.ietf.ldap.LDAPResponseQueue
1926 * @see org.ietf.ldap.LDAPConstraints
1927 */
1928 public LDAPResponseQueue delete( String dn,
1929 LDAPResponseQueue listener )
1930 throws LDAPException {
1931
1932 return delete( dn, listener, _defaultConstraints );
1933 }
1934
1935 /**
1936 * Deletes the entry for the specified DN from the directory.
1937 *
1938 * @param dn distinguished name of the entry to delete
1939 * @param listener handler for messages returned from a server in response
1940 * to this request. If it is null, a listener object is created internally.
1941 * @param cons constraints specific to the operation
1942 * @return LDAPResponseQueue handler for messages returned from a server
1943 * in response to this request.
1944 * @exception LDAPException Failed to send request.
1945 * @see org.ietf.ldap.LDAPResponseQueue
1946 * @see org.ietf.ldap.LDAPConstraints
1947 */
1948 public LDAPResponseQueue delete( String dn,
1949 LDAPResponseQueue listener,
1950 LDAPConstraints cons )
1951 throws LDAPException {
1952 if (cons == null) {
1953 cons = _defaultConstraints;
1954 }
1955
1956 internalBind (cons);
1957
1958 if (listener == null) {
1959 listener = new LDAPResponseQueue(/*asynchOp=*/true);
1960 }
1961
1962 sendRequest (new JDAPDeleteRequest(dn), listener, cons);
1963
1964 return listener;
1965
1966 }
1967
1968 /**
1969 * Disconnects from the LDAP server. Before you can perform LDAP operations
1970 * again, you need to reconnect to the server by calling
1971 * <CODE>connect</CODE>.
1972 * @exception LDAPException Failed to disconnect from the LDAP server.
1973 * @see org.ietf.ldap.LDAPConnection#connect(java.lang.String, int)
1974 */
1975 public synchronized void disconnect() throws LDAPException {
1976 if (!isConnected())
1977 throw new LDAPException ( "unable to disconnect() without connecting",
1978 LDAPException.OTHER );
1979
1980 // Clone the Connection Setup Manager if the connection is shared
1981 if (_thread.isRunning() && _thread.getClientCount() > 1) {
1982 _connMgr = (LDAPConnSetupMgr) _connMgr.clone();
1983 _connMgr.disconnect();
1984 }
1985
1986 if (_referralConnection != null && _referralConnection.isConnected()) {
1987 _referralConnection.disconnect();
1988 }
1989 _referralConnection = null;
1990
1991 if (_cache != null) {
1992 _cache.removeReference();
1993 _cache = null;
1994 }
1995
1996 deleteThreadConnEntry();
1997 deregisterConnection();
1998 }
1999
2000 /**
2001 * Performs an extended operation on the directory. Extended operations
2002 * are part of version 3 of the LDAP protocol.<P>
2003 *
2004 * Note that in order for the extended operation to work, the server
2005 * that you are connecting to must support LDAP v3 and must be configured
2006 * to process the specified extended operation.
2007 *
2008 * @param op LDAPExtendedOperation object specifying the OID of the
2009 * extended operation and the data to use in the operation
2010 * @exception LDAPException Failed to execute the operation
2011 * @return LDAPExtendedOperation object representing the extended response
2012 * returned by the server.
2013 * @see org.ietf.ldap.LDAPExtendedOperation
2014 */
2015 public LDAPExtendedOperation extendedOperation( LDAPExtendedOperation op )
2016 throws LDAPException {
2017
2018 return extendedOperation(op, _defaultConstraints);
2019 }
2020
2021 /**
2022 * Performs an extended operation on the directory. Extended operations
2023 * are part of version 3 of the LDAP protocol. This method allows the
2024 * user to set the preferences for the operation.<P>
2025 *
2026 * Note that in order for the extended operation to work, the server
2027 * that you are connecting to must support LDAP v3 and must be configured
2028 * to process the specified extended operation.
2029 *
2030 * @param op LDAPExtendedOperation object specifying the OID of the
2031 * extended operation and the data to use in the operation
2032 * @param cons preferences for the extended operation
2033 * @exception LDAPException Failed to execute the operation
2034 * @return LDAPExtendedOperation object representing the extended response
2035 * returned by the server.
2036 * @see org.ietf.ldap.LDAPExtendedOperation
2037 */
2038 public LDAPExtendedOperation extendedOperation( LDAPExtendedOperation op,
2039 LDAPConstraints cons )
2040 throws LDAPException {
2041 internalBind (cons);
2042
2043 LDAPResponseQueue myListener = getResponseListener ();
2044 LDAPMessage response = null;
2045 byte[] results = null;
2046 String resultID;
2047
2048 try {
2049 sendRequest ( new JDAPExtendedRequest( op.getID(),
2050 op.getValue() ),
2051 myListener, cons );
2052 response = myListener.getResponse();
2053 checkMsg (response);
2054 JDAPExtendedResponse res = (JDAPExtendedResponse)response.getProtocolOp();
2055 results = res.getValue();
2056 resultID = res.getID();
2057 } catch (LDAPReferralException e) {
2058 return performExtendedReferrals( e, cons, op );
2059 } finally {
2060 releaseResponseListener (myListener);
2061 }
2062 return new LDAPExtendedOperation( resultID, results );
2063 }
2064
2065 /**
2066 * Performs an extended operation on the directory. Extended operations
2067 * are part of version 3 of the LDAP protocol.<P>
2068 *
2069 * Note that in order for the extended operation to work, the server
2070 * that you are connecting to must support LDAP v3 and must be configured
2071 * to process the specified extended operation.
2072 *
2073 * @param op LDAPExtendedOperation object specifying the OID of the
2074 * extended operation and the data to use in the operation
2075 * @param queue handler for messages returned from a server in response
2076 * to this request. If it is null, a listener object is created internally.
2077 * @exception LDAPException Failed to execute the operation
2078 * @return LDAPExtendedOperation object representing the extended response
2079 * returned by the server.
2080 * @see org.ietf.ldap.LDAPExtendedOperation
2081 */
2082 public LDAPResponseQueue extendedOperation(
2083 LDAPExtendedOperation op,
2084 LDAPResponseQueue queue )
2085 throws LDAPException {
2086 return extendedOperation( op, queue, _defaultConstraints );
2087 }
2088
2089 /**
2090 * Performs an extended operation on the directory. Extended operations
2091 * are part of version 3 of the LDAP protocol.<P>
2092 *
2093 * Note that in order for the extended operation to work, the server
2094 * that you are connecting to must support LDAP v3 and must be configured
2095 * to process the specified extended operation.
2096 *
2097 * @param op LDAPExtendedOperation object specifying the OID of the
2098 * extended operation and the data to use in the operation
2099 * @param queue handler for messages returned from a server in response
2100 * to this request. If it is null, a listener object is created internally.
2101 * @param cons the set of preferences to apply to this operation
2102 * @exception LDAPException Failed to execute the operation
2103 * @return LDAPExtendedOperation object representing the extended response
2104 * returned by the server.
2105 * @see org.ietf.ldap.LDAPExtendedOperation
2106 */
2107 public LDAPResponseQueue extendedOperation(
2108 LDAPExtendedOperation op,
2109 LDAPResponseQueue queue,
2110 LDAPConstraints cons )
2111 throws LDAPException {
2112 return null;
2113 }
2114
2115 /**
2116 * Finalize method, which disconnects from the LDAP server
2117 * @exception LDAPException Thrown on error in disconnecting
2118 */
2119 protected void finalize() throws LDAPException {
2120 if (isConnected()) {
2121 disconnect();
2122 }
2123 }
2124
2125 /**
2126 * Returns the distinguished name (DN) used for authentication over
2127 * this connection.
2128 * @return distinguished name used for authentication over this connection.
2129 */
2130 public String getAuthenticationDN () {
2131 return _boundDN;
2132 }
2133
2134 /**
2135 * Returns the password used for authentication over this connection.
2136 * @return password used for authentication over this connection.
2137 */
2138 byte[] getAuthenticationPassword () {
2139 return _boundPasswd;
2140 }
2141
2142
2143 /**
2144 * Gets the authentication method used to bind:<BR>
2145 * "none", "simple", or "sasl"
2146 *
2147 * @return the authentication method, or "none"
2148 */
2149 public String getAuthenticationMethod() {
2150 return isConnected() ? _authMethod : "none";
2151 }
2152
2153 /**
2154 * Gets the <CODE>LDAPCache</CODE> object associated with
2155 * the current <CODE>LDAPConnection</CODE> object.
2156 * <P>
2157 *
2158 * @return the <CODE>LDAPCache</CODE> object representing
2159 * the cache that the current connection should use
2160 * @see org.ietf.ldap.LDAPCache
2161 * @see org.ietf.ldap.LDAPConnection#setCache(org.ietf.ldap.LDAPCache)
2162 */
2163 public LDAPCache getCache() {
2164 return _cache;
2165 }
2166
2167 /**
2168 * Returns the maximum time to wait for the connection to be established.
2169 * @return the maximum connect time in seconds or 0 (unlimited)
2170 * @see org.ietf.ldap.LDAPConnection#setConnectTimeout
2171 */
2172 public int getConnectTimeout () {
2173 return _connectTimeout;
2174 }
2175
2176 /**
2177 * Returns the delay in seconds when making concurrent connection attempts to
2178 * multiple servers.
2179 * @return the delay in seconds between connection attempts:<br>
2180 * <CODE>NODELAY_SERIAL</CODE> The serial connection setup policy is enabled
2181 * (no concurrency).<br>
2182 * <CODE>NODELAY_PARALLEL</CODE> The parallel connection setup policy with no delay
2183 * is enabled.<br>
2184 * <CODE>delay > 0</CODE> The parallel connection setup policy with the delay of
2185 * <CODE>delay</CODE> seconds is enabled.
2186 * @see org.ietf.ldap.LDAPConnection#setConnSetupDelay
2187 */
2188 public int getConnSetupDelay () {
2189 return _connSetupDelay;
2190 }
2191
2192 /**
2193 * Returns the set of constraints that apply to all operations
2194 * performed through this connection (unless you specify a different
2195 * set of constraints when calling a method).
2196 * <P>
2197 *
2198 * Note that if you want to get individual constraints (rather than
2199 * getting the
2200 * entire set of constraints), call the <CODE>getOption</CODE> method.
2201 * <P>
2202 *
2203 * Typically, you might call the <CODE>getConstraints</CODE> method
2204 * to create a slightly different set of constraints for a particular
2205 * operation.
2206 * <P>
2207 *
2208 * For example, the following section of code changes the timeout
2209 * to 3000 milliseconds for a specific rename. Rather than construct a new
2210 * set of constraints from scratch, the example gets the current
2211 * settings for the connections and just changes the setting for the
2212 * timeout.
2213 * <P>
2214 *
2215 * Note that this change only applies to the searches performed with this
2216 * custom set of constraints. All other searches performed through this
2217 * connection use the original set of search constraints.
2218 * <P>
2219 *
2220 * <PRE>
2221 * ...
2222 * LDAPConstraints myOptions = ld.getConstraints();
2223 * myOptions.setTimeout( 3000 );
2224 * ld.search( "cn=William Jensen, ou=Accounting, o=Ace Industry,c=US",
2225 * "cn=Will Jensen",
2226 * null,
2227 * false,
2228 * myOptions );
2229 * ...
2230 * </PRE>
2231 *
2232 * @return a copy of the <CODE>LDAPConstraints</CODE> object representing the
2233 * set of constraints that apply (by default) to all operations
2234 * performed through this connection.
2235 * @see org.ietf.ldap.LDAPConstraints
2236 * @see org.ietf.ldap.LDAPConnection#getOption
2237 */
2238 public LDAPConstraints getConstraints () {
2239 return getSearchConstraints();
2240 }
2241
2242 /**
2243 * Returns the host name of the LDAP server to which you are connected.
2244 * @return host name of the LDAP server.
2245 */
2246 public String getHost () {
2247 if (_connMgr != null) {
2248 return _connMgr.getHost();
2249 }
2250 return null;
2251 }
2252
2253 /**
2254 * Gets the stream for reading from the listener socket
2255 *
2256 * @return the stream for reading from the listener socket, or
2257 * <CODE>null</CODE> if there is none
2258 */
2259 public InputStream getInputStream() {
2260 return (_thread != null) ? _thread.getInputStream() : null;
2261 }
2262
2263 /**
2264 * Gets the stream for writing to the socket
2265 *
2266 * @return the stream for writing to the socket, or
2267 * <CODE>null</CODE> if there is none
2268 */
2269 public OutputStream getOutputStream() {
2270 return (_thread != null) ? _thread.getOutputStream() : null;
2271 }
2272
2273 /**
2274 * Returns the port number of the LDAP server to which you are connected.
2275 * @return port number of the LDAP server.
2276 */
2277 public int getPort () {
2278 if (_connMgr != null) {
2279 return _connMgr.getPort();
2280 }
2281 return -1;
2282 }
2283
2284 /**
2285 * Gets a property of a connection. <P>
2286 *
2287 * You can get the following properties for a given connection: <P>
2288 * <UL TYPE="DISC">
2289 * <LI><CODE>LDAP_PROPERTY_SDK</CODE> <P>
2290 * To get the version of this SDK, get this property. The value of
2291 * this property is of the type <CODE>Float</CODE>. <P>
2292 * <LI><CODE>LDAP_PROPERTY_PROTOCOL</CODE> <P>
2293 * To get the highest supported version of the LDAP protocol, get
2294 * this property.
2295 * The value of this property is of the type <CODE>Float</CODE>. <P>
2296 * <LI><CODE>LDAP_PROPERTY_SECURITY</CODE> <P>
2297 * To get a comma-separated list of the types of authentication
2298 * supported, get this property. The value of this property is of the
2299 * type <CODE>String</CODE>. <P>
2300 * </UL>
2301 * <P>
2302 *
2303 * For example, the following section of code gets the version of
2304 * the SDK.<P>
2305 *
2306 * <PRE>
2307 * ...
2308 * Float sdkVersion = ( Float )myConn.getProperty( myConn.LDAP_PROPERTY_SDK );
2309 * System.out.println( "SDK version: " + sdkVersion );
2310 * ... </PRE>
2311 *
2312 * @param name name of the property (for example, <CODE>LDAP_PROPERTY_SDK</CODE>) <P>
2313 *
2314 * @return the value of the property. <P>
2315 *
2316 * Since the return value is an object, you should recast it as the appropriate type.
2317 * (For example, when getting the <CODE>LDAP_PROPERTY_SDK</CODE> property,
2318 * recast the return value as a <CODE>Float</CODE>.) <P>
2319 *
2320 * If you pass this method an unknown property name, the method
2321 * returns null. <P>
2322 *
2323 * @exception LDAPException Unable to get the value of the
2324 * specified property. <P>
2325 *
2326 * @see org.ietf.ldap.LDAPConnection#LDAP_PROPERTY_SDK
2327 * @see org.ietf.ldap.LDAPConnection#LDAP_PROPERTY_PROTOCOL
2328 * @see org.ietf.ldap.LDAPConnection#LDAP_PROPERTY_SECURITY
2329 */
2330 public Object getProperty(String name) throws LDAPException {
2331 return _properties.get( name );
2332 }
2333
2334 /**
2335 * Returns the protocol version that the connection is bound to (which
2336 * currently is 3). If the connection is not bound, it returns 3.
2337 *
2338 * @return the protocol version that the connection is bound to
2339 */
2340 public int getProtocolVersion() {
2341 return _protocolVersion;
2342 }
2343
2344 /**
2345 * Returns an array of the latest controls (if any) from server.
2346 * <P>
2347 * To retrieve the controls from a search result, call the
2348 * <CODE>getResponseControls</CODE> method from the <CODE>LDAPSearchResults
2349 * </CODE> object returned with the result.
2350 * @return an array of the controls returned by an operation, or
2351 * null if none.
2352 * @see org.ietf.ldap.LDAPControl
2353 * @see org.ietf.ldap.LDAPSearchResults#getResponseControls
2354 */
2355 public LDAPControl[] getResponseControls() {
2356 LDAPControl[] controls = null;
2357
2358 /* Get the latest controls returned for our thread */
2359 synchronized(_responseControlTable) {
2360 Vector<LDAPResponseControl> responses = _responseControlTable.get(_thread);
2361
2362 if (responses != null) {
2363 // iterate through each response control
2364 for (int i=0,size=responses.size(); i<size; i++) {
2365 LDAPResponseControl responseObj = responses.elementAt(i);
2366
2367 // check if the response belongs to this connection
2368 if (responseObj.getConnection().equals(this)) {
2369 controls = responseObj.getControls();
2370 responses.removeElementAt(i);
2371 break;
2372 }
2373 }
2374 }
2375 }
2376
2377 return controls;
2378 }
2379
2380 /**
2381 * Returns an array of the latest controls associated with the
2382 * particular request. Used internally by LDAPSearchResults to
2383 * get response controls returned for a search request.
2384 * <P>
2385 * @param msdid Message ID
2386 */
2387 LDAPControl[] getResponseControls(int msgID) {
2388 LDAPControl[] controls = null;
2389
2390 /* Get the latest controls returned for our thread */
2391 synchronized(_responseControlTable) {
2392 Vector<LDAPResponseControl> responses = _responseControlTable.get(_thread);
2393
2394 if (responses != null) {
2395 // iterate through each response control
2396 for (int i=0,size=responses.size(); i<size; i++) {
2397 LDAPResponseControl responseObj = responses.elementAt(i);
2398
2399 // check if the response matches msgID
2400 if (responseObj.getMsgID() == msgID) {
2401 controls = responseObj.getControls();
2402 responses.removeElementAt(i);
2403 break;
2404 }
2405 }
2406 }
2407 }
2408
2409 return controls;
2410 }
2411
2412 /**
2413 * Returns the callback handler, if any, specified on binding with a
2414 * SASL mechanism
2415 *
2416 * @return the callback handler, if any, specified on binding with a
2417 * SASL mechanism
2418 */
2419 public CallbackHandler getSaslBindCallbackHandler() {
2420 return _saslCallbackHandler;
2421 }
2422
2423 /**
2424 * Returns the properties, if any, specified on binding with a
2425 * SASL mechanism
2426 *
2427 * @return the properties, if any, specified on binding with a
2428 * SASL mechanism
2429 */
2430 public Properties getSaslBindProperties() {
2431 return _securityProperties;
2432 }
2433
2434 /**
2435 * Returns the set of search constraints that apply to all searches
2436 * performed through this connection (unless you specify a different
2437 * set of search constraints when calling the <CODE>search</CODE>
2438 * method).
2439 * <P>
2440 *
2441 * Note that if you want to get individual constraints (rather than
2442 * getting the
2443 * entire set of constraints), call the <CODE>getOption</CODE> method.
2444 * <P>
2445 *
2446 * Typically, you might call the <CODE>getSearchConstraints</CODE> method
2447 * to create a slightly different set of search constraints
2448 * to apply to a particular search.
2449 * <P>
2450 *
2451 * For example, the following section of code changes the maximum number
2452 * of results to 10 for a specific search. Rather than construct a new
2453 * set of search constraints from scratch, the example gets the current
2454 * settings for the connections and just changes the setting for the
2455 * maximum results.
2456 * <P>
2457 *
2458 * Note that this change only applies to the searches performed with this
2459 * custom set of constraints. All other searches performed through this
2460 * connection use the original set of search constraints.
2461 * <P>
2462 *
2463 * <PRE>
2464 * ...
2465 * LDAPSearchConstraints myOptions = ld.getSearchConstraints();
2466 * myOptions.setMaxResults( 10 );
2467 * String[] myAttrs = { "objectclass" };
2468 * LDAPSearchResults myResults = ld.search( "o=Ace Industry,c=US",
2469 * LDAPConnection.SCOPE_SUB,
2470 * "(objectclass=*)",
2471 * myAttrs,
2472 * false,
2473 * myOptions );
2474 * ...
2475 * </PRE>
2476 *
2477 * @return a copy of the <CODE>LDAPSearchConstraints</CODE> object
2478 * representing the set of search constraints that apply (by default) to
2479 * all searches performed through this connection.
2480 * @see org.ietf.ldap.LDAPSearchConstraints
2481 * @see org.ietf.ldap.LDAPConnection#getOption
2482 * @see org.ietf.ldap.LDAPConnection#search(java.lang.String, int, java.lang.String, java.lang.String[], boolean, org.ietf.ldap.LDAPSearchConstraints)
2483 */
2484 public LDAPSearchConstraints getSearchConstraints () {
2485 return (LDAPSearchConstraints)_defaultConstraints.clone();
2486 }
2487
2488 /**
2489 * Gets the object representing the socket factory used to establish
2490 * a connection to the LDAP server.
2491 * <P>
2492 *
2493 * @return the object representing the socket factory used to
2494 * establish a connection to a server.
2495 * @see org.ietf.ldap.LDAPSocketFactory
2496 * @see org.ietf.ldap.LDAPSSLSocketFactory
2497 * @see org.ietf.ldap.LDAPConnection#setSocketFactory(org.ietf.ldap.LDAPSocketFactory)
2498 */
2499 public LDAPSocketFactory getSocketFactory () {
2500 return _factory;
2501 }
2502
2503 /**
2504 * Indicates whether this client has authenticated to the LDAP server
2505 * (other than anonymously with simple bind)
2506 *
2507 * @return <CODE>false</CODE> initially, <CODE>false</CODE> upon a bind
2508 * request, and <CODE>true</CODE> after successful completion of the last
2509 * outstanding non-anonymous simple bind
2510 */
2511 public boolean isBound() {
2512 if (_bound) {
2513 if ((_boundDN == null) || _boundDN.equals("") ||
2514 (_boundPasswd == null) || (_boundPasswd.length < 1)) {
2515 return false;
2516 }
2517 }
2518 return _bound;
2519 }
2520
2521 /**
2522 * Indicates if the connection represented by this object
2523 * is open at this time
2524 *
2525 * @return <CODE>true</CODE> if connected to an LDAP server over this
2526 * connection.
2527 * If not connected to an LDAP server, returns <CODE>false</CODE>.
2528 */
2529 public boolean isConnected() {
2530 // This is the hack: If the user program calls isConnected() when
2531 // the thread is about to shut down, the isConnected might get called
2532 // before the deregisterConnection(). We add the yield() so that
2533 // the deregisterConnection() will get called first.
2534 // This problem only exists on Solaris.
2535 Thread.yield();
2536 return (_thread != null);
2537 }
2538
2539 /**
2540 * Indicates if the connection is currently protected by TLS
2541 *
2542 * @return <CODE>true</CODE> if the connection is currently protected
2543 * by TLS; if not connected to an LDAP server, returns <CODE>false</CODE>.
2544 */
2545 public boolean isTLS() {
2546 return false;
2547 }
2548
2549 /**
2550 * Makes a single change to an existing entry in the directory
2551 * (for example, changes the value of an attribute, adds a new
2552 * attribute value, or removes an existing attribute value). <P>
2553 *
2554 * Use the <CODE>LDAPModification</CODE> object to specify the change
2555 * to make and the <CODE>LDAPAttribute</CODE> object
2556 * to specify the attribute value to change. The
2557 * <CODE>LDAPModification</CODE> object allows you add an attribute
2558 * value, change an attibute value, or remove an attribute
2559 * value. <P>
2560 *
2561 * For example, the following section of code changes Barbara Jensen's email
2562 * address in the directory to [email protected]. <P>
2563 *
2564 * <PRE>
2565 * ...
2566 * String myEntryDN = "cn=Barbara Jensen,ou=Product Development,o=Ace Industry,c=US";
2567 *
2568 * LDAPAttribute attrEmail = new LDAPAttribute( "mail", "[email protected]" );
2569 * LDAPModification singleChange = new LDAPModification( LDAPModification.REPLACE, attrEmail );
2570 *
2571 * myConn.modify( myEntryDN, singleChange );
2572 * ... </PRE>
2573 *
2574 * @param DN the distinguished name of the entry to modify
2575 * @param mod a single change to make to the entry
2576 * @exception LDAPException Failed to make the specified change to the
2577 * directory entry.
2578 * @see org.ietf.ldap.LDAPModification
2579 */
2580 public void modify( String DN, LDAPModification mod ) throws LDAPException {
2581 modify( DN, mod, _defaultConstraints );
2582 }
2583
2584 /**
2585 * Makes a single change to an existing entry in the directory and
2586 * allows you to specify preferences for this LDAP modify operation
2587 * by using an <CODE>LDAPConstraints</CODE> object. For
2588 * example, you can specify whether or not to follow referrals.
2589 * You can also apply LDAP v3 controls to the operation.
2590 * <P>
2591 *
2592 * @param DN the distinguished name of the entry to modify
2593 * @param mod a single change to make to the entry
2594 * @param cons the set of preferences to apply to this operation
2595 * @exception LDAPException Failed to make the specified change to the
2596 * directory entry.
2597 * @see org.ietf.ldap.LDAPModification
2598 * @see org.ietf.ldap.LDAPConstraints
2599 */
2600 public void modify( String DN, LDAPModification mod,
2601 LDAPConstraints cons ) throws LDAPException {
2602 LDAPModification[] mods = { mod };
2603 modify( DN, mods, cons );
2604 }
2605
2606 /**
2607 * Makes a set of changes to an existing entry in the directory
2608 * (for example, changes attribute values, adds new attribute values,
2609 * or removes existing attribute values). <P>
2610 *
2611 * Use an array of <CODE>LDAPModification</CODE> objects to specify the
2612 * changes to make. Each change must be specified by
2613 * an <CODE>LDAPModification</CODE> object, and you must specify each
2614 * attribute value to modify, add, or remove by an <CODE>LDAPAttribute</CODE>
2615 * object. <P>
2616 *
2617 * @param DN the distinguished name of the entry to modify
2618 * @param mods an array of objects representing the changes to make
2619 * to the entry
2620 * @exception LDAPException Failed to make the specified changes to the
2621 * directory entry.
2622 * @see org.ietf.ldap.LDAPModification
2623 */
2624 public void modify( String DN, LDAPModification[] mods )
2625 throws LDAPException {
2626 modify( DN, mods, _defaultConstraints );
2627 }
2628
2629 /**
2630 * Makes a set of changes to an existing entry in the directory and
2631 * allows you to specify preferences for this LDAP modify operation
2632 * by using an <CODE>LDAPConstraints</CODE> object. For
2633 * example, you can specify whether or not to follow referrals.
2634 * You can also apply LDAP v3 controls to the operation.
2635 * <P>
2636 *
2637 * @param DN the distinguished name of the entry to modify
2638 * @param mods an array of objects representing the changes to make
2639 * to the entry
2640 * @param cons the set of preferences to apply to this operation
2641 * @exception LDAPException Failed to make the specified changes to the
2642 * directory entry.
2643 * @see org.ietf.ldap.LDAPModification
2644 * @see org.ietf.ldap.LDAPConstraints
2645 */
2646 public void modify( String DN, LDAPModification[] mods,
2647 LDAPConstraints cons ) throws LDAPException {
2648 internalBind (cons);
2649
2650 LDAPResponseQueue myListener = getResponseListener ();
2651 LDAPMessage response = null;
2652 try {
2653 sendRequest (new JDAPModifyRequest (DN, mods), myListener, cons);
2654 response = myListener.getResponse();
2655 checkMsg (response);
2656 } catch (LDAPReferralException e) {
2657 performReferrals(e, cons, JDAPProtocolOp.MODIFY_REQUEST,
2658 DN, 0, null, null, false, mods, null, null, null);
2659 } finally {
2660 releaseResponseListener (myListener);
2661 }
2662 }
2663
2664 /**
2665 * Makes a single change to an existing entry in the directory. For
2666 * example, it changes the value of an attribute, adds a new attribute
2667 * value, or removes an existing attribute value). <BR>
2668 * The LDAPModification object specifies both the change to make and
2669 * the LDAPAttribute value to be changed.
2670 *
2671 * @param dn distinguished name of the entry to modify
2672 * @param mod a single change to make to an entry
2673 * @param listener handler for messages returned from a server in response
2674 * to this request. If it is null, a listener object is created internally.
2675 * @return LDAPResponseQueue handler for messages returned from a server
2676 * in response to this request.
2677 * @exception LDAPException Failed to send request.
2678 * @see org.ietf.ldap.LDAPModification
2679 * @see org.ietf.ldap.LDAPResponseQueue
2680 */
2681 public LDAPResponseQueue modify( String dn,
2682 LDAPModification mod,
2683 LDAPResponseQueue listener )
2684 throws LDAPException{
2685
2686 return modify( dn, mod, listener, _defaultConstraints );
2687 }
2688
2689 /**
2690 * Makes a single change to an existing entry in the directory. For
2691 * example, it changes the value of an attribute, adds a new attribute
2692 * value, or removes an existing attribute value). <BR>
2693 * The LDAPModification object specifies both the change to make and
2694 * the LDAPAttribute value to be changed.
2695 *
2696 * @param dn distinguished name of the entry to modify
2697 * @param mod a single change to make to an entry
2698 * @param listener handler for messages returned from a server in response
2699 * to this request. If it is null, a listener object is created internally.
2700 * @param cons constraints specific to the operation
2701 * @return LDAPResponseQueue handler for messages returned from a server
2702 * in response to this request.
2703 * @exception LDAPException Failed to send request.
2704 * @see org.ietf.ldap.LDAPModification
2705 * @see org.ietf.ldap.LDAPResponseQueue
2706 * @see org.ietf.ldap.LDAPConstraints
2707 */
2708 public LDAPResponseQueue modify( String dn,
2709 LDAPModification mod,
2710 LDAPResponseQueue listener,
2711 LDAPConstraints cons )
2712 throws LDAPException{
2713 if (cons == null) {
2714 cons = _defaultConstraints;
2715 }
2716
2717 internalBind (cons);
2718
2719 if (listener == null) {
2720 listener = new LDAPResponseQueue(/*asynchOp=*/true);
2721 }
2722
2723 LDAPModification[] modList = { mod };
2724 sendRequest (new JDAPModifyRequest (dn, modList), listener, cons);
2725
2726 return listener;
2727 }
2728
2729 /**
2730 * Reads the entry for the specified distiguished name (DN) and retrieves
2731 * all attributes for the entry.
2732 * <P>
2733 *
2734 * For example, the following section of code reads the entry for
2735 * Barbara Jensen and retrieves all attributes for that entry.
2736 * <P>
2737 *
2738 * <PRE>
2739 * String findDN = "cn=Barbara Jensen,ou=Product Development,o=Ace Industry,c=US";
2740 * LDAPEntry foundEntry = null;
2741 * try {
2742 * foundEntry = myConn.read( findDN );
2743 * } catch ( LDAPException e ) {
2744 * switch( e.getResultCode() ) {
2745 * case e.NO_SUCH_OBJECT:
2746 * System.out.println( "The specified entry does not exist." );
2747 * break;
2748 * case e.LDAP_PARTIAL_RESULTS:
2749 * System.out.println( "Entry served by a different LDAP server." );
2750 * break;
2751 * case e.INSUFFICIENT_ACCESS_RIGHTS:
2752 * System.out.println( "You do not have the access rights to perform this operation." );
2753 * break;
2754 * default:
2755 * System.out.println( "Error number: " + e.getResultCode() );
2756 * System.out.println( "Could not read the specified entry." );
2757 * break;
2758 * }
2759 * return;
2760 * }
2761 * System.out.println( "Found the specified entry." );
2762 * </PRE>
2763 *
2764 * @param DN distinguished name of the entry to retrieve
2765 * @exception LDAPException Failed to find or read the specified entry
2766 * from the directory.
2767 * @return LDAPEntry returns the specified entry or raises an exception
2768 * if the entry is not found.
2769 */
2770 public LDAPEntry read( String DN ) throws LDAPException {
2771 return read( DN, null, _defaultConstraints );
2772 }
2773
2774 /**
2775 * Reads the entry for the specified distiguished name (DN) and retrieves all
2776 * attributes for the entry. This method allows the user to specify the
2777 * preferences for the read operation.
2778 * <P>
2779 *
2780 * For example, the following section of code reads the entry for
2781 * Barbara Jensen and retrieves all attributes for that entry.
2782 * <P>
2783 *
2784 * <PRE>
2785 * String findDN = "cn=Barbara Jensen,ou=Product Development,o=Ace Industry,c=US";
2786 * LDAPEntry foundEntry = null;
2787 * try {
2788 * foundEntry = myConn.read( findDN );
2789 * } catch ( LDAPException e ) {
2790 * switch( e.getResultCode() ) {
2791 * case e.NO_SUCH_OBJECT:
2792 * System.out.println( "The specified entry does not exist." );
2793 * break;
2794 * case e.LDAP_PARTIAL_RESULTS:
2795 * System.out.println( "Entry served by a different LDAP server." );
2796 * break;
2797 * case e.INSUFFICIENT_ACCESS_RIGHTS:
2798 * System.out.println( "You do not have the access rights to perform this operation." );
2799 * break;
2800 * default:
2801 * System.out.println( "Error number: " + e.getResultCode() );
2802 * System.out.println( "Could not read the specified entry." );
2803 * break;
2804 * }
2805 * return;
2806 * }
2807 * System.out.println( "Found the specified entry." );
2808 * </PRE>
2809 *
2810 * @param DN distinguished name of the entry to retrieve
2811 * @param cons preferences for the read operation
2812 * @exception LDAPException Failed to find or read the specified entry
2813 * from the directory.
2814 * @return LDAPEntry returns the specified entry or raises an exception
2815 * if the entry is not found.
2816 */
2817 public LDAPEntry read( String DN, LDAPSearchConstraints cons )
2818 throws LDAPException {
2819 return read( DN, null, cons );
2820 }
2821
2822 /**
2823 * Reads the entry for the specified distinguished name (DN) and
2824 * retrieves only the specified attributes from the entry.
2825 * <P>
2826 *
2827 * For example, the following section of code reads the entry for
2828 * Barbara Jensen and retrieves only the <CODE>cn</CODE> and
2829 * <CODE>sn</CODE> attributes.
2830 * The example prints out all attributes that have been retrieved
2831 * (the two specified attributes).
2832 * <P>
2833 *
2834 * <PRE>
2835 * String findDN = "cn=Barbara Jensen,ou=Product Development,o=Ace Industry,c=US";
2836 * LDAPEntry foundEntry = null;
2837 * String getAttrs[] = { "cn", "sn" };
2838 * try {
2839 * foundEntry = myConn.read( findDN, getAttrs );
2840 * } catch ( LDAPException e ) {
2841 * switch( e.getResultCode() ) {
2842 * case e.NO_SUCH_OBJECT:
2843 * System.out.println( "The specified entry does not exist." );
2844 * break;
2845 * case e.LDAP_PARTIAL_RESULTS:
2846 * System.out.println( "Entry served by a different LDAP server." );
2847 * break;
2848 * case e.INSUFFICIENT_ACCESS_RIGHTS:
2849 * System.out.println( "You do not have the access " +
2850 * "rights to perform this operation." );
2851 * break;
2852 * default:
2853 * System.out.println( "Error number: " + e.getResultCode() );
2854 * System.out.println( "Could not read the specified entry." );
2855 * break;
2856 * }
2857 * return;
2858 * }
2859 *
2860 * LDAPAttributeSet foundAttrs = foundEntry.getAttributeSet();
2861 * int size = foundAttrs.size();
2862 * Iterator enumAttrs = foundAttrs.iterator();
2863 * System.out.println( "Attributes: " );
2864 *
2865 * while ( enumAttrs.hasMore() ) {
2866 * LDAPAttribute anAttr = ( LDAPAttribute )enumAttrs.next();
2867 * String attrName = anAttr.getName();
2868 * System.out.println( "\t" + attrName );
2869 * Enumeration enumVals = anAttr.getStringValues();
2870 * while ( enumVals.hasMoreElements() ) {
2871 * String aVal = ( String )enumVals.nextElement();
2872 * System.out.println( "\t\t" + aVal );
2873 * }
2874 * }
2875 * </PRE>
2876 *
2877 * @param DN distinguished name of the entry to retrieve
2878 * @param attrs names of attributes to retrieve
2879 * @return LDAPEntry returns the specified entry (or raises an
2880 * exception if the entry is not found).
2881 * @exception LDAPException Failed to read the specified entry from
2882 * the directory.
2883 */
2884 public LDAPEntry read( String DN, String attrs[] ) throws LDAPException {
2885 return read( DN, attrs, _defaultConstraints );
2886 }
2887
2888 /**
2889 * Reads the entry for the specified distinguished name (DN) and
2890 * retrieves only the specified attributes from the entry.
2891 * <P>
2892 *
2893 * For example, the following section of code reads the entry for
2894 * Barbara Jensen and retrieves only the <CODE>cn</CODE> and
2895 * <CODE>sn</CODE> attributes.
2896 * The example prints out all attributes that have been retrieved
2897 * (the two specified attributes).
2898 * <P>
2899 *
2900 * <PRE>
2901 * String findDN = "cn=Barbara Jensen,ou=Product Development,o=Ace Industry,c=US";
2902 * LDAPEntry foundEntry = null;
2903 * String getAttrs[] = { "cn", "sn" };
2904 * try {
2905 * foundEntry = myConn.read( findDN, getAttrs );
2906 * } catch ( LDAPException e ) {
2907 * switch( e.getResultCode() ) {
2908 * case e.NO_SUCH_OBJECT:
2909 * System.out.println( "The specified entry does not exist." );
2910 * break;
2911 * case e.LDAP_PARTIAL_RESULTS:
2912 * System.out.println( "Entry served by a different LDAP server." );
2913 * break;
2914 * case e.INSUFFICIENT_ACCESS_RIGHTS:
2915 * System.out.println( "You do not have the access " +
2916 * "rights to perform this operation." );
2917 * break;
2918 * default:
2919 * System.out.println( "Error number: " + e.getResultCode() );
2920 * System.out.println( "Could not read the specified entry." );
2921 * break;
2922 * }
2923 * return;
2924 * }
2925 *
2926 * LDAPAttributeSet foundAttrs = foundEntry.getAttributeSet();
2927 * int size = foundAttrs.size();
2928 * Iterator enumAttrs = foundAttrs.iterator();
2929 * System.out.println( "Attributes: " );
2930 *
2931 * while ( enumAttrs.hasMore() ) {
2932 * LDAPAttribute anAttr = ( LDAPAttribute )enumAttrs.next();
2933 * String attrName = anAttr.getName();
2934 * System.out.println( "\t" + attrName );
2935 * Enumeration enumVals = anAttr.getStringValues();
2936 * while ( enumVals.hasMoreElements() ) {
2937 * String aVal = ( String )enumVals.nextElement();
2938 * System.out.println( "\t\t" + aVal );
2939 * }
2940 * }
2941 * </PRE>
2942 *
2943 * @param DN distinguished name of the entry to retrieve
2944 * @param attrs names of attributes to retrieve
2945 * @param cons preferences for the read operation
2946 * @return LDAPEntry returns the specified entry (or raises an
2947 * exception if the entry is not found).
2948 * @exception LDAPException Failed to read the specified entry from
2949 * the directory.
2950 */
2951 public LDAPEntry read( String DN, String attrs[],
2952 LDAPSearchConstraints cons ) throws LDAPException {
2953 LDAPSearchResults results =
2954 search (DN, SCOPE_BASE,
2955 "(|(objectclass=*)(objectclass=ldapsubentry))",
2956 attrs, false, cons);
2957 if ( results == null ) {
2958 return null;
2959 }
2960 LDAPEntry entry = results.next();
2961
2962 // cleanup required for referral connections
2963 while( results.hasMore() ) {
2964 results.next();
2965 }
2966
2967 return entry;
2968 }
2969
2970 /**
2971 * Reads the entry specified by the LDAP URL. <P>
2972 *
2973 * When you call this method, a new connection is created automatically,
2974 * using the host and port specified in the URL. After finding the entry,
2975 * the method closes this connection (in other words, it disconnects from
2976 * the LDAP server). <P>
2977 *
2978 * If the URL specifies a filter and scope, these are not used.
2979 * Of the information specified in the URL, this method only uses
2980 * the LDAP host name and port number, the base distinguished name (DN),
2981 * and the list of attributes to return. <P>
2982 *
2983 * The method returns the entry specified by the base DN. <P>
2984 *
2985 * (Note: If you want to search for more than one entry, use the
2986 * <CODE>search( LDAPUrl )</CODE> method instead.) <P>
2987 *
2988 * For example, the following section of code reads the entry specified
2989 * by the LDAP URL.
2990 * <P>
2991 *
2992 * <PRE>
2993 * String flatURL = "ldap://alway.mcom.com:3890/cn=Barbara Jenson,ou=Product Development,o=Ace Industry,c=US?cn,sn,mail";
2994 * LDAPUrl myURL;
2995 * try {
2996 * myURL = new LDAPUrl( flatURL );
2997 * } catch ( java.net.MalformedURLException e ) {
2998 * System.out.println( "BAD URL!!! BAD, BAD, BAD URL!!!" );
2999 * return;
3000 * }
3001 * LDAPEntry myEntry = null;
3002 * try {
3003 * myEntry = myConn.read( myURL );
3004 * } catch ( LDAPException e ) {
3005 * int errCode = e.getResultCode();
3006 * switch( errCode ) {
3007 * case ( e.NO_SUCH_OBJECT ):
3008 * System.out.println( "The specified entry " + myDN +
3009 * " does not exist in the directory." );
3010 * return;
3011 * default:
3012 * System.out.println( "An internal error occurred." );
3013 * return;
3014 * }
3015 * }
3016 * </PRE>
3017 *
3018 * @param toGet LDAP URL specifying the entry to read
3019 * @return LDAPEntry returns the entry specified by the URL (or raises
3020 * an exception if the entry is not found).
3021 * @exception LDAPException Failed to read the specified entry from
3022 * the directory.
3023 * @see org.ietf.ldap.LDAPUrl
3024 * @see org.ietf.ldap.LDAPConnection#search(org.ietf.ldap.LDAPUrl)
3025 */
3026 public static LDAPEntry read( LDAPUrl toGet ) throws LDAPException {
3027 return read( toGet, null );
3028 }
3029
3030 /**
3031 * Reads the entry specified by the LDAP URL. <P>
3032 *
3033 * When you call this method, a new connection is created automatically,
3034 * using the host and port specified in the URL. After finding the entry,
3035 * the method closes this connection (in other words, it disconnects from
3036 * the LDAP server). <P>
3037 *
3038 * If the URL specifies a filter and scope, these are not used.
3039 * Of the information specified in the URL, this method only uses
3040 * the LDAP host name and port number, the base distinguished name (DN),
3041 * and the list of attributes to return. <P>
3042 *
3043 * The method returns the entry specified by the base DN. <P>
3044 *
3045 * (Note: If you want to search for more than one entry, use the
3046 * <CODE>search( LDAPUrl )</CODE> method instead.) <P>
3047 *
3048 * For example, the following section of code reads the entry specified
3049 * by the LDAP URL.
3050 * <P>
3051 *
3052 * <PRE>
3053 * String flatURL = "ldap://alway.mcom.com:3890/cn=Barbara Jenson,ou=Product Development,o=Ace Industry,c=US?cn,sn,mail";
3054 * LDAPUrl myURL;
3055 * try {
3056 * myURL = new LDAPUrl( flatURL );
3057 * } catch ( java.net.MalformedURLException e ) {
3058 * System.out.println( "BAD URL!!! BAD, BAD, BAD URL!!!" );
3059 * return;
3060 * }
3061 * LDAPEntry myEntry = null;
3062 * try {
3063 * myEntry = myConn.read( myURL );
3064 * } catch ( LDAPException e ) {
3065 * int errCode = e.getResultCode();
3066 * switch( errCode ) {
3067 * case ( e.NO_SUCH_OBJECT ):
3068 * System.out.println( "The specified entry " + myDN +
3069 * " does not exist in the directory." );
3070 * return;
3071 * default:
3072 * System.out.println( "An internal error occurred." );
3073 * return;
3074 * }
3075 * }
3076 * </PRE>
3077 *
3078 * @param toGet LDAP URL specifying the entry to read
3079 * @param cons preferences for the read operation
3080 * @return LDAPEntry returns the entry specified by the URL (or raises
3081 * an exception if the entry is not found).
3082 * @exception LDAPException Failed to read the specified entry from
3083 * the directory.
3084 * @see org.ietf.ldap.LDAPUrl
3085 * @see org.ietf.ldap.LDAPConnection#search(org.ietf.ldap.LDAPUrl)
3086 */
3087 public static LDAPEntry read( LDAPUrl toGet,
3088 LDAPSearchConstraints cons )
3089 throws LDAPException {
3090 if (cons == null) {
3091 cons = new LDAPSearchConstraints();
3092 }
3093 String host = toGet.getHost ();
3094 int port = toGet.getPort();
3095
3096 if (host == null) {
3097 throw new LDAPException ( "no host for connection",
3098 LDAPException.PARAM_ERROR );
3099 }
3100
3101 String[] attributes = toGet.getAttributeArray ();
3102 String DN = toGet.getDN();
3103 LDAPEntry returnValue;
3104
3105 LDAPConnection connection = new LDAPConnection ();
3106 if (toGet.isSecure()) {
3107 LDAPSocketFactory factory = LDAPUrl.getSocketFactory();
3108 if (factory == null) {
3109 throw new LDAPException("No socket factory for LDAPUrl",
3110 LDAPException.OTHER);
3111 }
3112 connection.setSocketFactory(factory);
3113 }
3114 connection.connect (host, port);
3115
3116 returnValue = connection.read (DN, attributes, cons);
3117 connection.disconnect ();
3118
3119 return returnValue;
3120 }
3121
3122 /**
3123 * Disconnect from the server and then reconnect using the current
3124 * credentials and authentication method
3125 * @exception LDAPException if not previously connected, or if
3126 * there is a failure on disconnecting or on connecting
3127 */
3128 public void reconnect() throws LDAPException {
3129
3130 disconnect();
3131 connect();
3132
3133 if (_saslBinder != null) {
3134 _saslBinder.bind(this, true);
3135 _authMethod = "sasl";
3136 } else {
3137 internalBind (_protocolVersion, true, _defaultConstraints);
3138 }
3139 }
3140
3141 /**
3142 * Deregisters an object so that it will no longer be notified on
3143 * arrival of an unsolicited message from a server. If the object is
3144 * null or was not previously registered for unsolicited notifications,
3145 * the method does nothing.
3146 */
3147 public void removeUnsolicitedNotificationListener(
3148 LDAPUnsolicitedNotificationListener listener ) {
3149 }
3150
3151 /**
3152 * Renames an existing entry in the directory. <P>
3153 *
3154 * You can specify whether or not the original name of the entry is
3155 * retained as a value in the entry. For example, suppose you rename
3156 * the entry "cn=Barbara" to "cn=Babs". You can keep "cn=Barbara"
3157 * as a value in the entry so that the cn attribute has two values: <P>
3158 *
3159 * <PRE>
3160 * cn=Barbara
3161 * cn=Babs
3162 * </PRE>
3163 * The following example renames an entry. The old name of the entry
3164 * is kept as a value in the entry. <P>
3165 *
3166 * <PRE>
3167 * ...
3168 * String myEntryDN = "cn=Barbara Jensen,ou=Product Development,o=Ace Industry,c=US";
3169 * String newRDN = "cn=Babs Jensen";
3170 * myConn.rename( myEntryDN, newRDN, false );
3171 * ... </PRE>
3172 *
3173 * @param DN current distinguished name of the entry
3174 * @param newRDN new relative distinguished name for the entry (for example,
3175 * "cn=newName")
3176 * @param deleteOldRDN if <CODE>true</CODE>, the old name is not retained
3177 * as an attribute value (for example, the attribute value "cn=oldName" is
3178 * removed). If <CODE>false</CODE>, the old name is retained
3179 * as an attribute value (for example, the entry might now have two values
3180 * for the cn attribute: "cn=oldName" and "cn=newName").
3181 * @exception LDAPException Failed to rename the specified entry.
3182 */
3183 public void rename( String DN, String newRDN, boolean deleteOldRDN )
3184 throws LDAPException {
3185 rename( DN, newRDN, null, deleteOldRDN );
3186 }
3187
3188 /**
3189 * Renames an existing entry in the directory. <P>
3190 *
3191 * You can specify whether or not the original name of the entry is
3192 * retained as a value in the entry. For example, suppose you rename
3193 * the entry "cn=Barbara" to "cn=Babs". You can keep "cn=Barbara"
3194 * as a value in the entry so that the cn attribute has two values: <P>
3195 *
3196 * <PRE>
3197 * cn=Barbara
3198 * cn=Babs
3199 * </PRE>
3200 * The following example renames an entry. The old name of the entry
3201 * is kept as a value in the entry. <P>
3202 *
3203 * <PRE>
3204 * ...
3205 * String myEntryDN = "cn=Barbara Jensen,ou=Product Development,o=Ace Industry,c=US";
3206 * String newRDN = "cn=Babs Jensen";
3207 * myConn.rename( myEntryDN, newRDN, false );
3208 * ... </PRE>
3209 *
3210 * @param DN current distinguished name of the entry
3211 * @param newRDN new relative distinguished name for the entry (for example,
3212 * "cn=newName")
3213 * @param deleteOldRDN if <CODE>true</CODE>, the old name is not retained
3214 * as an attribute value (for example, the attribute value "cn=oldName" is
3215 * removed). If <CODE>false</CODE>, the old name is retained
3216 * as an attribute value (for example, the entry might now have two values
3217 * for the cn attribute: "cn=oldName" and "cn=newName").
3218 * @param cons the set of preferences to apply to this operation
3219 * @exception LDAPException Failed to rename the specified entry.
3220 */
3221 public void rename( String DN, String newRDN, boolean deleteOldRDN,
3222 LDAPConstraints cons )
3223 throws LDAPException {
3224 rename( DN, newRDN, null, deleteOldRDN, cons );
3225 }
3226
3227 /**
3228 * Renames an existing entry in the directory and (optionally)
3229 * changes the location of the entry in the directory tree.<P>
3230 *
3231 * <B>NOTE: </B>Netscape Directory Server 3.0 does not support the
3232 * capability to move an entry to a different location in the
3233 * directory tree. If you specify a value for the <CODE>newParentDN</CODE>
3234 * argument, an <CODE>LDAPException</CODE> will be thrown.
3235 * <P>
3236 *
3237 * @param DN current distinguished name of the entry
3238 * @param newRDN new relative distinguished name for the entry (for example,
3239 * "cn=newName")
3240 * @param newParentDN if not null, the distinguished name for the
3241 * entry under which the entry should be moved (for example, to move
3242 * an entry under the Accounting subtree, specify this argument as
3243 * "ou=Accounting, o=Ace Industry, c=US")
3244 * @param deleteOldRDN if <CODE>true</CODE>, the old name is not retained
3245 * as an attribute value (for example, the attribute value "cn=oldName" is
3246 * removed). If <CODE>false</CODE>, the old name is retained
3247 * as an attribute value (for example, the entry might now have two values
3248 * for the cn attribute: "cn=oldName" and "cn=newName").
3249 * @exception LDAPException Failed to rename the specified entry.
3250 */
3251 public void rename( String DN,
3252 String newRDN,
3253 String newParentDN,
3254 boolean deleteOldRDN ) throws LDAPException {
3255 rename( DN, newRDN, newParentDN, deleteOldRDN, _defaultConstraints );
3256 }
3257
3258 /**
3259 * Renames an existing entry in the directory and (optionally)
3260 * changes the location of the entry in the directory tree. Also
3261 * allows you to specify preferences for this LDAP modify DN operation
3262 * by using an <CODE>LDAPConstraints</CODE> object. For
3263 * example, you can specify whether or not to follow referrals.
3264 * You can also apply LDAP v3 controls to the operation.
3265 * <P>
3266 *
3267 * <B>NOTE: </B>Netscape Directory Server 3.0 does not support the
3268 * capability to move an entry to a different location in the
3269 * directory tree. If you specify a value for the <CODE>newParentDN</CODE>
3270 * argument, an <CODE>LDAPException</CODE> will be thrown.
3271 * <P>
3272 *
3273 * @param DN current distinguished name of the entry
3274 * @param newRDN new relative distinguished name for the entry (for example,
3275 * "cn=newName")
3276 * @param newParentDN if not null, the distinguished name for the
3277 * entry under which the entry should be moved (for example, to move
3278 * an entry under the Accounting subtree, specify this argument as
3279 * "ou=Accounting, o=Ace Industry, c=US")
3280 * @param deleteOldRDN if <CODE>true</CODE>, the old name is not retained
3281 * as an attribute value (for example, the attribute value "cn=oldName" is
3282 * removed). If <CODE>false</CODE>, the old name is retained
3283 * as an attribute value (for example, the entry might now have two values
3284 * for the cn attribute: "cn=oldName" and "cn=newName").
3285 * @param cons the set of preferences to apply to this operation
3286 * @exception LDAPException Failed to rename the specified entry.
3287 * @see org.ietf.ldap.LDAPConstraints
3288 */
3289 public void rename ( String DN,
3290 String newRDN,
3291 String newParentDN,
3292 boolean deleteOldRDN,
3293 LDAPConstraints cons )
3294 throws LDAPException {
3295 internalBind (cons);
3296
3297 LDAPResponseQueue myListener = getResponseListener ();
3298 try {
3299 JDAPModifyRDNRequest request = null;
3300 if ( newParentDN != null ) {
3301 request = new JDAPModifyRDNRequest( DN,
3302 newRDN,
3303 deleteOldRDN,
3304 newParentDN );
3305 } else {
3306 request = new JDAPModifyRDNRequest( DN,
3307 newRDN,
3308 deleteOldRDN );
3309 }
3310 sendRequest (request, myListener, cons);
3311 LDAPMessage response = myListener.getResponse();
3312 checkMsg (response);
3313 } catch (LDAPReferralException e) {
3314 performReferrals(e, cons, JDAPProtocolOp.MODIFY_RDN_REQUEST,
3315 DN, 0, newRDN, null, deleteOldRDN, null, null,
3316 null, null);
3317 } finally {
3318 releaseResponseListener (myListener);
3319 }
3320 }
3321
3322 /**
3323 * Renames an existing entry in the directory.
3324 *
3325 * @param DN current distinguished name of the entry
3326 * @param newRDN new relative distinguished name for the entry
3327 * @param deleteOldRDN if true, the old name is not retained as an
3328 * attribute value
3329 * @param listener handler for messages returned from a server in response
3330 * to this request. If it is null, a listener object is created internally.
3331 * @return LDAPResponseQueue handler for messages returned from a server
3332 * in response to this request.
3333 * @exception LDAPException Failed to send request.
3334 * @see org.ietf.ldap.LDAPResponseQueue
3335 */
3336 public LDAPResponseQueue rename( String DN,
3337 String newRDN,
3338 boolean deleteOldRDN,
3339 LDAPResponseQueue listener )
3340 throws LDAPException{
3341 return rename( DN, newRDN, deleteOldRDN, listener,
3342 _defaultConstraints );
3343 }
3344
3345 /**
3346 * Renames an existing entry in the directory.
3347 *
3348 * @param DN current distinguished name of the entry
3349 * @param newRDN new relative distinguished name for the entry
3350 * @param deleteOldRDN if true, the old name is not retained as an attribute
3351 * value
3352 * @param listener handler for messages returned from a server in response
3353 * to this request. If it is null, a listener object is created internally.
3354 * @param cons constraints specific to the operation
3355 * @return LDAPResponseQueue handler for messages returned from a server
3356 * in response to this request.
3357 * @exception LDAPException Failed to send request.
3358 * @see org.ietf.ldap.LDAPResponseQueue
3359 * @see org.ietf.ldap.LDAPConstraints
3360 */
3361 public LDAPResponseQueue rename( String DN,
3362 String newRDN,
3363 boolean deleteOldRDN,
3364 LDAPResponseQueue listener,
3365 LDAPConstraints cons )
3366 throws LDAPException{
3367 if (cons == null) {
3368 cons = _defaultConstraints;
3369 }
3370
3371 internalBind (cons);
3372
3373 if (listener == null) {
3374 listener = new LDAPResponseQueue(/*asynchOp=*/true);
3375 }
3376
3377 sendRequest (new JDAPModifyRDNRequest (DN, newRDN, deleteOldRDN),
3378 listener, cons);
3379
3380 return listener;
3381 }
3382
3383 /**
3384 * Renames an existing entry in the directory.
3385 *
3386 * @param DN current distinguished name of the entry
3387 * @param newRDN new relative distinguished name for the entry
3388 * @param newParentDN if not null, the distinguished name for the
3389 * entry under which the entry should be moved (for example, to move
3390 * an entry under the Accounting subtree, specify this argument as
3391 * "ou=Accounting, o=Ace Industry, c=US")
3392 * @param deleteOldRDN if true, the old name is not retained as an
3393 * attribute value
3394 * @param listener handler for messages returned from a server in response
3395 * to this request. If it is null, a listener object is created internally.
3396 * @return LDAPResponseQueue handler for messages returned from a server
3397 * in response to this request.
3398 * @exception LDAPException Failed to send request.
3399 * @see org.ietf.ldap.LDAPResponseQueue
3400 */
3401 public LDAPResponseQueue rename( String DN,
3402 String newRDN,
3403 String newParentDN,
3404 boolean deleteOldRDN,
3405 LDAPResponseQueue listener )
3406 throws LDAPException{
3407 return rename( DN, newRDN, newParentDN, deleteOldRDN, listener,
3408 _defaultConstraints );
3409 }
3410
3411 /**
3412 * Renames an existing entry in the directory.
3413 *
3414 * @param DN current distinguished name of the entry
3415 * @param newRDN new relative distinguished name for the entry
3416 * @param newParentDN if not null, the distinguished name for the
3417 * entry under which the entry should be moved (for example, to move
3418 * an entry under the Accounting subtree, specify this argument as
3419 * "ou=Accounting, o=Ace Industry, c=US")
3420 * @param deleteOldRDN if true, the old name is not retained as an
3421 * attribute value
3422 * @param listener handler for messages returned from a server in response
3423 * to this request. If it is null, a listener object is created internally.
3424 * @return LDAPResponseQueue handler for messages returned from a server
3425 * in response to this request.
3426 * @exception LDAPException Failed to send request.
3427 * @see org.ietf.ldap.LDAPResponseQueue
3428 */
3429 public LDAPResponseQueue rename( String DN,
3430 String newRDN,
3431 String newParentDN,
3432 boolean deleteOldRDN,
3433 LDAPResponseQueue listener,
3434 LDAPConstraints cons )
3435 throws LDAPException{
3436 if (cons == null) {
3437 cons = _defaultConstraints;
3438 }
3439
3440 internalBind (cons);
3441
3442 if (listener == null) {
3443 listener = new LDAPResponseQueue(/*asynchOp=*/true);
3444 }
3445
3446 JDAPModifyRDNRequest request;
3447 if ( newParentDN != null ) {
3448 request = new JDAPModifyRDNRequest( DN,
3449 newRDN,
3450 deleteOldRDN,
3451 newParentDN );
3452 } else {
3453 request = new JDAPModifyRDNRequest( DN,
3454 newRDN,
3455 deleteOldRDN );
3456 }
3457 sendRequest( request, listener, cons );
3458
3459 return listener;
3460 }
3461
3462 /**
3463 * Performs the search specified by the LDAP URL. <P>
3464 *
3465 * For example, the following section of code searches for all entries under
3466 * the <CODE>ou=Product Development,o=Ace Industry,c=US</CODE> subtree of a
3467 * directory. The example gets and prints the mail attribute for each entry
3468 * found. <P>
3469 *
3470 * <PRE>
3471 * String flatURL = "ldap://alway.mcom.com:3890/ou=Product Development,o=Ace Industry,c=US?mail?sub?objectclass=*";
3472 * LDAPUrl myURL;
3473 * try {
3474 * myURL = new LDAPUrl( flatURL );
3475 * } catch ( java.net.MalformedURLException e ) {
3476 * System.out.println( "Incorrect URL syntax." );
3477 * return;
3478 * }
3479 *
3480 * LDAPSearchResults myResults = null;
3481 * try {
3482 * myResults = myConn.search( myURL );
3483 * } catch ( LDAPException e ) {
3484 * int errCode = e.getResultCode();
3485 * System.out.println( "LDAPException: return code:" + errCode );
3486 * return;
3487 * }
3488 *
3489 * while ( myResults.hasMore() ) {
3490 * LDAPEntry myEntry = myResults.next();
3491 * String nextDN = myEntry.getDN();
3492 * System.out.println( nextDN );
3493 * LDAPAttributeSet entryAttrs = myEntry.getAttributeSet();
3494 * Iterator attrsInSet = entryAttrs.iterator();
3495 * while ( attrsInSet.hasMore() ) {
3496 * LDAPAttribute nextAttr = (LDAPAttribute)attrsInSet.next();
3497 * String attrName = nextAttr.getName();
3498 * System.out.print( "\t" + attrName + ": " );
3499 * Enumeration valsInAttr = nextAttr.getStringValues();
3500 * while ( valsInAttr.hasMoreElements() ) {
3501 * String nextValue = (String)valsInAttr.nextElement();
3502 * System.out.println( nextValue );
3503 * }
3504 * }
3505 * }
3506 * </PRE>
3507 * <P>
3508 *
3509 * To abandon the search, use the <CODE>abandon</CODE> method.
3510 *
3511 * @param toGet LDAP URL representing the search to perform
3512 * @return LDAPSearchResults the results of the search as an enumeration.
3513 * @exception LDAPException Failed to complete the search specified by
3514 * the LDAP URL.
3515 * @see org.ietf.ldap.LDAPUrl
3516 * @see org.ietf.ldap.LDAPSearchResults
3517 * @see org.ietf.ldap.LDAPConnection#abandon(org.ietf.ldap.LDAPSearchResults)
3518 */
3519 public static LDAPSearchResults search( LDAPUrl toGet )
3520 throws LDAPException {
3521 return search( toGet, null );
3522 }
3523
3524 /**
3525 * Performs the search specified by the LDAP URL. This method also
3526 * allows you to specify constraints for the search (such as the
3527 * maximum number of entries to find or the
3528 * maximum time to wait for search results). <P>
3529 *
3530 * As part of the search constraints, you can specify whether or not you
3531 * want the results delivered all at once or in smaller batches.
3532 * If you specify the results delivered in smaller
3533 * batches, each iteration blocks until the next batch of results is
3534 * returned. <P>
3535 *
3536 * For example, the following section of code retrieves the first 5
3537 * matching entries for the search specified by the LDAP URL. The
3538 * example accomplishes this by creating a new set of search
3539 * constraints where the maximum number of search results is 5. <P>
3540 *
3541 * <PRE>
3542 * LDAPSearchConstraints mySearchConstraints = myConn.getSearchConstraints();
3543 * mySearchConstraints.setMaxResults( 5 );
3544 * String flatURL = "ldap://alway.mcom.com:3890/ou=Product Development,o=Ace Industry,c=US?mail?sub?objectclass=*";
3545 * LDAPUrl myURL;
3546 * try {
3547 * myURL = new LDAPUrl( flatURL );
3548 * } catch ( java.net.MalformedURLException e ) {
3549 * System.out.println( "Incorrect URL syntax." );
3550 * return;
3551 * }
3552 * LDAPSearchResults myResults = null;
3553 * try {
3554 * myResults = myConn.search( myURL, mySearchConstraints );
3555 * } catch ( LDAPException e ) {
3556 * int errCode = e.getResultCode();
3557 * System.out.println( "LDAPException: return code:" + errCode );
3558 * return;
3559 * }
3560 * </PRE>
3561 * <P>
3562 *
3563 * To abandon the search, use the <CODE>abandon</CODE> method.
3564 *
3565 * @param toGet LDAP URL representing the search to run
3566 * @param cons constraints specific to the search
3567 * @return LDAPSearchResults the results of the search as an enumeration.
3568 * @exception LDAPException Failed to complete the search specified
3569 * by the LDAP URL.
3570 * @see org.ietf.ldap.LDAPUrl
3571 * @see org.ietf.ldap.LDAPSearchResults
3572 * @see org.ietf.ldap.LDAPConnection#abandon(org.ietf.ldap.LDAPSearchResults)
3573 */
3574 public static LDAPSearchResults search( LDAPUrl toGet,
3575 LDAPSearchConstraints cons )
3576 throws LDAPException {
3577 String host = toGet.getHost ();
3578 int port = toGet.getPort();
3579
3580 if (host == null) {
3581 throw new LDAPException ( "no host for connection",
3582 LDAPException.PARAM_ERROR );
3583 }
3584
3585 String[] attributes = toGet.getAttributeArray ();
3586 String DN = toGet.getDN();
3587 String filter = toGet.getFilter();
3588 if (filter == null) {
3589 filter = defaultFilter;
3590 }
3591 int scope = toGet.getScope ();
3592
3593 LDAPConnection connection = new LDAPConnection ();
3594 if (toGet.isSecure()) {
3595 LDAPSocketFactory factory = LDAPUrl.getSocketFactory();
3596 if (factory == null) {
3597 throw new LDAPException("No socket factory for LDAPUrl",
3598 LDAPException.OTHER);
3599 }
3600 connection.setSocketFactory(factory);
3601 }
3602 connection.connect (host, port);
3603
3604 LDAPSearchResults results;
3605 if (cons != null) {
3606 results = connection.search (DN, scope, filter, attributes, false, cons);
3607 } else {
3608 results = connection.search (DN, scope, filter, attributes, false);
3609 }
3610
3611 results.closeOnCompletion(connection);
3612
3613 return results;
3614 }
3615
3616 /**
3617 * Performs the search specified by the criteria that you enter. <P>
3618 *
3619 * For example, the following section of code searches for all entries under
3620 * the <CODE>ou=Product Development,o=Ace Industry,c=US</CODE> subtree of a
3621 * directory. The example gets and prints the mail attribute for each entry
3622 * found. <P>
3623 *
3624 * <PRE>
3625 * String myBaseDN = "ou=Product Development,o=Ace Industry,c=US";
3626 * String myFilter="(objectclass=*)";
3627 * String[] myAttrs = { "mail" };
3628 *
3629 * LDAPSearchResults myResults = null;
3630 * try {
3631 * myResults = myConn.search( myBaseDN, LDAPConnection.SCOPE_SUB, myFilter, myAttrs, false );
3632 * } catch ( LDAPException e ) {
3633 * int errCode = e.getResultCode();
3634 * System.out.println( "LDAPException: return code:" + errCode );
3635 * return;
3636 * }
3637 *
3638 * while ( myResults.hasMore() ) {
3639 * LDAPEntry myEntry = myResults.next();
3640 * String nextDN = myEntry.getDN();
3641 * System.out.println( nextDN );
3642 * LDAPAttributeSet entryAttrs = myEntry.getAttributeSet();
3643 * Iterator attrsInSet = entryAttrs.iterator();
3644 * while ( attrsInSet.hasMore() ) {
3645 * LDAPAttribute nextAttr = (LDAPAttribute)attrsInSet.next();
3646 * String attrName = nextAttr.getName();
3647 * System.out.println( "\t" + attrName + ":" );
3648 * Enumeration valsInAttr = nextAttr.getStringValues();
3649 * while ( valsInAttr.hasMoreElements() ) {
3650 * String nextValue = (String)valsInAttr.nextElement();
3651 * System.out.println( "\t\t" + nextValue );
3652 * }
3653 * }
3654 * }
3655 * </PRE>
3656 * <P>
3657 *
3658 * To abandon the search, use the <CODE>abandon</CODE> method.
3659 *
3660 * @param base the base distinguished name from which to search
3661 * @param scope the scope of the entries to search. You can specify one
3662 * of the following: <P>
3663 * <UL>
3664 * <LI><CODE>LDAPConnection.SCOPE_BASE</CODE> (search only the base DN) <P>
3665 * <LI><CODE>LDAPConnection.SCOPE_ONE</CODE>
3666 * (search only entries under the base DN) <P>
3667 * <LI><CODE>LDAPConnection.SCOPE_SUB</CODE>
3668 * (search the base DN and all entries within its subtree) <P>
3669 * </UL>
3670 * <P>
3671 * @param filter search filter specifying the search criteria
3672 * @param attrs list of attributes that you want returned in the
3673 * search results
3674 * @param attrsOnly if true, returns the names but not the values of the
3675 * attributes found. If false, returns the names and values for
3676 * attributes found
3677 * @return LDAPSearchResults the results of the search as an enumeration.
3678 * @exception LDAPException Failed to complete the specified search.
3679 * @see org.ietf.ldap.LDAPConnection#abandon(org.ietf.ldap.LDAPSearchResults)
3680 */
3681 public LDAPSearchResults search( String base,
3682 int scope,
3683 String filter,
3684 String[] attrs,
3685 boolean attrsOnly ) throws LDAPException {
3686 return search( base, scope, filter, attrs, attrsOnly,
3687 _defaultConstraints );
3688 }
3689
3690 /**
3691 * Performs the search specified by the criteria that you enter.
3692 * This method also allows you to specify constraints for the search
3693 * (such as the maximum number of entries to find or the
3694 * maximum time to wait for search results). <P>
3695 *
3696 * As part of the search constraints, you can specify whether or not
3697 * you want the
3698 * results delivered all at once or in smaller batches. If you
3699 * specify that you want the results delivered in smaller batches,
3700 * each iteration blocks until the
3701 * next batch of results is returned. <P>
3702 *
3703 * For example, the following section of code retrieves the first 5 entries
3704 * matching the specified search criteria. The example accomplishes
3705 * this by creating a new set of search constraints where the maximum
3706 * number of search results is 5. <P>
3707 *
3708 * <PRE>
3709 * String myBaseDN = "ou=Product Development,o=Ace Industry,c=US";
3710 * String myFilter="(objectclass=*)";
3711 * String[] myAttrs = { "mail" };
3712 * LDAPSearchConstraints mySearchConstraints = myConn.getSearchConstraints();
3713 * mySearchConstraints.setMaxResults( 5 );
3714 *
3715 * LDAPSearchResults myResults = null;
3716 * try {
3717 * myResults = myConn.search( myBaseDN, LDAPConnection.SCOPE_SUB, myFilter, myAttrs, false, mySearchConstraints );
3718 * } catch ( LDAPException e ) {
3719 * int errCode = e.getResultCode();
3720 * System.out.println( "LDAPException: return code:" + errCode );
3721 * return;
3722 * }
3723 * </PRE>
3724 * <P>
3725 *
3726 * To abandon the search, use the <CODE>abandon</CODE> method.
3727 *
3728 * @param base the base distinguished name from which to search
3729 * @param scope the scope of the entries to search. You can specify one
3730 * of the following: <P>
3731 * <UL>
3732 * <LI><CODE>LDAPConnection.SCOPE_BASE</CODE> (search only the base DN) <P>
3733 * <LI><CODE>LDAPConnection.SCOPE_ONE</CODE>
3734 * (search only entries under the base DN) <P>
3735 * <LI><CODE>LDAPConnection.SCOPE_SUB</CODE>
3736 * (search the base DN and all entries within its subtree) <P>
3737 * </UL>
3738 * <P>
3739 * @param filter search filter specifying the search criteria
3740 * @param attrs list of attributes to return in the search
3741 * results
3742 * @param cons constraints specific to this search (for example, the
3743 * maximum number of entries to return)
3744 * @param attrsOnly if true, returns the names but not the values of the
3745 * attributes found. If false, returns the names and values for
3746 * attributes found
3747 * @return LDAPSearchResults the results of the search as an enumeration.
3748 * @exception LDAPException Failed to complete the specified search.
3749 * @see org.ietf.ldap.LDAPConnection#abandon(org.ietf.ldap.LDAPSearchResults)
3750 */
3751 public LDAPSearchResults search( String base,
3752 int scope,
3753 String filter,
3754 String[] attrs,
3755 boolean attrsOnly,
3756 LDAPSearchConstraints cons )
3757 throws LDAPException {
3758 if (cons == null) {
3759 cons = _defaultConstraints;
3760 }
3761
3762 LDAPSearchResults returnValue =
3763 new LDAPSearchResults( this, cons, base, scope, filter,
3764 attrs, attrsOnly );
3765 Vector<Object> cacheValue = null;
3766 Long key = null;
3767 boolean isKeyValid = true;
3768
3769 try {
3770 // get entry from cache which is a vector of JDAPMessages
3771 if ( _cache != null ) {
3772 // create key for cache entry using search arguments
3773 key = _cache.createKey( getHost(), getPort(),base, filter,
3774 scope, attrs, _boundDN, cons );
3775
3776 cacheValue = _cache.getEntry(key);
3777
3778 if ( cacheValue != null ) {
3779 return new LDAPSearchResults(
3780 cacheValue, this, cons, base, scope,
3781 filter, attrs, attrsOnly );
3782 }
3783 }
3784 } catch ( LDAPException e ) {
3785 isKeyValid = false;
3786 printDebug("Exception: "+e);
3787 }
3788
3789 internalBind( cons );
3790
3791 LDAPSearchQueue myListener = getSearchListener( cons );
3792 int deref = cons.getDereference();
3793
3794 JDAPSearchRequest request = null;
3795 try {
3796 request = new JDAPSearchRequest( base, scope, deref,
3797 cons.getMaxResults(),
3798 cons.getServerTimeLimit(),
3799 attrsOnly, filter, attrs );
3800 } catch ( IllegalArgumentException e ) {
3801 throw new LDAPException(e.getMessage(), LDAPException.PARAM_ERROR);
3802 }
3803
3804 // if using cache, then we need to set the key of the search listener
3805 if ( (_cache != null) && isKeyValid ) {
3806 myListener.setKey( key );
3807 }
3808
3809 try {
3810 sendRequest( request, myListener, cons );
3811 }
3812 catch ( LDAPException e ) {
3813 releaseSearchListener( myListener );
3814 throw e;
3815 }
3816
3817 /* Is this a persistent search? */
3818 boolean isPersistentSearch = false;
3819 LDAPControl[] controls =
3820 (LDAPControl[])getOption( SERVERCONTROLS, cons );
3821 for ( int i = 0; (controls != null) && (i < controls.length); i++ ) {
3822 if ( controls[i] instanceof
3823 org.ietf.ldap.controls.LDAPPersistSearchControl ) {
3824 isPersistentSearch = true;
3825 break;
3826 }
3827 }
3828
3829 /* For a persistent search, don't wait for a first result, because
3830 there may be none at this time if changesOnly was specified in
3831 the control.
3832 */
3833 if ( isPersistentSearch ) {
3834 returnValue.associatePersistentSearch (myListener);
3835
3836 } else if ( cons.getBatchSize() == 0 ) {
3837 /* Synchronous search if all requested at once */
3838 try {
3839 /* Block until all results are in */
3840 LDAPMessage response = myListener.completeRequest();
3841 Iterator<LDAPMessage> results = myListener.getAllMessages().iterator();
3842
3843 checkSearchMsg(returnValue, response, cons, base, scope,
3844 filter, attrs, attrsOnly);
3845
3846 while ( results.hasNext() ) {
3847 LDAPMessage msg = results.next();
3848 checkSearchMsg( returnValue, msg, cons, base, scope,
3849 filter, attrs, attrsOnly );
3850 }
3851 } finally {
3852 releaseSearchListener( myListener );
3853 }
3854 } else {
3855 /*
3856 * Asynchronous to retrieve one at a time, check to make sure
3857 * the search didn't fail
3858 */
3859 LDAPMessage firstResult = myListener.getResponse();
3860 if ( firstResult instanceof LDAPResponse ) {
3861 try {
3862 checkSearchMsg( returnValue, firstResult, cons, base,
3863 scope, filter, attrs, attrsOnly );
3864 } finally {
3865 releaseSearchListener( myListener );
3866 }
3867 } else {
3868 try {
3869 checkSearchMsg( returnValue, firstResult, cons, base,
3870 scope, filter, attrs, attrsOnly );
3871 } catch ( LDAPException ex ) {
3872 releaseSearchListener( myListener );
3873 throw ex;
3874 }
3875
3876 /* we let this listener get garbage collected.. */
3877 returnValue.associate( myListener );
3878 }
3879 }
3880 return returnValue;
3881 }
3882
3883 /**
3884 * Performs the search specified by the criteria that you enter. <P>
3885 * To abandon the search, use the <CODE>abandon</CODE> method.
3886 *
3887 * @param base the base distinguished name from which to search
3888 * @param scope the scope of the entries to search. You can specify one
3889 * of the following: <P>
3890 * <UL>
3891 * <LI><CODE>LDAPConnection.SCOPE_BASE</CODE> (search only the base DN) <P>
3892 * <LI><CODE>LDAPConnection.SCOPE_ONE</CODE>
3893 * (search only entries under the base DN) <P>
3894 * <LI><CODE>LDAPConnection.SCOPE_SUB</CODE>
3895 * (search the base DN and all entries within its subtree) <P>
3896 * </UL>
3897 * <P>
3898 * @param filter search filter specifying the search criteria
3899 * @param attrs list of attributes that you want returned in the
3900 * search results
3901 * @param typesOnly if true, returns the names but not the values of the
3902 * attributes found. If false, returns the names and values for
3903 * attributes found
3904 * @param listener handler for messages returned from a server in response
3905 * to this request. If it is null, a listener object is created internally.
3906 * @return LDAPSearchQueue handler for messages returned from a server
3907 * in response to this request.
3908 * @exception LDAPException Failed to send request.
3909 * @see org.ietf.ldap.LDAPConnection#abandon(org.ietf.ldap.LDAPSearchQueue)
3910 */
3911 public LDAPSearchQueue search( String base,
3912 int scope,
3913 String filter,
3914 String attrs[],
3915 boolean typesOnly,
3916 LDAPSearchQueue listener )
3917 throws LDAPException {
3918
3919 return search( base, scope, filter, attrs, typesOnly,
3920 listener, _defaultConstraints );
3921 }
3922
3923 /**
3924 * Performs the search specified by the criteria that you enter.
3925 * This method also allows you to specify constraints for the search
3926 * (such as the maximum number of entries to find or the
3927 * maximum time to wait for search results). <P>
3928 * To abandon the search, use the <CODE>abandon</CODE> method.
3929 *
3930 * @param base the base distinguished name from which to search
3931 * @param scope the scope of the entries to search. You can specify one
3932 * of the following: <P>
3933 * <UL>
3934 * <LI><CODE>LDAPConnection.SCOPE_BASE</CODE> (search only the base DN) <P>
3935 * <LI><CODE>LDAPConnection.SCOPE_ONE</CODE>
3936 * (search only entries under the base DN) <P>
3937 * <LI><CODE>LDAPConnection.SCOPE_SUB</CODE>
3938 * (search the base DN and all entries within its subtree) <P>
3939 * </UL>
3940 * <P>
3941 * @param filter search filter specifying the search criteria
3942 * @param attrs list of attributes that you want returned in the search
3943 * results
3944 * @param typesOnly if true, returns the names but not the values of the
3945 * attributes found. If false, returns the names and values for
3946 * attributes found.
3947 * @param listener handler for messages returned from a server in response
3948 * to this request. If it is null, a listener object is created internally.
3949 * @param cons constraints specific to this search (for example, the
3950 * maximum number of entries to return)
3951 * @return LDAPSearchQueue handler for messages returned from a server
3952 * in response to this request.
3953 * @exception LDAPException Failed to send request.
3954 * @see org.ietf.ldap.LDAPConnection#abandon(org.ietf.ldap.LDAPSearchQueue)
3955 */
3956 public LDAPSearchQueue search( String base,
3957 int scope,
3958 String filter,
3959 String attrs[],
3960 boolean typesOnly,
3961 LDAPSearchQueue listener,
3962 LDAPSearchConstraints cons )
3963 throws LDAPException {
3964 if ( cons == null ) {
3965 cons = _defaultConstraints;
3966 }
3967
3968 internalBind( cons );
3969
3970 if ( listener == null ) {
3971 listener = new LDAPSearchQueue( /*asynchOp=*/true, cons );
3972 }
3973
3974 JDAPSearchRequest request = null;
3975 try {
3976 request = new JDAPSearchRequest( base, scope,
3977 cons.getDereference(),
3978 cons.getMaxResults(),
3979 cons.getServerTimeLimit(),
3980 typesOnly, filter, attrs );
3981 }
3982 catch ( IllegalArgumentException e ) {
3983 throw new LDAPException( e.getMessage(),
3984 LDAPException.PARAM_ERROR );
3985 }
3986
3987 sendRequest( request, listener, cons );
3988 return listener;
3989
3990 }
3991
3992 /**
3993 * Sets the specified <CODE>LDAPCache</CODE> object as the
3994 * cache for the <CODE>LDAPConnection</CODE> object.
3995 * <P>
3996 *
3997 * @param cache the <CODE>LDAPCache</CODE> object representing
3998 * the cache that the current connection should use
3999 * @see org.ietf.ldap.LDAPCache
4000 * @see org.ietf.ldap.LDAPConnection#getCache
4001 */
4002 public void setCache( LDAPCache cache ) {
4003 if ( _cache != null ) {
4004 _cache.removeReference();
4005 }
4006 if ( cache != null ) {
4007 cache.addReference();
4008 }
4009 _cache = cache;
4010 if ( _thread != null ) {
4011 _thread.setCache( cache );
4012 }
4013 }
4014
4015 /**
4016 * Specifies the maximum time to wait for the connection to be established.
4017 * If the value is 0, the time is not limited.
4018 * @param timeout the maximum connect time in seconds or 0 (unlimited)
4019 */
4020 public void setConnectTimeout (int timeout) {
4021 if ( timeout < 0 ) {
4022 throw new IllegalArgumentException(
4023 "Timeout value can not be negative" );
4024 }
4025 _connectTimeout = timeout;
4026 if ( _connMgr != null ) {
4027 _connMgr.setConnectTimeout( _connectTimeout );
4028 }
4029 }
4030
4031 /**
4032 * Specifies the delay in seconds when making concurrent connection attempts to
4033 * multiple servers.
4034 * <P>Effectively, selects the connection setup policy when a list of hosts is passed
4035 * to the <CODE>connect</CODE> method.
4036 *
4037 * <br>If the serial policy is selected, the default one, an attempt is made to
4038 * connect to the first host in the list. The next entry in
4039 * the list is tried only if the attempt to connect to the current host fails.
4040 * This might cause your application to block for unacceptably long time if a host is down.
4041 *
4042 * <br>If the parallel policy is selected, multiple connection attempts may run
4043 * concurrently on a separate thread. A new connection attempt to the next entry
4044 * in the list can be started with or without delay.
4045 * <P>You must set the <CODE>ConnSetupDelay</CODE> before making the call to the
4046 * <CODE>connect</CODE> method.
4047 *
4048 * @param delay the delay in seconds between connection attempts. Possible values are:<br>
4049 * <CODE>NODELAY_SERIAL</CODE> Use the serial connection setup policy.<br>
4050 * <CODE>NODELAY_PARALLEL</CODE> Use the parallel connection setup policy with no delay.
4051 * Start all connection setup threads immediately.<br>
4052 * <CODE>delay > 0</CODE> Use the parallel connection setup policy with delay.
4053 * Start another connection setup thread after <CODE>delay</CODE> seconds.<br>
4054 * @see org.ietf.ldap.LDAPConnection#NODELAY_SERIAL
4055 * @see org.ietf.ldap.LDAPConnection#NODELAY_PARALLEL
4056 * @see org.ietf.ldap.LDAPConnection#connect(java.lang.String, int)
4057 */
4058 public void setConnSetupDelay( int delay ) {
4059 _connSetupDelay = delay;
4060 if ( _connMgr != null ) {
4061 _connMgr.setConnSetupDelay( delay );
4062 }
4063 }
4064
4065 /**
4066 * Set the default constraint set for all operations.
4067 * @param cons <CODE>LDAPConstraints</CODE> object to use as the default
4068 * constraint set
4069 * @see org.ietf.ldap.LDAPConnection#getConstraints
4070 * @see org.ietf.ldap.LDAPConstraints
4071 */
4072 public void setConstraints( LDAPConstraints cons ) {
4073 _defaultConstraints.setHopLimit( cons.getHopLimit() );
4074 _defaultConstraints.setReferralFollowing( cons.getReferralFollowing() );
4075 _defaultConstraints.setTimeLimit( cons.getTimeLimit() );
4076 _defaultConstraints.setReferralHandler( cons.getReferralHandler() );
4077
4078 LDAPControl[] tServerControls = cons.getControls();
4079 LDAPControl[] oServerControls = null;
4080 if ( (tServerControls != null) &&
4081 (tServerControls.length > 0) ) {
4082 oServerControls =
4083 new LDAPControl[tServerControls.length];
4084 for( int i = 0; i < tServerControls.length; i++ ) {
4085 oServerControls[i] = (LDAPControl)tServerControls[i].clone();
4086 }
4087 }
4088 _defaultConstraints.setControls( oServerControls );
4089
4090 if ( cons instanceof LDAPSearchConstraints ) {
4091 LDAPSearchConstraints scons = (LDAPSearchConstraints)cons;
4092 _defaultConstraints.setServerTimeLimit( scons.getServerTimeLimit() );
4093 _defaultConstraints.setDereference( scons.getDereference() );
4094 _defaultConstraints.setMaxResults( scons.getMaxResults() );
4095 _defaultConstraints.setBatchSize( scons.getBatchSize() );
4096 _defaultConstraints.setMaxBacklog( scons.getMaxBacklog() );
4097 }
4098 }
4099
4100 /**
4101 * Sets the stream for reading from the listener socket if
4102 * there is one
4103 *
4104 * @param is the stream for reading from the listener socket
4105 */
4106 public void setInputStream( InputStream is ) {
4107 if ( _thread != null ) {
4108 _thread.setInputStream( is );
4109 }
4110 }
4111
4112 /**
4113 * Sets the stream for writing to the socket
4114 *
4115 * @param os the stream for writing to the socket, if there is one
4116 */
4117 public void setOutputStream( OutputStream os ) {
4118 if ( _thread != null ) {
4119 _thread.setOutputStream( os );
4120 }
4121 }
4122
4123 /**
4124 * Sets a global property of the connection.
4125 * The following properties are defined:<BR>
4126 * com.org.ietf.ldap.schema.quoting - "standard" or "NetscapeBug"<BR>
4127 * Note: if this property is not set, the SDK will query the server
4128 * to determine if attribute syntax values and objectclass superior
4129 * values must be quoted when adding schema.<BR>
4130 * com.org.ietf.ldap.saslpackage - the default is "com.netscape.sasl"<BR>
4131 * <P>
4132 *
4133 * @param name name of the property to set
4134 * @param val value to set
4135 * @exception LDAPException Unable to set the value of the specified
4136 * property.
4137 */
4138 public void setProperty( String name, Object val ) throws LDAPException {
4139 if ( name.equalsIgnoreCase( SCHEMA_BUG_PROPERTY ) ) {
4140 _properties.put( SCHEMA_BUG_PROPERTY, val );
4141 } else if ( name.equalsIgnoreCase( SASL_PACKAGE_PROPERTY ) ) {
4142 _properties.put( SASL_PACKAGE_PROPERTY, val );
4143 } else if ( name.equalsIgnoreCase( "debug" ) ) {
4144 debug = ((String)val).equalsIgnoreCase( "true" );
4145
4146 } else if ( name.equalsIgnoreCase( TRACE_PROPERTY ) ) {
4147
4148 Object traceOutput = null;
4149 if (val == null) {
4150 _properties.remove(TRACE_PROPERTY);
4151 } else {
4152 if ( _thread != null ) {
4153 traceOutput = createTraceOutput( val );
4154 }
4155 _properties.put( TRACE_PROPERTY, val );
4156 }
4157
4158 if ( _thread != null ) {
4159 _thread.setTraceOutput( traceOutput );
4160 }
4161
4162 // This is used only by the ldapjdk test cases to simulate a
4163 // server problem and to test fail-over and rebind
4164 } else if ( name.equalsIgnoreCase( "breakConnection" ) ) {
4165 _connMgr.breakConnection();
4166
4167 } else {
4168 throw new LDAPException( "Unknown property: " + name );
4169 }
4170 }
4171
4172 /**
4173 * Set the default constraint set for all search operations.
4174 * @param cons <CODE>LDAPSearchConstraints</CODE> object to use as the
4175 * default constraint set
4176 * @see org.ietf.ldap.LDAPConnection#getSearchConstraints
4177 * @see org.ietf.ldap.LDAPSearchConstraints
4178 */
4179 public void setSearchConstraints( LDAPSearchConstraints cons ) {
4180 _defaultConstraints = (LDAPSearchConstraints)cons.clone();
4181 }
4182
4183 /**
4184 * Specifies the object representing the socket factory that you
4185 * want to use to establish a connection to a server.
4186 * <P>
4187 *
4188 * @param factory the object representing the socket factory that
4189 * you want to use to establish a connection to a server
4190 * @see org.ietf.ldap.LDAPSocketFactory
4191 * @see org.ietf.ldap.LDAPSSLSocketFactory
4192 * @see org.ietf.ldap.LDAPConnection#getSocketFactory
4193 */
4194 public void setSocketFactory( LDAPSocketFactory factory ) {
4195 _factory = factory;
4196 }
4197
4198 /**
4199 * Begin using the Transport Layer Security (TLS) protocol for session
4200 * privacy [TLS][LDAPTLS]. If the socket factory of the connection is
4201 * not capable of initiating a TLS session, an LDAPException is thrown
4202 * with the error code TLS_NOT_SUPPORTED. If the server does not support
4203 * the transition to a TLS session, an LDAPException is thrown with the
4204 * error code returned by the server. If there are outstanding LDAP
4205 * operations on the connection, an LDAPException is thrown.
4206 */
4207 public void startTLS() throws LDAPException {
4208 }
4209
4210 /**
4211 * Stop using the Transport Layer Security (TLS) protocol for session
4212 * privacy [LDAPTLS]. If the server does not support the termination of
4213 * a TLS session, an LDAPException is thrown with the error code
4214 * returned by the server. If there are outstanding LDAP operations on
4215 * the connection, an LDAPException is thrown.
4216 */
4217 public void stopTLS() throws LDAPException {
4218 }
4219
4220 /**
4221 * Returns the value of the specified option for this
4222 * <CODE>LDAPConnection</CODE> object. <P>
4223 *
4224 * These options represent the constraints for the current connection.
4225 * To get all constraints for the current connection, call the
4226 * <CODE>getSearchConstraints</CODE> method.
4227 * <P>
4228 *
4229 * By default, the constraints apply to all operations performed
4230 * through the current connection. You can change these constraints:
4231 * <P>
4232 *
4233 * <UL>
4234 * <LI> If you want to set a constraint only for a particular operation,
4235 * create an <CODE>LDAPConstraints</CODE> object (or a
4236 * <CODE>LDAPSearchConstraints</CODE> object for a search or find operation)
4237 * with your new constraints
4238 * and pass it to the <CODE>LDAPConnection</CODE> method that performs the
4239 * operation.
4240 * <P>
4241 *
4242 * <LI>If you want to override these constraints for all operations
4243 * performed under the current connection, call the
4244 * <CODE>setOption</CODE> method to change the constraint.
4245 * <P>
4246 *
4247 * </UL>
4248 * <P>
4249 *
4250 * For example, the following section of code gets and prints the
4251 * maximum number of search results that are returned for searches
4252 * performed through this connection. (This applies to all searches
4253 * unless a different set of search constraints is specified in an
4254 * <CODE>LDAPSearchConstraints</CODE> object.)
4255 * <P>
4256 *
4257 * <PRE>
4258 * LDAPConnection ld = new LDAPConnection();
4259 * int sizeLimit = ( (Integer)ld.getOption( LDAPConnection.SIZELIMIT ) ).intValue();
4260 * System.out.println( "Maximum number of results: " + sizeLimit );
4261 * </PRE>
4262 *
4263 * @param option you can specify one of the following options:
4264 * <TABLE CELLPADDING=5>
4265 * <TR VALIGN=BASELINE ALIGN=LEFT>
4266 * <TH>Option</TH><TH>Data Type</TH><TH>Description</TH></TR>
4267 * <TR VALIGN=BASELINE><TD>
4268 * <CODE>LDAPConnection.PROTOCOL_VERSION</CODE></TD>
4269 * <TD><CODE>Integer</CODE></TD>
4270 * <TD>Specifies the version of the LDAP protocol used by the
4271 * client.
4272 * <P>By default, the value of this option is 2.</TD></TR>
4273 * <TR VALIGN=BASELINE><TD>
4274 * <CODE>LDAPConnection.DEREF</CODE></TD>
4275 * <TD><CODE>Integer</CODE></TD>
4276 * <TD>Specifies when your client dereferences aliases.
4277 *<PRE>
4278 * Legal values for this option are:
4279 *
4280 * DEREF_NEVER Aliases are never dereferenced.
4281 *
4282 * DEREF_FINDING Aliases are dereferenced when find-
4283 * ing the starting point for the
4284 * search (but not when searching
4285 * under that starting entry).
4286 *
4287 * DEREF_SEARCHING Aliases are dereferenced when
4288 * searching the entries beneath the
4289 * starting point of the search (but
4290 * not when finding the starting
4291 * entry).
4292 *
4293 * DEREF_ALWAYS Aliases are always dereferenced.
4294 *</PRE>
4295 * <P>By default, the value of this option is
4296 * <CODE>DEREF_NEVER</CODE>.</TD></TR>
4297 * <TR VALIGN=BASELINE><TD>
4298 * <CODE>LDAPConnection.SIZELIMIT</CODE></TD>
4299 * <TD><CODE>Integer</CODE></TD>
4300 * <TD>Specifies the maximum number of search results to return.
4301 * If this option is set to 0, there is no maximum limit.
4302 * <P>By default, the value of this option is 1000.</TD></TR>
4303 * <TR VALIGN=BASELINE><TD>
4304 * <CODE>LDAPConnection.TIMELIMIT</CODE></TD>
4305 * <TD><CODE>Integer</CODE></TD>
4306 * <TD>Specifies the maximum number of milliseconds to wait for results
4307 * before timing out. If this option is set to 0, there is no maximum
4308 * time limit.
4309 * <P>By default, the value of this option is 0.</TD></TR>
4310 * <TR VALIGN=BASELINE><TD>
4311 * <CODE>LDAPConnection.REFERRALS</CODE></TD>
4312 * <TD><CODE>Boolean</CODE></TD>
4313 * <TD>Specifies whether or not your client follows referrals automatically.
4314 * If <CODE>true</CODE>, your client follows referrals automatically.
4315 * If <CODE>false</CODE>, an <CODE>LDAPReferralException</CODE> is raised
4316 * when referral is detected.
4317 * <P>By default, the value of this option is <CODE>false</CODE>.</TD></TR>
4318 * <TR VALIGN=BASELINE><TD>
4319 * <CODE>LDAPConnection.REFERRALS_REBIND_PROC</CODE></TD>
4320 * <TD><CODE>LDAPAuthHandler</CODE></TD>
4321 * <TD>Specifies an object with a class that implements the
4322 * <CODE>LDAPAuthHandler</CODE> interface. You must define this class and
4323 * the <CODE>getAuthProvider</CODE> method that will be used to
4324 * get the distinguished name and password to use for authentication.
4325 * Modifying this option sets the <CODE>LDAPConnection.BIND</CODE> option to null.
4326 * <P>By default, the value of this option is <CODE>null</CODE>.</TD></TR>
4327 * <TR VALIGN=BASELINE><TD>
4328 * <CODE>LDAPConnection.BIND</CODE></TD>
4329 * <TD><CODE>LDAPBind</CODE></TD>
4330 * <TD>Specifies an object with a class that implements the
4331 * <CODE>LDAPBind</CODE>
4332 * interface. You must define this class and the
4333 * <CODE>bind</CODE> method that will be used to authenticate
4334 * to the server on referrals. Modifying this option sets the
4335 * <CODE>LDAPConnection.REFERRALS_REBIND_PROC</CODE> to null.
4336 * <P>By default, the value of this option is <CODE>null</CODE>.</TD></TR>
4337 * <TR VALIGN=BASELINE><TD>
4338 * <CODE>LDAPConnection.REFERRALS_HOP_LIMIT</CODE></TD>
4339 * <TD><CODE>Integer</CODE></TD>
4340 * <TD>Specifies the maximum number of referrals in a sequence that
4341 * your client will follow. (For example, if REFERRALS_HOP_LIMIT is 5,
4342 * your client will follow no more than 5 referrals in a row when resolving
4343 * a single LDAP request.)
4344 * <P>By default, the value of this option is 10.</TD></TR>
4345 * <TR VALIGN=BASELINE><TD>
4346 * <CODE>LDAPConnection.BATCHSIZE</CODE></TD>
4347 * <TD><CODE>Integer</CODE></TD>
4348 * <TD>Specifies the number of search results to return at a time.
4349 * (For example, if BATCHSIZE is 1, results are returned one at a time.)
4350 * <P>By default, the value of this option is 1.</TD></TR>
4351 * <TD><CODE>LDAPControl[]</CODE></TD>
4352 * <TD>Specifies the client controls that may affect the handling of LDAP
4353 * operations in the LDAP classes. These controls are used by the client
4354 * and are not passed to the LDAP server. At this time, no client controls
4355 * are defined for clients built with the Netscape LDAP classes. </TD></TR>
4356 * <TR VALIGN=BASELINE><TD>
4357 * <CODE>LDAPConnection.SERVERCONTROLS</CODE></TD>
4358 * <TD><CODE>LDAPControl[]</CODE></TD>
4359 * <TD>Specifies the server controls that are passed to the LDAP
4360 * server on each LDAP operation. Not all servers support server
4361 * controls; a particular server may or may not support a given
4362 * server control.</TD></TR>
4363 * <TR VALIGN=BASELINE><TD>
4364 * <CODE>MAXBACKLOG</CODE></TD>
4365 * <TD><CODE>Integer</CODE></TD>
4366 * <TD>Specifies the maximum number of search results to accumulate in an
4367 * LDAPSearchResults before suspending the reading of input from the server.
4368 * <P>By default, the value of this option is 100. The value 0 means there
4369 * is no limit.</TD></TR>
4370 * </TABLE><P>
4371 * @return the value for the option wrapped in an object. (You
4372 * need to cast the returned value as its appropriate type. For
4373 * example, when getting the SIZELIMIT option, cast the returned
4374 * value as an <CODE>Integer</CODE>.)
4375 * @exception LDAPException Failed to get the specified option.
4376 * @see org.ietf.ldap.LDAPAuthHandler
4377 * @see org.ietf.ldap.LDAPConstraints
4378 * @see org.ietf.ldap.LDAPSearchConstraints
4379 * @see org.ietf.ldap.LDAPReferralException
4380 * @see org.ietf.ldap.LDAPControl
4381 * @see org.ietf.ldap.LDAPConnection#getSearchConstraints
4382 * @see org.ietf.ldap.LDAPConnection#search(java.lang.String, int, java.lang.String, java.lang.String[], boolean, org.ietf.ldap.LDAPSearchConstraints)
4383 */
4384 public Object getOption( int option ) throws LDAPException {
4385 if (option == LDAPConnection.PROTOCOL_VERSION) {
4386 return _protocolVersion;
4387 }
4388
4389 return getOption(option, _defaultConstraints);
4390 }
4391
4392 private static Object getOption( int option, LDAPSearchConstraints cons )
4393 throws LDAPException {
4394 switch (option) {
4395 case LDAPConnection.DEREF:
4396 return cons.getDereference();
4397 case LDAPConnection.SIZELIMIT:
4398 return cons.getMaxResults();
4399 case LDAPConnection.TIMELIMIT:
4400 return cons.getServerTimeLimit();
4401 case LDAPConnection.REFERRALS:
4402 return cons.getReferralFollowing();
4403 case LDAPConnection.REFERRALS_REBIND_PROC:
4404 return cons.getReferralHandler();
4405 case LDAPConnection.REFERRALS_HOP_LIMIT:
4406 return cons.getHopLimit();
4407 case LDAPConnection.BATCHSIZE:
4408 return cons.getBatchSize();
4409 case LDAPConnection.SERVERCONTROLS:
4410 return cons.getControls();
4411 case MAXBACKLOG:
4412 return cons.getMaxBacklog();
4413 default:
4414 throw new LDAPException ( "invalid option",
4415 LDAPException.PARAM_ERROR );
4416 }
4417 }
4418
4419 /**
4420 * Sets the value of the specified option for this
4421 * <CODE>LDAPConnection</CODE> object. <P>
4422 *
4423 * These options represent the constraints for the current
4424 * connection.
4425 * To get all constraints for the current connection, call the
4426 * <CODE>getSearchConstraints</CODE> method.
4427 * <P>
4428 *
4429 * By default, the option that you set applies to all subsequent
4430 * operations performed through the current connection. If you want to
4431 * set a constraint only for a particular operation, create an
4432 * <CODE>LDAPConstraints</CODE> object (or a
4433 * <CODE>LDAPSearchConstraints</CODE> object for a search or find operation)
4434 * with your new constraints
4435 * and pass it to the <CODE>LDAPConnection</CODE> method that performs the
4436 * operation.
4437 * <P>
4438 *
4439 * For example, the following section of code changes the constraint for
4440 * the maximum number of search results that are returned for searches
4441 * performed through this connection. (This applies to all searches
4442 * unless a different set of search constraints is specified in an
4443 * <CODE>LDAPSearchConstraints</CODE> object.)
4444 * <P>
4445 *
4446 * <PRE>
4447 * LDAPConnection ld = new LDAPConnection();
4448 * Integer newLimit = new Integer( 20 );
4449 * ld.setOption( LDAPConnection.SIZELIMIT, newLimit );
4450 * System.out.println( "Changed the maximum number of results to " + newLimit.intValue() );
4451 * </PRE>
4452 *
4453 * @param option you can specify one of the following options:
4454 * <TABLE CELLPADDING=5>
4455 * <TR VALIGN=BASELINE ALIGN=LEFT>
4456 * <TH>Option</TH><TH>Data Type</TH><TH>Description</TH></TR>
4457 * <TR VALIGN=BASELINE><TD>
4458 * <CODE>LDAPConnection.PROTOCOL_VERSION</CODE></TD>
4459 * <TD><CODE>Integer</CODE></TD>
4460 * <TD>Specifies the version of the LDAP protocol used by the
4461 * client.
4462 * <P>By default, the value of this option is 2. If you want
4463 * to use LDAP v3 features (such as extended operations or
4464 * controls), you need to set this value to 3. </TD></TR>
4465 * <TR VALIGN=BASELINE><TD>
4466 * <CODE>LDAPConnection.DEREF</CODE></TD>
4467 * <TD><CODE>Integer</CODE></TD>
4468 * <TD>Specifies when your client dereferences aliases.
4469 *<PRE>
4470 * Legal values for this option are:
4471 *
4472 * DEREF_NEVER Aliases are never dereferenced.
4473 *
4474 * DEREF_FINDING Aliases are dereferenced when find-
4475 * ing the starting point for the
4476 * search (but not when searching
4477 * under that starting entry).
4478 *
4479 * DEREF_SEARCHING Aliases are dereferenced when
4480 * searching the entries beneath the
4481 * starting point of the search (but
4482 * not when finding the starting
4483 * entry).
4484 *
4485 * DEREF_ALWAYS Aliases are always dereferenced.
4486 *</PRE>
4487 * <P>By default, the value of this option is
4488 * <CODE>DEREF_NEVER</CODE>.</TD></TR>
4489 * <TR VALIGN=BASELINE><TD>
4490 * <CODE>LDAPConnection.SIZELIMIT</CODE></TD>
4491 * <TD><CODE>Integer</CODE></TD>
4492 * <TD>Specifies the maximum number of search results to return.
4493 * If this option is set to 0, there is no maximum limit.
4494 * <P>By default, the value of this option is 1000.</TD></TR>
4495 * <TR VALIGN=BASELINE><TD>
4496 * <CODE>LDAPConnection.TIMELIMIT</CODE></TD>
4497 * <TD><CODE>Integer</CODE></TD>
4498 * <TD>Specifies the maximum number of milliseconds to wait for results
4499 * before timing out. If this option is set to 0, there is no maximum
4500 * time limit.
4501 * <P>By default, the value of this option is 0.</TD></TR>
4502 * <TR VALIGN=BASELINE><TD>
4503 * <CODE>LDAPConnection.REFERRALS</CODE></TD>
4504 * <TD><CODE>Boolean</CODE></TD>
4505 * <TD>Specifies whether or not your client follows referrals automatically.
4506 * If <CODE>true</CODE>, your client follows referrals automatically.
4507 * If <CODE>false</CODE>, an <CODE>LDAPReferralException</CODE> is
4508 * raised when a referral is detected.
4509 * <P>By default, the value of this option is <CODE>false</CODE>.</TD></TR>
4510 * <TR VALIGN=BASELINE><TD>
4511 * <CODE>LDAPConnection.REFERRALS_REBIND_PROC</CODE></TD>
4512 * <TD><CODE>LDAPAuthHandler</CODE></TD>
4513 * <TD>Specifies an object with a class that implements the
4514 * <CODE>LDAPAuthHandler</CODE>
4515 * interface. You must define this class and the
4516 * <CODE>getAuthProvider</CODE> method that will be used to get
4517 * the distinguished name and password to use for authentication.
4518 * Modifying this option sets the <CODE>LDAPConnection.BIND</CODE> option to null.
4519 * <P>By default, the value of this option is <CODE>null</CODE>.</TD></TR>
4520 * <TR VALIGN=BASELINE><TD>
4521 * <CODE>LDAPConnection.BIND</CODE></TD>
4522 * <TD><CODE>LDAPBind</CODE></TD>
4523 * <TD>Specifies an object with a class that implements the
4524 * <CODE>LDAPBind</CODE>
4525 * interface. You must define this class and the
4526 * <CODE>bind</CODE> method that will be used to autheniticate
4527 * to the server on referrals. Modifying this option sets the
4528 * <CODE>LDAPConnection.REFERRALS_REBIND_PROC</CODE> to null.
4529 * <P>By default, the value of this option is <CODE>null</CODE>.</TD></TR>
4530 * <TR VALIGN=BASELINE><TD>
4531 * <CODE>LDAPConnection.REFERRALS_HOP_LIMIT</CODE></TD>
4532 * <TD><CODE>Integer</CODE></TD>
4533 * <TD>Specifies the maximum number of referrals in a sequence that
4534 * your client will follow. (For example, if REFERRALS_HOP_LIMIT is 5,
4535 * your client will follow no more than 5 referrals in a row when resolving
4536 * a single LDAP request.)
4537 * <P>By default, the value of this option is 10.</TD></TR>
4538 * <TR VALIGN=BASELINE><TD>
4539 * <CODE>LDAPConnection.BATCHSIZE</CODE></TD>
4540 * <TD><CODE>Integer</CODE></TD>
4541 * <TD>Specifies the number of search results to return at a time.
4542 * (For example, if BATCHSIZE is 1, results are returned one at a time.)
4543 * <P>By default, the value of this option is 1.</TD></TR>
4544 * <TD><CODE>LDAPControl[]</CODE></TD>
4545 * <TD>Specifies the client controls that may affect handling of LDAP
4546 * operations in the LDAP classes. These controls are used by the client
4547 * and are not passed to the server. At this time, no client controls
4548 * are defined for clients built with the Netscape LDAP classes. </TD></TR>
4549 * <TR VALIGN=BASELINE><TD>
4550 * <CODE>LDAPConnection.SERVERCONTROLS</CODE></TD>
4551 * <TD><CODE>LDAPControl[]</CODE></TD>
4552 * <TD>Specifies the server controls that are passed to the LDAP
4553 * server on each LDAP operation. Not all servers support server
4554 * controls; a particular server may or may not support a particular
4555 * control.</TD></TR>
4556 * <TR VALIGN=BASELINE><TD>
4557 * <CODE>MAXBACKLOG</CODE></TD>
4558 * <TD><CODE>Integer</CODE></TD>
4559 * <TD>Specifies the maximum number of search results to accumulate in an
4560 * LDAPSearchResults before suspending the reading of input from the server.
4561 * <P>By default, the value of this option is 100. The value 0 means there
4562 * is no limit.</TD></TR>
4563 * </TABLE><P>
4564 * @param value the value to assign to the option. The value must be
4565 * the java.lang object wrapper for the appropriate parameter
4566 * (e.g. boolean->Boolean,
4567 * integer->Integer)
4568 * @exception LDAPException Failed to set the specified option.
4569 * @see org.ietf.ldap.LDAPAuthHandler
4570 * @see org.ietf.ldap.LDAPConstraints
4571 * @see org.ietf.ldap.LDAPSearchConstraints
4572 * @see org.ietf.ldap.LDAPReferralException
4573 * @see org.ietf.ldap.LDAPControl
4574 * @see org.ietf.ldap.LDAPConnection#getSearchConstraints
4575 * @see org.ietf.ldap.LDAPConnection#search(java.lang.String, int, java.lang.String, java.lang.String[], boolean, org.ietf.ldap.LDAPSearchConstraints)
4576 */
4577 public void setOption( int option, Object value ) throws LDAPException {
4578 if (option == LDAPConnection.PROTOCOL_VERSION) {
4579 setProtocolVersion(((Integer)value).intValue());
4580 return;
4581 }
4582 setOption(option, value, _defaultConstraints);
4583 }
4584
4585 private static void setOption( int option,
4586 Object value,
4587 LDAPSearchConstraints cons )
4588 throws LDAPException {
4589 try {
4590 switch (option) {
4591 case LDAPConnection.DEREF:
4592 cons.setDereference(((Integer)value).intValue());
4593 return;
4594 case LDAPConnection.SIZELIMIT:
4595 cons.setMaxResults(((Integer)value).intValue());
4596 return;
4597 case LDAPConnection.TIMELIMIT:
4598 cons.setTimeLimit(((Integer)value).intValue());
4599 return;
4600 case LDAPConnection.SERVER_TIMELIMIT:
4601 cons.setServerTimeLimit(((Integer)value).intValue());
4602 return;
4603 case LDAPConnection.REFERRALS:
4604 cons.setReferralFollowing(((Boolean)value).booleanValue());
4605 return;
4606 case LDAPConnection.REFERRALS_REBIND_PROC:
4607 cons.setReferralHandler((LDAPReferralHandler)value);
4608 return;
4609 case LDAPConnection.REFERRALS_HOP_LIMIT:
4610 cons.setHopLimit(((Integer)value).intValue());
4611 return;
4612 case LDAPConnection.BATCHSIZE:
4613 cons.setBatchSize(((Integer)value).intValue());
4614 return;
4615 case LDAPConnection.SERVERCONTROLS:
4616 if ( value == null )
4617 cons.setControls( (LDAPControl[]) null );
4618 else if ( value instanceof LDAPControl )
4619 cons.setControls( (LDAPControl) value );
4620 else if ( value instanceof LDAPControl[] )
4621 cons.setControls( (LDAPControl[])value );
4622 else
4623 throw new LDAPException ( "invalid LDAPControl",
4624 LDAPException.PARAM_ERROR );
4625 return;
4626 case MAXBACKLOG:
4627 cons.setMaxBacklog( ((Integer)value).intValue() );
4628 return;
4629 default:
4630 throw new LDAPException ( "invalid option",
4631 LDAPException.PARAM_ERROR );
4632 }
4633 } catch ( ClassCastException cc ) {
4634 throw new LDAPException ( "invalid option value",
4635 LDAPException.PARAM_ERROR );
4636 }
4637 }
4638
4639 /**
4640 * Send a request to the server
4641 */
4642 void sendRequest( JDAPProtocolOp oper, LDAPMessageQueue myListener,
4643 LDAPConstraints cons ) throws LDAPException {
4644
4645 // retry three times if we get a nullPointer exception.
4646 // Don't remove this. The following situation might happen:
4647 // Before sendRequest gets invoked, it is possible that the
4648 // LDAPConnThread encountered a network error and called
4649 // deregisterConnection which set the thread reference to null.
4650 boolean requestSent = false;
4651 for ( int i = 0; !requestSent && (i < 3); i++ ) {
4652 try {
4653 _thread.sendRequest( this, oper, myListener, cons );
4654 requestSent = true;
4655 } catch( NullPointerException ne ) {
4656 // do nothing
4657 } catch (IllegalArgumentException e) {
4658 throw new LDAPException(e.getMessage(),
4659 LDAPException.PARAM_ERROR);
4660 }
4661
4662 }
4663 if ( !isConnected() ) {
4664 throw new LDAPException( "The connection is not available",
4665 LDAPException.OTHER );
4666 }
4667 if ( !requestSent ) {
4668 throw new LDAPException( "Failed to send request",
4669 LDAPException.OTHER );
4670 }
4671 }
4672
4673 /**
4674 * Internal routine. Binds to the LDAP server.
4675 * This method is used by the "smart failover" feature. If a server
4676 * or network error has occurred, an attempt is made to automatically
4677 * restore the connection on the next ldap operation request
4678 * @exception LDAPException failed to bind or the user has disconncted
4679 */
4680 private void internalBind( LDAPConstraints cons ) throws LDAPException {
4681
4682 // If the user has invoked disconnect() no attempt is made
4683 // to restore the connection
4684 if ( (_connMgr != null) && _connMgr.isUserDisconnected() ) {
4685 throw new LDAPException( "not connected", LDAPException.OTHER );
4686 }
4687
4688 if ( _saslBinder != null ) {
4689 if ( !isConnected() ) {
4690 connect();
4691 }
4692 _saslBinder.bind( this, false );
4693 _authMethod = "sasl";
4694 } else {
4695 //Rebind using _rebindConstraints
4696 if ( _rebindConstraints == null ) {
4697 _rebindConstraints = _defaultConstraints;
4698 }
4699 internalBind ( _protocolVersion, false, _rebindConstraints );
4700 }
4701 }
4702
4703 void checkSearchMsg( LDAPSearchResults value, LDAPMessage msg,
4704 LDAPSearchConstraints cons, String dn,
4705 int scope, String filter,
4706 String attrs[], boolean attrsOnly)
4707 throws LDAPException {
4708
4709 value.setMsgID( msg.getMessageID() );
4710
4711 try {
4712 checkMsg( msg );
4713 // not the JDAPResult
4714 if ( msg.getProtocolOp().getType() !=
4715 JDAPProtocolOp.SEARCH_RESULT ) {
4716 value.add( msg );
4717 }
4718 } catch ( LDAPReferralException e ) {
4719 Vector<Object> res = new Vector<>();
4720
4721 try {
4722 performReferrals( e, cons, JDAPProtocolOp.SEARCH_REQUEST, dn,
4723 scope, filter, attrs, attrsOnly, null, null,
4724 null, res );
4725 }
4726 catch ( LDAPException ex ) {
4727 if ( msg.getProtocolOp() instanceof
4728 JDAPSearchResultReference ) {
4729 /*
4730 Don't want to miss all remaining results, so continue.
4731 This is very ugly (using println). We should have a
4732 configurable parameter (probably in LDAPSearchConstraints)
4733 whether to ignore failed search references or throw an
4734 exception.
4735 */
4736 System.err.println( "LDAPConnection.checkSearchMsg: " +
4737 "ignoring bad referral" );
4738 return;
4739 }
4740 throw ex;
4741 }
4742
4743 // The size of the vector can be more than 1 because it is possible
4744 // to visit more than one referral url to retrieve the entries
4745 for ( int i = 0; i < res.size(); i++ ) {
4746 value.addReferralEntries( (LDAPSearchResults)res.elementAt(i) );
4747 }
4748
4749 res = null;
4750 } catch ( LDAPException e ) {
4751 if ( (e.getResultCode() == LDAPException.ADMIN_LIMIT_EXCEEDED) ||
4752 (e.getResultCode() == LDAPException.TIME_LIMIT_EXCEEDED) ||
4753 (e.getResultCode() == LDAPException.SIZE_LIMIT_EXCEEDED) ) {
4754 value.add(e);
4755 } else {
4756 throw e;
4757 }
4758 }
4759 }
4760
4761
4762 /**
4763 * Internal routine. Binds to the LDAP server.
4764 * @param version protocol version to request from server
4765 * @param rebind true if the bind/authenticate operation is requested,
4766 * false if the method is invoked by the "smart failover" feature
4767 * @exception LDAPException failed to bind
4768 */
4769 private void internalBind( int version, boolean rebind,
4770 LDAPConstraints cons ) throws LDAPException {
4771 _saslBinder = null;
4772
4773 if ( !isConnected() ) {
4774 _bound = false;
4775 _authMethod = "none";
4776 connect();
4777 // special case: the connection currently is not bound, and now
4778 // there is a bind request. The connection needs to reconnect if
4779 // the thread has more than one LDAPConnection.
4780 } else if ( !_bound && rebind && (_thread.getClientCount() > 1) ) {
4781 disconnect();
4782 connect();
4783 }
4784
4785 // if the connection is still intact and no rebind request
4786 if ( _bound && !rebind ) {
4787 return;
4788 }
4789
4790 // if the connection was lost and did not have any kind of bind
4791 // operation and the current one does not request any bind operation (ie,
4792 // no authenticate has been called)
4793 if ( !_anonymousBound &&
4794 ((_boundDN == null) || (_boundPasswd == null)) &&
4795 !rebind ) {
4796 return;
4797 }
4798
4799 if ( _bound && rebind ) {
4800 if ( _protocolVersion == version ) {
4801 if ( _anonymousBound &&
4802 ((_boundDN == null) || (_boundPasswd == null)) ) {
4803 return;
4804 }
4805
4806 if ( !_anonymousBound &&
4807 (_boundDN != null) &&
4808 (_boundPasswd != null) &&
4809 _boundDN.equals(_prevBoundDN) &&
4810 equalsBytes(_boundPasswd, _prevBoundPasswd) ) {
4811 return;
4812 }
4813 }
4814
4815 // if we got this far, we need to rebind since previous and
4816 // current credentials are not the same.
4817 // if the current connection is the only connection of the thread,
4818 // then reuse this current connection. otherwise, disconnect the
4819 // current one (ie, detach from the current thread) and reconnect
4820 // again (ie, get a new thread).
4821 if ( _thread.getClientCount() > 1 ) {
4822 disconnect();
4823 connect();
4824 }
4825 }
4826
4827 _protocolVersion = version;
4828
4829 LDAPResponseQueue myListener = getResponseListener();
4830 try {
4831 if ( (_referralConnection != null) &&
4832 _referralConnection.isConnected() ) {
4833 _referralConnection.disconnect();
4834 }
4835 _referralConnection = null;
4836 _bound = false;
4837 sendRequest( new JDAPBindRequest( _protocolVersion, _boundDN,
4838 _boundPasswd),
4839 myListener, cons );
4840 checkMsg( myListener.getResponse() );
4841 markConnAsBound();
4842 _rebindConstraints = (LDAPConstraints)cons.clone();
4843 _authMethod = "simple";
4844 } catch (LDAPReferralException e) {
4845 _referralConnection = createReferralConnection( e, cons );
4846 } finally {
4847 releaseResponseListener( myListener );
4848 }
4849 }
4850
4851 private static boolean equalsBytes( byte[] b1, byte[] b2 ) {
4852 if ( b1 == null ) {
4853 return ( b2 == null );
4854 } else if ( b2 == null ) {
4855 return true;
4856 }
4857 if ( b1.length != b2.length ) {
4858 return false;
4859 }
4860 for( int i = 0; i < b1.length; i++ ) {
4861 if ( b1[i] != b2[1] ) {
4862 return false;
4863 }
4864 }
4865 return true;
4866 }
4867
4868 /**
4869 * Mark this connection as bound in the thread connection table
4870 */
4871 void markConnAsBound() {
4872 synchronized (_threadConnTable) {
4873 if (_threadConnTable.containsKey(_thread)) {
4874 Vector<LDAPConnection> v = _threadConnTable.get(_thread);
4875 for (int i=0, n=v.size(); i<n; i++) {
4876 LDAPConnection conn = v.elementAt(i);
4877 conn._bound = true;
4878 }
4879 } else {
4880 printDebug( "Thread table does not contain the thread of " +
4881 "this object" );
4882 }
4883 }
4884 }
4885
4886
4887 /**
4888 * Evaluate the TRACE_PROPERTY value and create output stream.
4889 * The value can be of type String, OutputStream or LDAPTraceWriter.
4890 * The String value represents output file name. If the name is an empty
4891 * string, the output is sent to System.err. If the file name is
4892 * prefixed with a '+' character, the file is opened in append mode.
4893 *
4894 * @param out Trace output specifier. A file name, an output stream
4895 * or an instance of LDAPTraceWriter
4896 * @return An output stream or an LDAPTraceWriter instance
4897 */
4898 Object createTraceOutput( Object out ) throws LDAPException {
4899
4900 if ( out instanceof String ) { // trace file name
4901 OutputStream os = null;
4902 String file = (String)out;
4903 if ( file.length() == 0 ) {
4904 os = System.err;
4905 } else {
4906 try {
4907 boolean appendMode = (file.charAt(0) == '+');
4908 if ( appendMode ) {
4909 file = file.substring(1);
4910 }
4911 FileOutputStream fos =
4912 new FileOutputStream( file, appendMode );
4913 os = new BufferedOutputStream( fos );
4914 }
4915 catch ( IOException e ) {
4916 throw new LDAPException(
4917 "Can not open output trace file " + file + " " + e );
4918 }
4919 }
4920 return os;
4921 }
4922 else if ( out instanceof OutputStream ) {
4923 return out;
4924 }
4925 else if ( out instanceof LDAPTraceWriter ) {
4926 return out;
4927 } else {
4928 throw new LDAPException( TRACE_PROPERTY +
4929 " must be an OutputStream, a file " +
4930 "name or an instance of LDAPTraceWriter" );
4931 }
4932
4933 }
4934
4935 /**
4936 * Sets the LDAP protocol version that your client prefers to use when
4937 * connecting to the LDAP server.
4938 * <P>
4939 *
4940 * @param version the LDAP protocol version that your client uses
4941 */
4942 private void setProtocolVersion( int version ) {
4943 _protocolVersion = version;
4944 }
4945
4946 /**
4947 * Remove this connection from the thread connection table
4948 */
4949 private void deleteThreadConnEntry() {
4950 synchronized ( _threadConnTable ) {
4951 Vector<LDAPConnection> connVector = _threadConnTable.get( _thread );
4952 if ( connVector == null ) {
4953 printDebug( "Thread table does not contain the thread of " +
4954 "this object" );
4955 return;
4956 }
4957 Enumeration<LDAPConnection> enumv = connVector.elements();
4958 while ( enumv.hasMoreElements() ) {
4959 LDAPConnection c = enumv.nextElement();
4960 if ( c.equals( this ) ) {
4961 connVector.removeElement( c );
4962 if ( connVector.size() == 0 ) {
4963 _threadConnTable.remove( _thread );
4964 }
4965 return;
4966 }
4967 }
4968 }
4969 }
4970
4971 /**
4972 * Remove the association between this object and the connection thread
4973 */
4974 synchronized void deregisterConnection() {
4975 if ( (_thread != null) && _thread.isRunning() ) {
4976 _thread.deregister( this );
4977 }
4978 _thread = null;
4979 _bound = false;
4980 }
4981
4982 /**
4983 * Returns the trace output object if set by the user
4984 */
4985 Object getTraceOutput() throws LDAPException {
4986
4987 // Check first if trace output has been set using setProperty()
4988 Object traceOut = _properties.get( TRACE_PROPERTY );
4989 if ( traceOut != null ) {
4990 return createTraceOutput( traceOut );
4991 }
4992
4993 // Check if the property has been set with java
4994 // -Dcom.org.ietf.ldap.trace
4995 // If the property does not have a value, send the trace to the
4996 // System.err, otherwise use the value as the output file name
4997 try {
4998 traceOut = System.getProperty( TRACE_PROPERTY );
4999 if ( traceOut != null ) {
5000 return createTraceOutput( traceOut );
5001 }
5002 }
5003 catch ( Exception e ) {
5004 ;// In browser, access to property might not be allowed
5005 }
5006 return null;
5007 }
5008
5009
5010 private synchronized LDAPConnThread getNewThread(LDAPConnSetupMgr connMgr,
5011 LDAPCache cache)
5012 throws LDAPException {
5013
5014 LDAPConnThread newThread = null;
5015 Vector<LDAPConnection> v = null;
5016
5017 synchronized( _threadConnTable ) {
5018
5019 Enumeration<LDAPConnThread> keys = _threadConnTable.keys();
5020 boolean connExists = false;
5021
5022 // transverse each thread
5023 while ( keys.hasMoreElements() ) {
5024 LDAPConnThread connThread = keys.nextElement();
5025 Vector<LDAPConnection> connVector = _threadConnTable.get( connThread );
5026 Enumeration<LDAPConnection> enumv = connVector.elements();
5027
5028 // traverse each LDAPConnection under the same thread
5029 while ( enumv.hasMoreElements() ) {
5030 LDAPConnection conn = enumv.nextElement();
5031
5032 // this is not a brand new connection
5033 if ( conn.equals( this ) ) {
5034 connExists = true;
5035
5036 if ( !connThread.isAlive() ) {
5037 // need to move all the LDAPConnections from the dead thread
5038 // to the new thread
5039 try {
5040 newThread =
5041 new LDAPConnThread( connMgr, cache,
5042 getTraceOutput() );
5043 v = _threadConnTable.remove(
5044 connThread );
5045 break;
5046 } catch ( Exception e ) {
5047 throw new LDAPException(
5048 "unable to establish connection",
5049 LDAPException.UNAVAILABLE );
5050 }
5051 }
5052 break;
5053 }
5054 }
5055
5056 if ( connExists ) {
5057 break;
5058 }
5059 }
5060
5061 // if this connection is new or the corresponding thread for
5062 // the current connection is dead
5063 if ( !connExists ) {
5064 try {
5065 newThread = new LDAPConnThread( connMgr, cache,
5066 getTraceOutput() );
5067 v = new Vector<>();
5068 v.addElement( this );
5069 } catch ( Exception e ) {
5070 throw new LDAPException( "unable to establish connection",
5071 LDAPException.UNAVAILABLE );
5072 }
5073 }
5074
5075 // add new thread to the table
5076 if ( newThread != null ) {
5077 _threadConnTable.put( newThread, v );
5078 for ( int i = 0, n = v.size(); i < n; i++ ) {
5079 LDAPConnection c = v.elementAt( i );
5080 newThread.register( c );
5081 c._thread = newThread;
5082 }
5083 }
5084 }
5085
5086 return newThread;
5087 }
5088
5089 /**
5090 * Performs certificate-based authentication if client authentication was
5091 * specified at construction time.
5092 * @exception LDAPException if certificate-based authentication fails.
5093 */
5094 private void authenticateSSLConnection() throws LDAPException {
5095
5096 // if this is SSL
5097 if ( (_factory != null) &&
5098 (_factory instanceof LDAPSSLSocketFactoryExt) ) {
5099
5100 if ( ((LDAPSSLSocketFactoryExt)_factory).isClientAuth() ) {
5101 bind( null, null, new String[] {EXTERNAL_MECHANISM},
5102 EXTERNAL_MECHANISM_PACKAGE, null, null, null );
5103 }
5104 }
5105 }
5106
5107 /**
5108 * Gets a new listening agent from the internal buffer of available agents.
5109 * These objects are used to make the asynchronous LDAP operations
5110 * synchronous.
5111 *
5112 * @return response listener object
5113 */
5114 synchronized LDAPResponseQueue getResponseListener() {
5115 if ( _responseListeners == null ) {
5116 _responseListeners = new Vector<>( 5 );
5117 }
5118
5119 LDAPResponseQueue l;
5120 if ( _responseListeners.size() < 1 ) {
5121 l = new LDAPResponseQueue ( /*asynchOp=*/false );
5122 }
5123 else {
5124 l = _responseListeners.elementAt( 0 );
5125 _responseListeners.removeElementAt( 0 );
5126 }
5127 return l;
5128 }
5129
5130 /**
5131 * Get a new search listening agent from the internal buffer of available
5132 * agents. These objects are used to make the asynchronous LDAP operations
5133 * synchronous.
5134 * @return a search response listener object
5135 */
5136 private synchronized LDAPSearchQueue getSearchListener (
5137 LDAPSearchConstraints cons ) {
5138 if ( _searchListeners == null ) {
5139 _searchListeners = new Vector<>( 5 );
5140 }
5141
5142 LDAPSearchQueue l;
5143 if ( _searchListeners.size() < 1 ) {
5144 l = new LDAPSearchQueue ( /*asynchOp=*/false, cons );
5145 }
5146 else {
5147 l = _searchListeners.elementAt( 0 );
5148 _searchListeners.removeElementAt( 0 );
5149 l.setSearchConstraints( cons );
5150 }
5151 return l;
5152 }
5153
5154 /**
5155 * Put a listening agent into the internal buffer of available agents.
5156 * These objects are used to make the asynchronous LDAP operations
5157 * synchronous.
5158 * @param l listener to buffer
5159 */
5160 synchronized void releaseResponseListener( LDAPResponseQueue l ) {
5161 if ( _responseListeners == null ) {
5162 _responseListeners = new Vector<>( 5 );
5163 }
5164
5165 l.reset();
5166 _responseListeners.addElement( l );
5167 }
5168
5169 /**
5170 * Put a search listening agent into the internal buffer of available
5171 * agents. These objects are used to make the asynchronous LDAP
5172 * operations synchronous.
5173 * @param l listener to buffer
5174 */
5175 synchronized void releaseSearchListener( LDAPSearchQueue l ) {
5176 if ( _searchListeners == null ) {
5177 _searchListeners = new Vector<>( 5 );
5178 }
5179
5180 l.reset();
5181 _searchListeners.addElement( l );
5182 }
5183
5184 /**
5185 * Checks the message (assumed to be a return value). If the resultCode
5186 * is anything other than SUCCESS, it throws an LDAPException describing
5187 * the server's (error) response.
5188 * @param m server response to validate
5189 * @exception LDAPException failed to check message
5190 */
5191 void checkMsg( LDAPMessage m ) throws LDAPException {
5192 if ( m.getProtocolOp() instanceof JDAPResult ) {
5193 JDAPResult response = (JDAPResult)m.getProtocolOp();
5194 int resultCode = response.getResultCode();
5195
5196 if ( resultCode == JDAPResult.SUCCESS ) {
5197 return;
5198 }
5199
5200 if ( resultCode == JDAPResult.REFERRAL ) {
5201 throw new LDAPReferralException ( "referral", resultCode,
5202 response.getReferrals() );
5203 }
5204
5205 if ( resultCode == JDAPResult.LDAP_PARTIAL_RESULTS ) {
5206 throw new LDAPReferralException ( "referral", resultCode,
5207 response.getErrorMessage() );
5208 } else {
5209 throw new LDAPException(
5210 LDAPException.resultCodeToString(resultCode),
5211 resultCode,
5212 response.getErrorMessage(),
5213 response.getMatchedDN());
5214 }
5215
5216 } else if ( m.getProtocolOp() instanceof JDAPSearchResultReference ) {
5217 String[] referrals =
5218 ((JDAPSearchResultReference)m.getProtocolOp()).getUrls();
5219 throw new LDAPReferralException ( "referral",
5220 JDAPResult.SUCCESS, referrals );
5221 } else {
5222 return;
5223 }
5224 }
5225
5226 /**
5227 * Set response controls for the current connection for a particular
5228 * thread. Get the oldest returned controls and remove them from the
5229 * queue. If the connection is executing a persistent search, there may
5230 * be more than one set of controls in the queue. For any other
5231 * operation, there will only ever be at most one set of controls
5232 * (controls from any earlier operation are replaced by controls
5233 * received on the latest operation on this connection by this thread).
5234 * @param current the target thread
5235 * @param con the server response controls
5236 */
5237 void setResponseControls( LDAPConnThread current,
5238 LDAPResponseControl con ) {
5239 synchronized(_responseControlTable) {
5240 Vector<LDAPResponseControl> v = _responseControlTable.get( current );
5241
5242 // if the current thread already contains response controls from
5243 // a previous operation
5244 if ( (v != null) && (v.size() > 0) ) {
5245
5246 // look at each response control
5247 for ( int i = v.size() - 1; i >= 0; i-- ) {
5248 LDAPResponseControl response = v.elementAt( i );
5249
5250 // if this response control belongs to this connection
5251 if ( response.getConnection().equals( this ) ) {
5252
5253 // if the given control is null or
5254 // the given control is not null and the current
5255 // control does not correspond to the new LDAPMessage
5256 if ( (con == null) ||
5257 (con.getMsgID() != response.getMsgID()) ) {
5258 v.removeElement( response );
5259 }
5260
5261 // For the same connection, if the message id from the
5262 // given control is the same as the one in the queue,
5263 // those controls in the queue will not get removed
5264 // since they come from the persistent search control
5265 // which allows more than one control response for
5266 // one persistent search operation.
5267 }
5268 }
5269 } else {
5270 if ( con != null ) {
5271 v = new Vector<>();
5272 }
5273 }
5274
5275 if ( con != null ) {
5276 v.addElement( con );
5277 _responseControlTable.put( current, v );
5278 }
5279
5280 /* Do some garbage collection: check if any attached threads have
5281 exited */
5282 /* Now check all threads in the list */
5283 Enumeration<LDAPConnThread> e = _attachedList.elements();
5284 while( e.hasMoreElements() ) {
5285 LDAPConnThread aThread = e.nextElement();
5286 if ( !aThread.isAlive() ) {
5287 _responseControlTable.remove( aThread );
5288 _attachedList.removeElement( aThread );
5289 }
5290 }
5291 }
5292 /* Make sure we're registered */
5293 if ( _attachedList.indexOf( current ) < 0 ) {
5294 _attachedList.addElement( current );
5295 }
5296 }
5297
5298 /**
5299 * Set up connection for referral.
5300 * @param u referral URL
5301 * @param cons search constraints
5302 * @return new LDAPConnection, already connected and authenticated
5303 */
5304 private LDAPConnection prepareReferral( String connectList,
5305 LDAPConstraints cons )
5306 throws LDAPException {
5307 LDAPConnection connection =
5308 new LDAPConnection( this.getSocketFactory() );
5309
5310 // Set the same connection setup failover policy as for this connection
5311 connection.setConnSetupDelay( getConnSetupDelay() );
5312
5313 connection.setOption( REFERRALS, true );
5314 connection.setOption( REFERRALS_REBIND_PROC,
5315 cons.getReferralHandler() );
5316
5317 // need to set the protocol version which gets passed to connection
5318 connection.setOption( PROTOCOL_VERSION, _protocolVersion );
5319
5320 connection.setOption( REFERRALS_HOP_LIMIT, cons.getHopLimit()-1 );
5321
5322 try {
5323 connection.connect( connectList, LDAPConnection.DEFAULT_PORT );
5324 }
5325 catch ( LDAPException e ) {
5326 throw new LDAPException( "Referral connect failed: " +
5327 e.getMessage(),
5328 e.getResultCode() );
5329 }
5330 return connection;
5331 }
5332
5333 private void referralRebind( LDAPConnection ldc, LDAPConstraints cons )
5334 throws LDAPException{
5335 try {
5336 LDAPReferralHandler handler = cons.getReferralHandler();
5337 if ( handler == null ) {
5338 ldc.bind ( _protocolVersion, null, null );
5339 } else if ( handler instanceof LDAPAuthHandler ) {
5340 LDAPAuthProvider auth =
5341 ((LDAPAuthHandler)handler).getAuthProvider(
5342 ldc.getHost(),
5343 ldc.getPort());
5344 ldc.bind( _protocolVersion,
5345 auth.getDN(),
5346 auth.getPassword() );
5347 } else if ( handler instanceof LDAPBindHandler ) {
5348 String[] urls = { "ldap://" + ldc.getHost() + ':' +
5349 ldc.getPort() + '/' };
5350 ((LDAPBindHandler)handler).bind( urls, ldc);
5351 }
5352 }
5353 catch ( LDAPException e ) {
5354 throw new LDAPException( "Referral bind failed: " + e.getMessage(),
5355 e.getResultCode() );
5356 }
5357 }
5358
5359
5360 private String createReferralConnectList( String[] urls ) {
5361 String connectList = "";
5362 String host = null;
5363 int port = 0;
5364
5365 for ( int i=0; urls != null && i < urls.length; i++ ) {
5366 try {
5367 LDAPUrl url = new LDAPUrl( urls[i] );
5368 host = url.getHost();
5369 port = url.getPort();
5370 if ( (host == null) ||
5371 (host.length() < 1) ) {
5372 // If no host:port was specified, use the latest
5373 // (hop-wise) parameters
5374 host = getHost();
5375 port = getPort();
5376 }
5377 } catch ( Exception e ) {
5378 host = getHost();
5379 port = getPort();
5380 }
5381 connectList += (i==0 ? "" : " ") + host+":"+port;
5382 }
5383
5384 return (connectList.length() == 0) ? null : connectList;
5385 }
5386
5387 private LDAPUrl findReferralURL( LDAPConnection ldc, String[] urls ) {
5388 String connHost = ldc.getHost();
5389 int connPort = ldc.getPort();
5390 for ( int i = 0; i < urls.length; i++ ) {
5391 try {
5392 LDAPUrl url = new LDAPUrl( urls[i] );
5393 String host = url.getHost();
5394 int port = url.getPort();
5395 if ( host == null ||
5396 host.length() < 1 ) {
5397 // No host:port specified, compare with the latest
5398 // (hop-wise) parameters
5399 if ( connHost.equals( getHost() ) &&
5400 connPort == getPort() ) {
5401 return url;
5402 }
5403 } else if ( connHost.equals( host ) &&
5404 connPort == port ) {
5405 return url;
5406 }
5407 } catch ( Exception e ) {
5408 }
5409 }
5410 return null;
5411 }
5412
5413 /**
5414 * Establish the LDAPConnection to the referred server. This one is used
5415 * for bind operation only since we need to keep this new connection for
5416 * the subsequent operations. This new connection will be destroyed in
5417 * two circumstances: disconnect gets called or the client binds as
5418 * someone else.
5419 * @return the new LDAPConnection to the referred server
5420 */
5421 LDAPConnection createReferralConnection( LDAPReferralException e,
5422 LDAPConstraints cons )
5423 throws LDAPException {
5424 if ( cons.getHopLimit() <= 0 ) {
5425 throw new LDAPException( "exceed hop limit",
5426 e.getResultCode(),
5427 e.getLDAPErrorMessage() );
5428 }
5429 if ( !cons.getReferralFollowing() ) {
5430 throw e;
5431 }
5432
5433 String connectList =
5434 createReferralConnectList( e.getReferrals() );
5435 // If there are no referrals (because the server isn't set up for
5436 // them), give up here
5437 if ( connectList == null ) {
5438 throw new LDAPException( "No target URL in referral",
5439 LDAPException.NO_RESULTS_RETURNED );
5440 }
5441
5442 LDAPConnection connection = null;
5443 connection = prepareReferral( connectList, cons );
5444 try {
5445 connection.bind( _protocolVersion, _boundDN, _boundPasswd );
5446 } catch ( LDAPException authEx ) {
5447 // Disconnect needed to terminate the LDAPConnThread
5448 try {
5449 connection.disconnect();
5450 } catch ( LDAPException ignore ) {
5451 }
5452 throw authEx;
5453 }
5454 return connection;
5455 }
5456
5457 /**
5458 * Follows a referral
5459 *
5460 * @param e referral exception
5461 * @param cons search constraints
5462 */
5463 void performReferrals( LDAPReferralException e,
5464 LDAPConstraints cons, int ops,
5465 /* unions of different operation parameters */
5466 String dn, int scope, String filter, String types[],
5467 boolean attrsOnly, LDAPModification mods[],
5468 LDAPEntry entry,
5469 LDAPAttribute attr,
5470 /* result */
5471 Vector<Object> results )
5472 throws LDAPException {
5473
5474 if ( cons.getHopLimit() <= 0 ) {
5475 throw new LDAPException( "exceed hop limit",
5476 e.getResultCode(),
5477 e.getLDAPErrorMessage() );
5478 }
5479 if ( !cons.getReferralFollowing() ) {
5480 if ( ops == JDAPProtocolOp.SEARCH_REQUEST ) {
5481 LDAPSearchResults res = new LDAPSearchResults();
5482 res.add( e );
5483 results.addElement( res );
5484 return;
5485 } else {
5486 throw e;
5487 }
5488 }
5489
5490 String[] urls = e.getReferrals();
5491 // If there are no referrals (because the server isn't configured to
5492 // return one), give up here
5493 if ( (urls == null) || (urls.length == 0) ) {
5494 return;
5495 }
5496
5497 LDAPUrl referralURL = null;
5498 LDAPConnection connection = null;
5499
5500 if ( (_referralConnection != null) &&
5501 _referralConnection.isConnected() ) {
5502 referralURL = findReferralURL( _referralConnection, urls );
5503 }
5504 if ( referralURL != null ) {
5505 connection = _referralConnection;
5506 }
5507 else {
5508 String connectList = createReferralConnectList( urls );
5509 connection = prepareReferral( connectList, cons );
5510
5511 // which one did we connect to...
5512 referralURL = findReferralURL( connection, urls );
5513
5514 // Authenticate
5515 referralRebind( connection, cons );
5516 }
5517
5518 String newDN = referralURL.getDN();
5519 String DN = null;
5520 if ( (newDN == null) || newDN.equals("") ) {
5521 DN = dn;
5522 } else {
5523 DN = newDN;
5524 }
5525 // If this was a one-level search, and a direct subordinate
5526 // has a referral, there will be a "?base" in the URL, and
5527 // we have to rewrite the scope from one to base
5528 if ( referralURL.toString().indexOf("?base") > -1 ) {
5529 scope = SCOPE_BASE;
5530 }
5531
5532 LDAPSearchConstraints newcons = (LDAPSearchConstraints)cons.clone();
5533 newcons.setHopLimit( cons.getHopLimit()-1 );
5534
5535 performReferrals( connection, newcons, ops, DN, scope, filter,
5536 types, attrsOnly, mods, entry, attr, results );
5537 }
5538
5539 void performReferrals( LDAPConnection connection,
5540 LDAPConstraints cons, int ops, String dn, int scope,
5541 String filter, String types[], boolean attrsOnly,
5542 LDAPModification mods[], LDAPEntry entry,
5543 LDAPAttribute attr,
5544 Vector<Object> results ) throws LDAPException {
5545
5546 LDAPSearchResults res = null;
5547 try {
5548 switch ( ops ) {
5549 case JDAPProtocolOp.SEARCH_REQUEST:
5550
5551 res = connection.search( dn, scope, filter,
5552 types, attrsOnly,
5553 (LDAPSearchConstraints)cons );
5554 if ( res != null ) {
5555 res.closeOnCompletion( connection );
5556 results.addElement( res );
5557 } else {
5558 if ( (_referralConnection == null) ||
5559 !connection.equals(_referralConnection) ) {
5560 connection.disconnect();
5561 }
5562 }
5563 break;
5564 case JDAPProtocolOp.MODIFY_REQUEST:
5565 connection.modify( dn, mods, cons );
5566 break;
5567 case JDAPProtocolOp.ADD_REQUEST:
5568 if ( (dn != null) && !dn.equals("") )
5569 entry.setDN( dn );
5570 connection.add( entry, cons );
5571 break;
5572 case JDAPProtocolOp.DEL_REQUEST:
5573 connection.delete( dn, cons );
5574 break;
5575 case JDAPProtocolOp.MODIFY_RDN_REQUEST:
5576 connection.rename( dn, filter /* newRDN */,
5577 attrsOnly /* deleteOld */, cons );
5578 break;
5579 case JDAPProtocolOp.COMPARE_REQUEST:
5580 boolean bool = connection.compare( dn, attr, cons );
5581 results.addElement( bool );
5582 break;
5583 default:
5584 /* impossible */
5585 break;
5586 }
5587 } catch ( LDAPException ee ) {
5588 throw ee;
5589 } finally {
5590 if ( (connection != null) &&
5591 ((ops != JDAPProtocolOp.SEARCH_REQUEST) || (res == null)) &&
5592 ((_referralConnection == null) ||
5593 !connection.equals(_referralConnection)) ) {
5594 connection.disconnect();
5595 }
5596 }
5597 }
5598
5599 /**
5600 * Follows a referral for an extended operation
5601 *
5602 * @param e referral exception
5603 * @param cons search constraints
5604 */
5605 private LDAPExtendedOperation performExtendedReferrals(
5606 LDAPReferralException e,
5607 LDAPConstraints cons, LDAPExtendedOperation op )
5608 throws LDAPException {
5609
5610 if ( cons.getHopLimit() <= 0 ) {
5611 throw new LDAPException( "exceed hop limit",
5612 e.getResultCode(),
5613 e.getLDAPErrorMessage() );
5614 }
5615 if ( !cons.getReferralFollowing() ) {
5616 throw e;
5617 }
5618
5619 String[] u = e.getReferrals();
5620 // If there are no referrals (because the server isn't configured to
5621 // return one), give up here
5622 if ( (u == null) || (u.length == 0) ) {
5623 return null;
5624 }
5625
5626 String connectList = createReferralConnectList( u );
5627 LDAPConnection connection = prepareReferral( connectList, cons );
5628 referralRebind( connection, cons );
5629 LDAPExtendedOperation results =
5630 connection.extendedOperation( op );
5631 connection.disconnect();
5632 return results; /* return right away if operation is successful */
5633
5634 }
5635
5636 /**
5637 * Sets up basic connection privileges for Communicator.
5638 * @return true if in Communicator and connections okay.
5639 */
5640 private static boolean checkCommunicator() {
5641 try {
5642 java.lang.reflect.Method m = LDAPCheckComm.getMethod(
5643 "netscape.security.PrivilegeManager", "enablePrivilege" );
5644 if ( m == null ) {
5645 printDebug( "Method is null" );
5646 return false;
5647 }
5648
5649 Object[] args = new Object[1];
5650 args[0] = new String( "UniversalConnect" );
5651 m.invoke( null, args);
5652 printDebug( "UniversalConnect enabled" );
5653 args[0] = new String( "UniversalPropertyRead" );
5654 m.invoke( null, args);
5655 printDebug( "UniversalPropertyRead enabled" );
5656 return true;
5657 } catch ( LDAPException e ) {
5658 printDebug( "Exception: " + e.toString() );
5659 } catch ( Exception ie ) {
5660 printDebug( "Exception on invoking " + "enablePrivilege: " +
5661 ie.toString() );
5662 }
5663 return false;
5664 }
5665
5666 /**
5667 * Reports if the class is running in a Netscape browser.
5668 * @return <CODE>true</CODE> if the class is running in a Netscape browser.
5669 */
5670 public static boolean isNetscape() {
5671 return isCommunicator;
5672 }
5673
5674 static void printDebug( String msg ) {
5675 if ( debug ) {
5676 System.out.println( msg );
5677 }
5678 }
5679
5680 /**
5681 * Returns the string representation for this <CODE>LDAPConnection</CODE>.
5682 * <P>
5683 * For example:
5684 *
5685 * <PRE>LDAPConnection {ldap://dilly:389 (2) ldapVersion:3 bindDN:
5686 * "uid=admin,o=iplanet.com"}</PRE>
5687 *
5688 * For cloned connections, the number of LDAPConnection instances sharing
5689 * the same physical connection is shown in parenthesis following the ldap
5690 * url.
5691 * If an LDAPConnection objectis not cloned, this number is omitted from
5692 * the string representation.
5693 *
5694 * @return string representation of the connection
5695 * @see org.ietf.ldap.LDAPConnection#clone
5696 */
5697 public String toString() {
5698 int cloneCnt = (_thread == null) ? 0 : _thread.getClientCount();
5699 StringBuffer sb = new StringBuffer( "LDAPConnection {" );
5700 //url
5701 // sb.append( (isSecure() ? "ldaps" : "ldap") );
5702 sb.append( "ldap" );
5703 sb.append( "://" );
5704 sb.append( getHost() );
5705 sb.append( ":" );
5706 sb.append( getPort() );
5707 // clone count
5708 if ( cloneCnt > 1 ) {
5709 sb.append( " (" );
5710 sb.append( cloneCnt );
5711 sb.append( ")" );
5712 }
5713 // ldap version
5714 sb.append( " ldapVersion:" );
5715 sb.append( _protocolVersion );
5716 // bind DN
5717 sb.append( " bindDN:\"" );
5718 if ( getAuthenticationDN() != null ) {
5719 sb.append( getAuthenticationDN() );
5720 }
5721 sb.append( "\"}" );
5722
5723 return sb.toString();
5724 }
5725
5726 /**
5727 * Prints out the LDAP Java SDK version and the highest LDAP
5728 * protocol version supported by the SDK. To view this
5729 * information, open a terminal window, and enter:
5730 * <PRE>java org.ietf.ldap.LDAPConnection
5731 * </PRE>
5732 * @param args not currently used
5733 */
5734 public static void main(String[] args) {
5735 System.out.println( "LDAP SDK Version is " + SdkVersion );
5736 System.out.println( "LDAP Protocol Version is " + ProtocolVersion );
5737 }
5738
5739 /**
5740 * Option specifying the maximum number of unread results to be cached in
5741 * any LDAPSearchResults without suspending reading from the server
5742 * @see org.ietf.ldap.LDAPConnection#getOption
5743 * @see org.ietf.ldap.LDAPConnection#setOption
5744 */
5745 public static final int MAXBACKLOG = 30;
5746
5747 private static boolean isCommunicator = checkCommunicator();
5748 private static boolean debug = false;
5749 }