Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *    Purpose: An implementation of the AuthInterface interface that
4
 *             allows Metacat to use the LDAP protocol for
5
 *             directory services
6
 *  Copyright: 2000 Regents of the University of California and the
7
 *             National Center for Ecological Analysis and Synthesis
8
 *    Authors: Matt Jones
9
 *    Release: @release@
10
 *
11
 *   '$Author: sgarg $'
12
 *     '$Date: 2005-10-10 12:27:12 -0700 (Mon, 10 Oct 2005) $'
13
 * '$Revision: 2668 $'
14
 *
15
 * This program is free software; you can redistribute it and/or modify
16
 * it under the terms of the GNU General Public License as published by
17
 * the Free Software Foundation; either version 2 of the License, or
18
 * (at your option) any later version.
19
 *
20
 * This program is distributed in the hope that it will be useful,
21
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23
 * GNU General Public License for more details.
24
 *
25
 * You should have received a copy of the GNU General Public License
26
 * along with this program; if not, write to the Free Software
27
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
28
 */
29

    
30
package edu.ucsb.nceas.metacat;
31

    
32
import java.net.ConnectException;
33
import javax.naming.AuthenticationException;
34
import javax.naming.Context;
35
import javax.naming.NamingEnumeration;
36
import javax.naming.NamingException;
37
import javax.naming.SizeLimitExceededException;
38
import javax.naming.InitialContext;
39
import javax.naming.directory.InvalidSearchFilterException;
40
import javax.naming.directory.Attribute;
41
import javax.naming.directory.Attributes;
42
import javax.naming.directory.BasicAttribute;
43
import javax.naming.directory.BasicAttributes;
44
import javax.naming.directory.DirContext;
45
import javax.naming.directory.InitialDirContext;
46
import javax.naming.directory.SearchResult;
47
import javax.naming.directory.SearchControls;
48
import javax.naming.ReferralException;
49
import javax.naming.ldap.*;
50

    
51
import org.apache.log4j.Logger;
52

    
53
import java.net.URLDecoder;
54
import java.util.Iterator;
55
import java.util.HashMap;
56
import java.util.Hashtable;
57
import java.util.Enumeration;
58
import java.util.Set;
59
import java.util.Vector;
60

    
61
/**
62
 * An implementation of the AuthInterface interface that
63
 * allows Metacat to use the LDAP protocol for directory services.
64
 * The LDAP authentication service is used to determine if a user
65
 * is authenticated, and whether they are a member of a particular group.
66
 */
67
public class AuthLdap
68
    implements AuthInterface, Runnable {
69
  private MetaCatUtil util = new MetaCatUtil();
70
  private String ldapUrl;
71
  private String ldapsUrl;
72
  private String ldapBase;
73
  private String referral;
74
  private Context referralContext;
75
  Hashtable env = new Hashtable(11);
76
  private Context rContext;
77
  private String userName;
78
  private String userPassword;
79
  ReferralException refExc;
80

    
81
  private static Logger logMetacat = Logger.getLogger(AuthLdap.class);
82
  
83
  /**
84
   * Construct an AuthLdap
85
   */
86
  public AuthLdap() {
87
    // Read LDAP URI for directory service information
88
    this.ldapUrl = MetaCatUtil.getOption("ldapurl");
89
    this.ldapsUrl = MetaCatUtil.getOption("ldapsurl");
90
    this.ldapBase = MetaCatUtil.getOption("ldapbase");
91
    this.referral = MetaCatUtil.getOption("referral");
92
  }
93

    
94
  /**
95
   * Determine if a user/password are valid according to the authentication
96
   * service.
97
   *
98
   * @param user the name of the principal to authenticate
99
   * @param password the password to use for authentication
100
   * @returns boolean true if authentication successful, false otherwise
101
   */
102
  public boolean authenticate(String user, String password) throws
103
      ConnectException {
104
    String ldapUrl = this.ldapUrl;
105
    String ldapsUrl = this.ldapsUrl;
106
    String ldapBase = this.ldapBase;
107
    boolean authenticated = false;
108
    String identifier = user;
109
    //get uid here.
110
    //uid=user.substring(0, user.indexOf(","));
111

    
112
    try {
113
      // Check the usename as passed in
114
      authenticated = ldapAuthenticate(identifier, password);
115
      // if not found, try looking up a valid DN then auth again
116
      if (!authenticated) {
117
        logMetacat.info("Looking up DN for: " + identifier);
118
        identifier = getIdentifyingName(identifier, ldapUrl, ldapBase);
119
        logMetacat.info("DN found: " + identifier);
120
        String decoded = URLDecoder.decode(identifier);
121
        logMetacat.info("DN decoded: " + decoded);
122
        identifier = decoded;
123
        String refUrl = "";
124
        String refBase = "";
125
        if (identifier.startsWith("ldap")) {
126
          refUrl = identifier.substring(0,
127
                                        identifier.lastIndexOf("/") + 1);
128
          logMetacat.info("Ref ldapUrl: " + refUrl);
129
          int position = identifier.indexOf(",");
130
          int position2 = identifier.indexOf(",", position + 1);
131
          refBase = identifier.substring(position2 + 1);
132
          logMetacat.info("Ref ldapBase: " + refBase);
133
          identifier = identifier.substring(
134
              identifier.lastIndexOf("/") + 1);
135
          logMetacat.info("Trying: " + identifier);
136
          authenticated = ldapAuthenticate(identifier, password,
137
                                           refUrl, refBase);
138
        }
139
        else {
140
          identifier = identifier + "," + ldapBase;
141
          logMetacat.info("Trying: " + identifier);
142
          authenticated = ldapAuthenticate(identifier, password);
143
        }
144
        //authenticated = ldapAuthenticate(identifier, password);
145
      }
146

    
147
    }
148
    catch (NullPointerException e) {
149
      logMetacat.error("NullPointerException b' password is null");
150
      logMetacat.error("NullPointerException while authenticating in " +
151
                        "AuthLdap.authenticate: " + e);
152
      throw new ConnectException(
153
          "NullPointerException while authenticating in " +
154
          "AuthLdap.authenticate: " + e);
155
    }
156
    catch (NamingException e) {
157
      logMetacat.error("Naming exception while authenticating in " +
158
                        "AuthLdap.authenticate: " + e);
159
      e.printStackTrace();
160
    }
161
    catch (Exception e) {
162
      logMetacat.error(e.getMessage());
163
    }
164
    return authenticated;
165
  }
166

    
167
  /**
168
   * Connect to the LDAP directory and do the authentication using the
169
   * username and password as passed into the routine.
170
   *
171
   * @param identifier the distinguished name to check against LDAP
172
   * @param password the password for authentication
173
   */
174
  private boolean ldapAuthenticate(String identifier, String password) throws
175
      ConnectException, NamingException, NullPointerException {
176
    return ldapAuthenticate(identifier, password,
177
                            this.ldapsUrl, this.ldapBase);
178
  }
179

    
180
  /**
181
   * Connect to the LDAP directory and do the authentication using the
182
   * username and password as passed into the routine.
183
   *
184
   * @param identifier the distinguished name to check against LDAP
185
   * @param password the password for authentication
186
   */
187
  private boolean ldapAuthenticate(String identifier, String password,
188
                                   String directoryUrl, String searchBase) throws
189
      ConnectException, NamingException, NullPointerException {
190
    double totStartTime = System.currentTimeMillis();
191
    boolean authenticated = false;
192
    if (identifier != null && !password.equals("")) {
193

    
194
      //Pass the username and password to run() method
195
      userName = identifier;
196
      userPassword = password;
197
      // Identify service provider to use
198
      Hashtable env = new Hashtable(11);
199
      env.put(Context.INITIAL_CONTEXT_FACTORY,
200
              "com.sun.jndi.ldap.LdapCtxFactory");
201
      env.put(Context.REFERRAL, "throw");
202
      env.put(Context.PROVIDER_URL, directoryUrl + searchBase);
203
      logMetacat.info("PROVIDER_URL set to: " + directoryUrl + searchBase);
204
      if (!ldapsUrl.equals(ldapUrl)) {
205
        // ldap is set on default port 389
206
        // ldaps is set on second port - 636 by default
207
        // env.put(Context.SECURITY_PROTOCOL, "ssl");
208
       }
209
      env.put(Context.SECURITY_AUTHENTICATION, "simple");
210
      env.put(Context.SECURITY_PRINCIPAL, identifier);
211
      env.put(Context.SECURITY_CREDENTIALS, password);
212
      // If our auth credentials are invalid, an exception will be thrown
213
      DirContext ctx = null;
214
      try {
215
        double startTime = System.currentTimeMillis();
216
        //Here to check the authorization
217
        ctx = new InitialDirContext(env);
218
        double stopTime = System.currentTimeMillis();
219
        logMetacat.info("Connection time thru " + ldapsUrl + " was: " +
220
                          (stopTime - startTime) / 1000 + " seconds.");
221
        authenticated = true;
222
        //tls.close();
223
        ctx.close();
224
        this.ldapUrl = ldapUrl;
225
        this.ldapBase = ldapBase;
226
        //break;
227
      }
228
      catch (AuthenticationException ae) {
229
        authenticated = false;
230
        if (ctx != null) {
231
          ctx.close();
232
        }
233
      }
234
      catch (javax.naming.InvalidNameException ine) {
235
        logMetacat.error("An invalid DN was provided!");
236
      }
237
      catch (javax.naming.ReferralException re) {
238
        logMetacat.error("referral during authentication");
239
        logMetacat.error("Referral information: " + re.getReferralInfo());
240
        try {
241
          refExc = re;
242

    
243
          Thread t = new Thread(this);
244
          t.start();
245
          Thread.sleep(5000); //this is a manual override of ldap's
246
          //hideously long time out period.
247
          logMetacat.info("Awake after 5 seconds.");
248
          if (referralContext == null) {
249
            t.interrupt();
250
            authenticated = false;
251
          }
252
          else {
253
            authenticated = true;
254
          }
255
        }
256
        catch (Exception e) {
257
          authenticated = false;
258
        }
259
      }
260
    }
261
    else {
262
      logMetacat.info("User not found");
263
    }
264
    double totStopTime = System.currentTimeMillis();
265
    logMetacat.warn("total ldap authentication time: " +
266
                      (totStopTime - totStartTime) / 1000 + " seconds");
267
    return authenticated;
268
  }
269

    
270
  /**
271
   * Get the identifying name for a given userid or name.  This is the name
272
   * that is used in conjunction withthe LDAP BaseDN to create a
273
   * distinguished name (dn) for the record
274
   *
275
   * @param user the user for which the identifying name is requested
276
   * @returns String the identifying name for the user,
277
   *          or null if not found
278
   */
279
  private String getIdentifyingName(String user, String ldapUrl,
280
                                    String ldapBase) throws NamingException {
281
    String identifier = null;
282
    // Identify service provider to use
283
    Hashtable env = new Hashtable(11);
284
    env.put(Context.INITIAL_CONTEXT_FACTORY,
285
            "com.sun.jndi.ldap.LdapCtxFactory");
286
    logMetacat.info("setting referrals to: " + referral);
287
    env.put(Context.REFERRAL, referral);
288
    env.put(Context.PROVIDER_URL, ldapUrl + ldapBase);
289
    //    non-secure LDAP context; dn are publicly readable
290
    try {
291

    
292
      // Bind to the LDAP server, in order to search for the right
293
      // distinguished name (dn) based on userid (uid) or common name (cn)
294
      DirContext ctx = new InitialDirContext(env);
295
      SearchControls ctls = new SearchControls();
296
      ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
297
      // Search for the user id or name using the uid, then cn and sn
298
      //attributes
299
      // If we find a record, determine the dn for the record
300
      // The following blocks need to be refactored into a subroutine
301
      // they have a ridiculous amount of redundancy
302

    
303
      // Parse out the uid and org components and look up the real DN
304
      // This assumes a dn like "uid=x,o=y,dc=someinst,dc=org"
305
      int position = user.indexOf(",");
306
      String comp1 = user.substring(0, position);
307
      logMetacat.info("First comp is: " + comp1);
308
      String comp2 = user.substring(position + 1,
309
                                    user.indexOf(",", position + 1));
310
      logMetacat.info("Second comp is: " + comp2);
311

    
312
      //String filter = "(&(" + comp1 + "))";
313
      String filter = "(&(" + comp1 + ")(" + comp2 + "))";
314
      logMetacat.info("Filter is: " + filter);
315
      logMetacat.info("Provider URL is: " + ldapUrl + ldapBase);
316
      NamingEnumeration answer;
317
      try {
318
        logMetacat.info("Trying search 1: " + filter);
319
        answer = ctx.search("", filter, ctls);
320
        logMetacat.info("Search 1 complete");
321
        if (answer == null) {
322
          logMetacat.info("Search 1 answer is null.");
323
        }
324
        if (answer.hasMore()) {
325
          logMetacat.info("Search 1 has answers.");
326
          SearchResult sr = (SearchResult) answer.next();
327
          identifier = sr.getName();
328
          logMetacat.info("Originally Found: " + identifier);
329
          return identifier;
330
        }
331
      }
332
      catch (InvalidSearchFilterException e) {
333
        logMetacat.error("Invalid Filter exception thrown (if1)");
334
      }
335

    
336
      // That failed, so check if it is just a username
337
      filter = "(" + user + ")";
338
      try {
339
        logMetacat.info("Trying again: " + filter);
340
        answer = ctx.search("", filter, ctls);
341
        if (answer.hasMore()) {
342
          SearchResult sr = (SearchResult) answer.next();
343
          identifier = sr.getName();
344
          if (!sr.isRelative()) {
345
            this.ldapUrl = identifier.substring(0,
346
                                                identifier.lastIndexOf("/") + 1);
347
            this.ldapBase = identifier.substring(identifier.indexOf(",") + 1);
348
            identifier = identifier.substring(identifier.lastIndexOf("/") + 1,
349
                                              identifier.indexOf(","));
350
          }
351
          logMetacat.info("Found: " + identifier);
352
          return identifier;
353
        }
354
      }
355
      catch (InvalidSearchFilterException e) {}
356

    
357
      // Maybe its a user id (uid)
358
      filter = "(uid=" + user + ")";
359
      logMetacat.info("Trying again: " + filter);
360
      answer = ctx.search("", filter, ctls);
361
      if (answer.hasMore()) {
362
        SearchResult sr = (SearchResult) answer.next();
363
        identifier = sr.getName();
364
        if (!sr.isRelative()) {
365
          this.ldapUrl = identifier.substring(0,
366
                                              identifier.lastIndexOf("/") + 1);
367
          this.ldapBase = identifier.substring(identifier.indexOf(",") + 1);
368
          identifier = identifier.substring(identifier.lastIndexOf("/") + 1,
369
                                            identifier.indexOf(","));
370
        }
371
        logMetacat.info("Found: " + identifier);
372
      }
373
      else {
374

    
375
        // maybe its just a common name
376
        filter = "(cn=" + user + ")";
377
        logMetacat.info("Trying again: " + filter);
378
        NamingEnumeration answer2 = ctx.search("", filter, ctls);
379
        if (answer2.hasMore()) {
380
          SearchResult sr = (SearchResult) answer2.next();
381
          identifier = sr.getName();
382
          if (!sr.isRelative()) {
383
            this.ldapUrl = identifier.substring(0,
384
                                                identifier.lastIndexOf("/") + 1);
385
            this.ldapBase = identifier.substring(identifier.indexOf(",") + 1);
386
            identifier = identifier.substring(identifier.lastIndexOf("/") + 1,
387
                                              identifier.indexOf(","));
388
          }
389
          logMetacat.info("Found: " + identifier);
390
        }
391
        else {
392

    
393
          // ok, last resort, is it a surname?
394
          filter = "(sn=" + user + ")";
395
          logMetacat.info("Trying again: " + filter);
396
          NamingEnumeration answer3 = ctx.search("", filter, ctls);
397
          if (answer3.hasMore()) {
398
            SearchResult sr = (SearchResult) answer3.next();
399
            identifier = sr.getName();
400
            if (!sr.isRelative()) {
401
              this.ldapUrl = identifier.substring(0,
402
                                                  identifier.lastIndexOf("/") +
403
                                                  1);
404
              this.ldapBase = identifier.substring(identifier.indexOf(",") + 1);
405
              identifier = identifier.substring(identifier.lastIndexOf("/") + 1,
406
                                                identifier.indexOf(","));
407
            }
408
            logMetacat.info("Found: " + identifier);
409
          }
410
        }
411
      }
412
      // Close the context when we're done the initial search
413
      ctx.close();
414
    }
415
    catch (NamingException e) {
416
      logMetacat.error("Naming exception while getting dn: " + e);
417
      throw new NamingException(
418
          "Naming exception in AuthLdap.getIdentifyingName: " + e);
419
    }
420
    logMetacat.error("Returning found identifier as: " + identifier);
421
    return identifier;
422
  }
423

    
424
  /**
425
   * Get all users from the authentication service
426
   *
427
   * @param user the user for authenticating against the service
428
   * @param password the password for authenticating against the service
429
   * @returns string array of all of the user names
430
   */
431
  public String[][] getUsers(String user, String password) throws
432
      ConnectException {
433
    String[][] users = null;
434

    
435
    // Identify service provider to use
436
    Hashtable env = new Hashtable(11);
437
    env.put(Context.INITIAL_CONTEXT_FACTORY,
438
            "com.sun.jndi.ldap.LdapCtxFactory");
439
    env.put(Context.REFERRAL, referral);
440
    env.put(Context.PROVIDER_URL, ldapUrl);
441

    
442
    try {
443

    
444
      // Create the initial directory context
445
      DirContext ctx = new InitialDirContext(env);
446

    
447
      // Specify the attributes to match.
448
      // Users are objects that have the attribute objectclass=InetOrgPerson.
449
      SearchControls ctls = new SearchControls();
450
      String[] attrIDs = {
451
          "dn", "cn", "o", "ou", "mail"};
452
      ctls.setReturningAttributes(attrIDs);
453
      ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
454
      //ctls.setCountLimit(1000);
455
      String filter = "(objectClass=inetOrgPerson)";
456
      NamingEnumeration namingEnum = ctx.search(ldapBase, filter, ctls);
457

    
458
      // Store the users in a vector
459
      Vector uvec = new Vector();
460
      Vector uname = new Vector();
461
      Vector uorg = new Vector();
462
      Vector uou = new Vector();
463
      Vector umail = new Vector();
464
      Attributes tempAttr = null;
465
      try {
466
        while (namingEnum.hasMore()) {
467
          SearchResult sr = (SearchResult) namingEnum.next();
468
          tempAttr = sr.getAttributes();
469

    
470
          if ( (tempAttr.get("cn") + "").startsWith("cn: ")) {
471
            uname.add( (tempAttr.get("cn") + "").substring(4));
472
          }
473
          else {
474
            uname.add(tempAttr.get("cn") + "");
475
          }
476

    
477
          if ( (tempAttr.get("o") + "").startsWith("o: ")) {
478
            uorg.add( (tempAttr.get("o") + "").substring(3));
479
          }
480
          else {
481
            uorg.add(tempAttr.get("o") + "");
482
          }
483

    
484
          if ( (tempAttr.get("ou") + "").startsWith("ou: ")) {
485
            uou.add( (tempAttr.get("ou") + "").substring(4));
486
          }
487
          else {
488
            uou.add(tempAttr.get("ou") + "");
489
          }
490

    
491
          if ( (tempAttr.get("mail") + "").startsWith("mail: ")) {
492
            umail.add( (tempAttr.get("mail") + "").substring(6));
493
          }
494
          else {
495
            umail.add(tempAttr.get("mail") + "");
496
          }
497

    
498
          uvec.add(sr.getName() + "," + ldapBase);
499
        }
500
      }
501
      catch (SizeLimitExceededException slee) {
502
        logMetacat.error("LDAP Server size limit exceeded. " +
503
                          "Returning incomplete record set.");
504
      }
505

    
506
      // initialize users[]; fill users[]
507
      users = new String[uvec.size()][5];
508
      for (int i = 0; i < uvec.size(); i++) {
509
        users[i][0] = (String) uvec.elementAt(i);
510
        users[i][1] = (String) uname.elementAt(i);
511
        users[i][2] = (String) uorg.elementAt(i);
512
        users[i][3] = (String) uorg.elementAt(i);
513
        users[i][4] = (String) umail.elementAt(i);
514
      }
515

    
516
      // Close the context when we're done
517
      ctx.close();
518

    
519
    }
520
    catch (NamingException e) {
521
      logMetacat.error("Problem getting users in AuthLdap.getUsers:" + e);
522
      //e.printStackTrace(System.err);
523
      throw new ConnectException(
524
          "Problem getting users in AuthLdap.getUsers:" + e);
525
    }
526

    
527
    return users;
528
  }
529

    
530
  /**
531
   * Get the users for a particular group from the authentication service
532
   *
533
   * @param user the user for authenticating against the service
534
   * @param password the password for authenticating against the service
535
   * @param group the group whose user list should be returned
536
   * @returns string array of the user names belonging to the group
537
   */
538
  public String[] getUsers(String user, String password, String group) throws
539
      ConnectException {
540
    String[] users = null;
541

    
542
    // Identify service provider to use
543
    Hashtable env = new Hashtable(11);
544
    env.put(Context.INITIAL_CONTEXT_FACTORY,
545
            "com.sun.jndi.ldap.LdapCtxFactory");
546
    env.put(Context.REFERRAL, referral);
547
    env.put(Context.PROVIDER_URL, ldapUrl);
548

    
549
    try {
550

    
551
      // Create the initial directory context
552
      DirContext ctx = new InitialDirContext(env);
553

    
554
      // Specify the ids of the attributes to return
555
      String[] attrIDs = {
556
          "uniqueMember"};
557

    
558
      Attributes answer = ctx.getAttributes(group, attrIDs);
559

    
560
      Vector uvec = new Vector();
561
      try {
562
        for (NamingEnumeration ae = answer.getAll(); ae.hasMore(); ) {
563
          Attribute attr = (Attribute) ae.next();
564
          for (NamingEnumeration e = attr.getAll();
565
               e.hasMore();
566
               uvec.add(e.next())
567
               ) {
568
            ;
569
          }
570
        }
571
      }
572
      catch (SizeLimitExceededException slee) {
573
        logMetacat.error("LDAP Server size limit exceeded. " +
574
                          "Returning incomplete record set.");
575
      }
576

    
577
      // initialize users[]; fill users[]
578
      users = new String[uvec.size()];
579
      for (int i = 0; i < uvec.size(); i++) {
580
        users[i] = (String) uvec.elementAt(i);
581
      }
582

    
583
      // Close the context when we're done
584
      ctx.close();
585

    
586
    }
587
    catch (NamingException e) {
588
      logMetacat.error("Problem getting users for a group in " +
589
                        "AuthLdap.getUsers:" + e);
590
      throw new ConnectException(
591
          "Problem getting users for a group in AuthLdap.getUsers:" + e);
592
    }
593

    
594
    return users;
595
  }
596

    
597
  /**
598
   * Get all groups from the authentication service
599
   *
600
   * @param user the user for authenticating against the service
601
   * @param password the password for authenticating against the service
602
   * @returns string array of the group names
603
   */
604
  public String[][] getGroups(String user, String password) throws
605
      ConnectException {
606
    return getGroups(user, password, null);
607
  }
608

    
609
  /**
610
   * Get the groups for a particular user from the authentication service
611
   *
612
   * @param user the user for authenticating against the service
613
   * @param password the password for authenticating against the service
614
   * @param foruser the user whose group list should be returned
615
   * @returns string array of the group names
616
   */
617
  public String[][] getGroups(String user, String password, String foruser) throws
618
      ConnectException {
619
    Vector gvec = new Vector();
620
    Vector desc = new Vector();
621
    Attributes tempAttr = null;
622

    
623
    //Pass the username and password to run() method
624
    userName = user;
625
    userPassword = password;
626
    // Identify service provider to use
627
    env.put(Context.INITIAL_CONTEXT_FACTORY,
628
            "com.sun.jndi.ldap.LdapCtxFactory");
629
    env.put(Context.REFERRAL, "throw");
630
    env.put(Context.PROVIDER_URL, ldapUrl);
631
    try {
632
      // Create the initial directory context
633
      DirContext ctx = new InitialDirContext(env);
634
      // Specify the ids of the attributes to return
635
      String[] attrIDs = {
636
          "cn", "o", "description"};
637
      // Specify the attributes to match.
638
      // Groups are objects with attribute objectclass=groupofuniquenames.
639
      // and have attribute uniquemember: uid=foruser,ldapbase.
640
      SearchControls ctls = new SearchControls();
641
      ctls.setReturningAttributes(attrIDs);
642
      ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
643

    
644
      String filter = null;
645
      String gfilter = "(objectClass=groupOfUniqueNames)";
646
      if (null == foruser) {
647
        filter = gfilter;
648
      }
649
      else {
650
        filter = "(& " + gfilter + "(uniqueMember=" + foruser + "))";
651
      }
652
      logMetacat.info("searching for groups: " + filter);
653
      NamingEnumeration namingEnum = ctx.search(ldapBase, filter, ctls);
654

    
655
      // Print the groups
656
      logMetacat.info("getting group results.");
657
      while (namingEnum.hasMore()) {
658
        SearchResult sr = (SearchResult) namingEnum.next();
659
        tempAttr = sr.getAttributes();
660

    
661
        if ( (tempAttr.get("description") + "").startsWith("description: ")) {
662
          desc.add( (tempAttr.get("description") + "").substring(13));
663
        }
664
        else {
665
          desc.add(tempAttr.get("description") + "");
666
        }
667

    
668
        gvec.add(sr.getName() + "," + ldapBase);
669
        logMetacat.info("group " + sr.getName() +
670
                                 " added to Group vector");
671
      }
672
      // Close the context when we're done
673
      ctx.close();
674

    
675
    }
676
    catch (ReferralException re) {
677
      refExc = re;
678
      Thread t = new Thread(new GetGroup());
679
      logMetacat.info("Starting thread...");
680
      t.start();
681
      logMetacat.info("sleeping for 5 seconds.");
682
      try {
683
        Thread.sleep(5000);
684
      }
685
      catch (InterruptedException ie) {
686
        logMetacat.error("main thread interrupted: " + ie.getMessage());
687
      }
688
      //this is a manual override of jndi's hideously long time
689
      //out period.
690
      logMetacat.info("Awake after 5 seconds.");
691
      if (referralContext == null) {
692
        logMetacat.info("thread timed out...returning groups: " +
693
                          gvec.toString());
694
        String groups[][] = new String[gvec.size()][2];
695
        for (int i = 0; i < gvec.size(); i++) {
696
          groups[i][0] = (String) gvec.elementAt(i);
697
          groups[i][1] = (String) desc.elementAt(i);
698
        }
699
        t.interrupt();
700
        return groups;
701
      }
702
      DirContext dc = (DirContext) referralContext;
703
      String[] attrIDs = {
704
          "cn", "o", "description"};
705
      // Specify the attributes to match.
706
      // Groups are objects with attribute objectclass=groupofuniquenames.
707
      // and have attribute uniquemember: uid=foruser,ldapbase.
708
      SearchControls ctls = new SearchControls();
709
      ctls.setReturningAttributes(attrIDs);
710
      ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
711

    
712
      String filter = null;
713
      String gfilter = "(objectClass=groupOfUniqueNames)";
714
      if (null == foruser) {
715
        filter = gfilter;
716
      }
717
      else {
718
        filter = "(& " + gfilter + "(uniqueMember=" + foruser + "))";
719
      }
720

    
721
      try {
722
        NamingEnumeration namingEnum = dc.search(ldapBase, filter, ctls);
723
        // Print the groups
724
        while (namingEnum.hasMore()) {
725
          SearchResult sr = (SearchResult) namingEnum.next();
726
          tempAttr = sr.getAttributes();
727

    
728
          if ( (tempAttr.get("description") + "").startsWith("description: ")) {
729
            desc.add( (tempAttr.get("description") + "").substring(13));
730
          }
731
          else {
732
            desc.add(tempAttr.get("description") + "");
733
          }
734

    
735
          gvec.add(sr.getName() + "," + ldapBase);
736
        }
737

    
738
        referralContext.close();
739
        dc.close();
740
      }
741
      catch (NamingException ne) {
742
        logMetacat.warn("Naming Exception in AuthLdap.getGroups" +
743
                                 ne.getExplanation() + ne.getMessage());
744
      }
745
    }
746
    catch (NamingException e) {
747
      e.printStackTrace(System.err);
748
      String groups[][] = new String[gvec.size()][2];
749
      for (int i = 0; i < gvec.size(); i++) {
750
        groups[i][0] = (String) gvec.elementAt(i);
751
        groups[i][1] = (String) desc.elementAt(i);
752
      }
753
      return groups;
754
      /*throw new ConnectException(
755
             "Problem getting groups for a user in AuthLdap.getGroups:" + e);*/
756
    }
757

    
758
    logMetacat.warn("The user is in the following groups: " +
759
                             gvec.toString());
760
    String groups[][] = new String[gvec.size()][2];
761
    for (int i = 0; i < gvec.size(); i++) {
762
      groups[i][0] = (String) gvec.elementAt(i);
763
      groups[i][1] = (String) desc.elementAt(i);
764
    }
765
    return groups;
766
  }
767

    
768
  /**
769
   * Get attributes describing a user or group
770
   *
771
   * @param foruser the user for which the attribute list is requested
772
   * @returns HashMap a map of attribute name to a Vector of values
773
   */
774
  public HashMap getAttributes(String foruser) throws ConnectException {
775
    return getAttributes(null, null, foruser);
776
  }
777

    
778
  /**
779
   * Get attributes describing a user or group
780
   *
781
   * @param user the user for authenticating against the service
782
   * @param password the password for authenticating against the service
783
   * @param foruser the user whose attributes should be returned
784
   * @returns HashMap a map of attribute name to a Vector of values
785
   */
786
  public HashMap getAttributes(String user, String password, String foruser) throws
787
      ConnectException {
788
    HashMap attributes = new HashMap();
789
    String ldapUrl = this.ldapUrl;
790
    String ldapBase = this.ldapBase;
791
    String userident = foruser;
792

    
793
    // Identify service provider to use
794
    Hashtable env = new Hashtable(11);
795
    env.put(Context.INITIAL_CONTEXT_FACTORY,
796
            "com.sun.jndi.ldap.LdapCtxFactory");
797
    env.put(Context.REFERRAL, referral);
798
    env.put(Context.PROVIDER_URL, ldapUrl);
799

    
800
    try {
801

    
802
      // Create the initial directory context
803
      DirContext ctx = new InitialDirContext(env);
804

    
805
      // Ask for all attributes of the user
806
      //Attributes attrs = ctx.getAttributes(userident);
807
      Attributes attrs = ctx.getAttributes(foruser);
808

    
809
      // Print all of the attributes
810
      NamingEnumeration en = attrs.getAll();
811
      while (en.hasMore()) {
812
        Attribute att = (Attribute) en.next();
813
        Vector values = new Vector();
814
        String attName = att.getID();
815
        NamingEnumeration attvalues = att.getAll();
816
        while (attvalues.hasMore()) {
817
          String value = (String) attvalues.next();
818
          values.add(value);
819
        }
820
        attributes.put(attName, values);
821
      }
822

    
823
      // Close the context when we're done
824
      ctx.close();
825
    }
826
    catch (NamingException e) {
827
      logMetacat.error("Problem getting attributes in " +
828
                        "AuthLdap.getAttributes:" + e);
829
      throw new ConnectException(
830
          "Problem getting attributes in AuthLdap.getAttributes:" + e);
831
    }
832

    
833
    return attributes;
834
  }
835

    
836
  /**
837
   * Get list of all subtrees holding Metacat's groups and users
838
   * starting from the Metacat LDAP root,
839
   * i.e. ldap://dev.nceas.ucsb.edu/dc=ecoinformatics,dc=org
840
   */
841
  private Hashtable getSubtrees(String user, String password,
842
                                String ldapUrl, String ldapBase) throws
843
      ConnectException {
844
    Hashtable trees = new Hashtable();
845

    
846
    // Identify service provider to use
847
    Hashtable env = new Hashtable(11);
848
    env.put(Context.INITIAL_CONTEXT_FACTORY,
849
            "com.sun.jndi.ldap.LdapCtxFactory");
850
    // env.put(Context.REFERRAL, referral);
851
    // Using 'ignore' here instead of 'follow' as 'ignore' seems
852
    // to do the job better. 'follow' was not bringing up the UCNRS
853
    // and PISCO tree whereas 'ignore' brings up the tree.
854

    
855
    env.put(Context.REFERRAL, "ignore");
856
    env.put(Context.PROVIDER_URL, ldapUrl + ldapBase);
857

    
858
    try {
859

    
860
      // Create the initial directory context
861
      DirContext ctx = new InitialDirContext(env);
862

    
863
      // Specify the ids of the attributes to return
864
      String[] attrIDs = {
865
          "o", "ref"};
866
      SearchControls ctls = new SearchControls();
867
      ctls.setReturningAttributes(attrIDs);
868
      ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
869

    
870
      // Specify the attributes to match.
871
      // Subtrees from the main server are found as objects with attribute
872
      // objectclass=organization or objectclass=referral to the subtree
873
      // resided on other server.
874
      String filter = "(|(objectclass=organization)(objectclass=referral))";
875

    
876
      // Search for objects in the current context
877
      NamingEnumeration namingEnum = ctx.search("", filter, ctls);
878

    
879
      // Print the subtrees' <ldapURL, baseDN>
880
      while (namingEnum.hasMore()) {
881

    
882
        SearchResult sr = (SearchResult) namingEnum.next();
883

    
884
        Attributes attrs = sr.getAttributes();
885
        NamingEnumeration enum1 = attrs.getAll(); // "dc" and "ref" attrs
886

    
887
        if (enum1.hasMore()) {
888
          Attribute attr = (Attribute) enum1.next();
889
          String attrValue = (String) attr.get();
890
          String attrName = (String) attr.getID();
891

    
892
          if (enum1.hasMore()) {
893
            attr = (Attribute) enum1.next();
894
            String refValue = (String) attr.get();
895
            String refName = (String) attr.getID();
896
            if (ldapBase.startsWith(refName + "=" + refValue)) {
897
              trees.put(ldapBase,
898
                        attrValue.substring(0, attrValue.lastIndexOf("/") + 1));
899
            }
900
            else {
901
              // this is a referral - so organization name is appended in
902
              // front of the ldapbase.... later it is stripped out
903
              // in getPrincipals
904
              trees.put("[" + refName + "=" + refValue + "]" +
905
                        attrValue.substring(attrValue.lastIndexOf("/") + 1,
906
                                            attrValue.length()),
907
                        attrValue.substring(0, attrValue.lastIndexOf("/") + 1));
908

    
909
              // trees.put(refName + "=" + refValue + "," + ldapBase,
910
              //           attrValue.substring(0, attrValue.lastIndexOf("/") + 1));
911
            }
912

    
913
          }
914
          else if (ldapBase.startsWith(attrName + "=" + attrValue)) {
915
            trees.put(ldapBase, ldapUrl);
916
          }
917
          else {
918
            if (sr.isRelative()) {
919
              trees.put(attrName + "=" + attrValue + "," + ldapBase, ldapUrl);
920
            }
921
            else {
922
              String referenceURL = sr.getName();
923
              referenceURL = referenceURL.substring(0,
924
                  referenceURL.lastIndexOf("/") + 1);
925
              trees.put(attrName + "=" + attrValue + "," + ldapBase,
926
                        referenceURL);
927
            }
928

    
929
          }
930
        }
931
      }
932

    
933
      // Close the context when we're done
934
      ctx.close();
935

    
936
    }
937
    catch (NamingException e) {
938
      logMetacat.error("Problem getting subtrees in AuthLdap.getSubtrees:"
939
                        + e);
940
      throw new ConnectException(
941
          "Problem getting subtrees in AuthLdap.getSubtrees:" + e);
942
    }
943

    
944
    return trees;
945
  }
946

    
947
  /**
948
   * Get all groups and users from authentication scheme.
949
   * The output is formatted in XML.
950
   * @param user the user which requests the information
951
   * @param password the user's password
952
   */
953
  public String getPrincipals(String user, String password) throws
954
      ConnectException {
955
    StringBuffer out = new StringBuffer();
956
   
957
    out.append("<?xml version=\"1.0\" encoding=\"US-ASCII\"?>\n");
958
    out.append("<principals>\n");
959

    
960
    /*
961
     * get all subtrees first in the current dir context
962
     * and then the Metacat users under them
963
     */
964
    Hashtable subtrees = getSubtrees(user, password, this.ldapUrl,
965
                                     this.ldapBase);
966

    
967
    Enumeration keyEnum = subtrees.keys();
968
    while (keyEnum.hasMoreElements()) {
969
      this.ldapBase = (String) keyEnum.nextElement();
970
      this.ldapUrl = (String) subtrees.get(ldapBase);
971

    
972
      /*
973
       * code to get the organization name from ldapBase
974
       */
975
      String orgName = this.ldapBase;
976
      if (orgName.startsWith("[")) {
977
        // if orgName starts with [ then it is a referral URL...
978
        // (see code in getSubtress)
979
        // hence orgName can be retrieved  by getting the string between
980
        // 'o=' and ']'
981
        // also the string between [ and ] needs to be striped out from
982
        // this.ldapBase
983
        this.ldapBase = orgName.substring(orgName.indexOf("]") + 1);
984
        if (orgName != null && orgName.indexOf("o=") > -1) {
985
          orgName = orgName.substring(orgName.indexOf("o=") + 2);
986
          orgName = orgName.substring(0, orgName.indexOf("]"));
987
        }
988
      }
989
      else {
990
        // else it is not referral
991
        // hence orgName can be retrieved  by getting the string between
992
        // 'o=' and ','
993
        if (orgName != null && orgName.indexOf("o=") > -1) {
994
          orgName = orgName.substring(orgName.indexOf("o=") + 2);
995
          if (orgName.indexOf(",") > -1) {
996
            orgName = orgName.substring(0, orgName.indexOf(","));
997
          }
998
        }
999
      }
1000

    
1001
      out.append("  <authSystem URI=\"" +
1002
                 this.ldapUrl + this.ldapBase + "\" organization=\"" + orgName +
1003
                 "\">\n");
1004

    
1005
      // get all groups for directory context
1006
      String[][] groups = getGroups(user, password);
1007
      String[][] users = getUsers(user, password);
1008
      int userIndex = 0;
1009

    
1010
      // for the groups and users that belong to them
1011
      if (groups != null && groups.length > 0) {
1012
        for (int i = 0; i < groups.length; i++) {
1013
          out.append("    <group>\n");
1014
          out.append("      <groupname>" + groups[i][0] + "</groupname>\n");
1015
          out.append("      <description>" + groups[i][1] + "</description>\n");
1016
          String[] usersForGroup = getUsers(user, password, groups[i][0]);
1017
          for (int j = 0; j < usersForGroup.length; j++) {
1018
            
1019
            userIndex = searchUser(usersForGroup[j], users);
1020
            out.append("      <user>\n");
1021

    
1022
            if (userIndex < 0) {
1023
              out.append("        <username>" + usersForGroup[j] +
1024
                         "</username>\n");
1025
            }
1026
            else {
1027
              out.append("        <username>" + users[userIndex][0] +
1028
                         "</username>\n");
1029
              out.append("        <name>" + users[userIndex][1] + "</name>\n");
1030
              out.append("        <organization>" + users[userIndex][2] +
1031
                         "</organization>\n");
1032
              if (users[userIndex][3].compareTo("null") != 0) {
1033
                out.append("      <organizationUnitName>" + users[userIndex][3] +
1034
                           "</organizationUnitName>\n");
1035
              }
1036
              out.append("        <email>" + users[userIndex][4] + "</email>\n");
1037
            }
1038

    
1039
            out.append("      </user>\n");
1040
          }
1041
          out.append("    </group>\n");
1042
        }
1043
      }
1044

    
1045
      // for the users not belonging to any grou8p
1046
      for (int j = 0; j < users.length; j++) {
1047
          out.append("    <user>\n");
1048
          out.append("      <username>" + users[j][0] + "</username>\n");
1049
          out.append("      <name>" + users[j][1] + "</name>\n");
1050
          out.append("      <organization>" + users[j][2] +
1051
                     "</organization>\n");
1052
          if (users[j][3].compareTo("null") != 0) {
1053
            out.append("      <organizationUnitName>" + users[j][3] +
1054
                       "</organizationUnitName>\n");
1055
          }
1056
          out.append("      <email>" + users[j][4] + "</email>\n");
1057
          out.append("    </user>\n");
1058
      }
1059

    
1060
      out.append("  </authSystem>\n");
1061
    }
1062
    out.append("</principals>");
1063
    return out.toString();
1064
  }
1065

    
1066
  /**
1067
   * Method for getting index of user DN in User info array
1068
   */
1069
  int searchUser(String user, String userGroup[][]) {
1070
    for (int j = 0; j < userGroup.length; j++) {
1071
      if (user.compareTo(userGroup[j][0]) == 0) {
1072
        return j;
1073
      }
1074
    }
1075
    return -1;
1076
  }
1077

    
1078
  /**
1079
   * Test method for the class
1080
   */
1081
  public static void main(String[] args) {
1082

    
1083
    // Provide a user, such as: "Matt Jones", or "jones"
1084
    String user = args[0];
1085
    String password = args[1];
1086

    
1087
    logMetacat.warn("Creating session...");
1088
    AuthLdap authservice = new AuthLdap();
1089
    logMetacat.warn("Session exists...");
1090

    
1091
    boolean isValid = false;
1092
    try {
1093
      logMetacat.warn("Authenticating...");
1094
      isValid = authservice.authenticate(user, password);
1095
      if (isValid) {
1096
    	  logMetacat.warn("Authentication successful for: " + user);
1097
      }
1098
      else {
1099
        logMetacat.warn("Authentication failed for: " + user);
1100
      }
1101

    
1102
      // Get attributes for the user
1103
      if (isValid) {
1104
        logMetacat.info("\nGetting attributes for user....");
1105
        HashMap userInfo = authservice.getAttributes(user, password, user);
1106
        // Print all of the attributes
1107
        Iterator attList = (Iterator) ( ( (Set) userInfo.keySet()).iterator());
1108
        while (attList.hasNext()) {
1109
          String att = (String) attList.next();
1110
          Vector values = (Vector) userInfo.get(att);
1111
          Iterator attvalues = values.iterator();
1112
          while (attvalues.hasNext()) {
1113
            String value = (String) attvalues.next();
1114
            logMetacat.warn(att + ": " + value);
1115
          }
1116
        }
1117
      }
1118

    
1119
      // get the groups
1120
      if (isValid) {
1121
        logMetacat.warn("\nGetting all groups....");
1122
        String[][] groups = authservice.getGroups(user, password);
1123
        logMetacat.info("Groups found: " + groups.length);
1124
        for (int i = 0; i < groups.length; i++) {
1125
          logMetacat.info("Group " + i + ": " + groups[i][0]);
1126
        }
1127
      }
1128

    
1129
      // get the groups for the user
1130
      String savedGroup = null;
1131
      if (isValid) {
1132
        logMetacat.warn("\nGetting groups for user....");
1133
        String[][] groups = authservice.getGroups(user, password, user);
1134
        logMetacat.info("Groups found: " + groups.length);
1135
        for (int i = 0; i < groups.length; i++) {
1136
          logMetacat.info("Group " + i + ": " + groups[i][0]);
1137
          savedGroup = groups[i][0];
1138
        }
1139
      }
1140

    
1141
      // get the users for a group
1142
      if (isValid) {
1143
        logMetacat.warn("\nGetting users for group....");
1144
        logMetacat.info("Group: " + savedGroup);
1145
        String[] users = authservice.getUsers(user, password, savedGroup);
1146
        logMetacat.info("Users found: " + users.length);
1147
        for (int i = 0; i < users.length; i++) {
1148
          logMetacat.warn("User " + i + ": " + users[i]);
1149
        }
1150
      }
1151

    
1152
      // get all users
1153
      if (isValid) {
1154
        logMetacat.warn("\nGetting all users ....");
1155
        String[][] users = authservice.getUsers(user, password);
1156
        logMetacat.info("Users found: " + users.length);
1157

    
1158
      }
1159

    
1160
      // get the whole list groups and users in XML format
1161
      if (isValid) {
1162
        logMetacat.warn("\nTrying principals....");
1163
        authservice = new AuthLdap();
1164
        String out = authservice.getPrincipals(user, password);
1165
        java.io.File f = new java.io.File("principals.xml");
1166
        java.io.FileWriter fw = new java.io.FileWriter(f);
1167
        java.io.BufferedWriter buff = new java.io.BufferedWriter(fw);
1168
        buff.write(out);
1169
        buff.flush();
1170
        buff.close();
1171
        fw.close();
1172
        logMetacat.warn("\nFinished getting principals.");
1173
      }
1174

    
1175
    }
1176
    catch (ConnectException ce) {
1177
      logMetacat.error(ce.getMessage());
1178
    }
1179
    catch (java.io.IOException ioe) {
1180
      logMetacat.error("I/O Error writing to file principals.txt");
1181
    }
1182
  }
1183

    
1184
  /**
1185
   * This method will be called by start a thread.
1186
   * It can handle if a referral exception happend.
1187
   */
1188
  public void run() {
1189
    referralContext = null;
1190
    DirContext refDirContext = null;
1191
    boolean moreReferrals = true;
1192
    String referralInfo = null;
1193
    //set a while loop is because we don't know if a referral excption contains
1194
    //another referral exception
1195
    while (moreReferrals) {
1196
      try {
1197
        //revise environment variable
1198
        referralInfo = (String) refExc.getReferralInfo();
1199
        logMetacat.info("Processing referral (pr0): ");
1200
        logMetacat.info("PROVIDER_URL set to (pr1): " + referralInfo);
1201
        //env.put(Context.PROVIDER_URL,referralInfo);
1202
        //env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
1203
        //env.put(Context.SECURITY_PRINCIPAL, userName);
1204
        //env.put(Context.SECURITY_CREDENTIALS, userPassword);
1205
        //env.put(Context.REFERRAL, "throw");
1206
        //logMetacat.info("Processing referral (pr1.info): " + userName,35);
1207
        //logMetacat.info("Processing referral (pr2)",35);
1208
        //rContext = refExc.getReferralContext(env);
1209
        rContext = refExc.getReferralContext();
1210
        logMetacat.info("Processing referral (pr3)");
1211
        //casting the context to dircontext and it will create a
1212
        //autherntication or naming exception if DN and password is incorrect
1213
        referralContext = rContext;
1214
        refDirContext = (DirContext) rContext;
1215
        refDirContext.close();
1216
        //get context and jump out the while loop
1217
        moreReferrals = false;
1218
        logMetacat.info("Processing referral (pr4)");
1219
      } //try
1220
      //if referral have another referral excption
1221
      catch (ReferralException re) {
1222
        logMetacat.warn("GOT referral exception (re1): " + re.getMessage());
1223
        logMetacat.warn("RE details (re2): " + re.toString(true));
1224
        //keep running in while loop
1225
        moreReferrals = true;
1226
        //assign refExc to new referral exception re
1227
        refExc = re;
1228
      }
1229
      //catch a authentication exception
1230
      catch (AuthenticationException ae) {
1231
        logMetacat.error("Error running referral handler thread (ae1): " +
1232
                          ae.getMessage());
1233
        //check if has another referral
1234
        moreReferrals = refExc.skipReferral();
1235
        //don't get the context
1236
        referralContext = null;
1237
      }
1238
      //catch a naming exception
1239
      catch (NamingException ne) {
1240
        logMetacat.error("Error running referral handler thread (ne1): " +
1241
                          ne.getMessage());
1242
        //check if has another referral
1243
        moreReferrals = refExc.skipReferral();
1244
        //don't get context
1245
        referralContext = null;
1246
      }
1247
    } //while
1248
  } //run()
1249

    
1250
  private class GetGroup
1251
      implements Runnable {
1252
    public void run() {
1253
      referralContext = null;
1254
      logMetacat.info("getting groups context");
1255
      DirContext refDirContext = null;
1256
      boolean moreReferrals = true;
1257
      //set a while loop is because we don't know if a referral excption
1258
      //contains another referral exception
1259
      while (moreReferrals) {
1260
        try {
1261
          //revise environment variable
1262
          String refInfo = null;
1263
          refInfo = (String) refExc.getReferralInfo();
1264
          if (refInfo != null) {
1265
            logMetacat.info("Referral in thread to: " +
1266
                                     refInfo.toString());
1267
          }
1268
          else {
1269
            logMetacat.info("getting refInfo Manually");
1270
            refInfo = (String) refExc.getReferralContext().getEnvironment().
1271
                get(Context.PROVIDER_URL);
1272
          }
1273
          logMetacat.info("refInfo: " + refInfo);
1274

    
1275
          env.put(Context.INITIAL_CONTEXT_FACTORY,
1276
                  "com.sun.jndi.ldap.LdapCtxFactory");
1277
          env.put(Context.REFERRAL, "throw");
1278
          env.put(Context.PROVIDER_URL, refInfo);
1279

    
1280
          logMetacat.info("creating referralContext");
1281
          referralContext = new InitialDirContext(env);
1282
          logMetacat.info("referralContext created");
1283
          //get context and jump out the while loop
1284
          moreReferrals = false;
1285
        } //try
1286
        catch (ReferralException re) {
1287
          //keep running in while loop
1288
          moreReferrals = true;
1289
          //assign refExc to new referral exception re
1290
          refExc = re;
1291
        }
1292
        catch (AuthenticationException ae) {
1293
          logMetacat.error("Error running referral handler thread (ae2): " +
1294
                            ae.getMessage());
1295
          //check if has another referral
1296
          moreReferrals = refExc.skipReferral();
1297
          //don't get the context
1298
          referralContext = null;
1299
        }
1300
        catch (NamingException ne) {
1301
          logMetacat.error("Error running referral handler thread (ne2): " +
1302
                            ne.getMessage());
1303
          //check if has another referral
1304
          moreReferrals = refExc.skipReferral();
1305
          //don't get context
1306
          referralContext = null;
1307
        }
1308
      } //while
1309
    } //run()
1310
  }
1311
}
(12-12/63)