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
 *
10
 *   '$Author: jones $'
11
 *     '$Date: 2006-11-10 10:25:38 -0800 (Fri, 10 Nov 2006) $'
12
 * '$Revision: 3077 $'
13
 *
14
 * This program is free software; you can redistribute it and/or modify
15
 * it under the terms of the GNU General Public License as published by
16
 * the Free Software Foundation; either version 2 of the License, or
17
 * (at your option) any later version.
18
 *
19
 * This program is distributed in the hope that it will be useful,
20
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22
 * GNU General Public License for more details.
23
 *
24
 * You should have received a copy of the GNU General Public License
25
 * along with this program; if not, write to the Free Software
26
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
27
 */
28

    
29
package edu.ucsb.nceas.metacat;
30

    
31
import java.net.ConnectException;
32
import javax.naming.AuthenticationException;
33
import javax.naming.Context;
34
import javax.naming.NamingEnumeration;
35
import javax.naming.NamingException;
36
import javax.naming.SizeLimitExceededException;
37
import javax.naming.directory.InvalidSearchFilterException;
38
import javax.naming.directory.Attribute;
39
import javax.naming.directory.Attributes;
40
import javax.naming.directory.DirContext;
41
import javax.naming.directory.InitialDirContext;
42
import javax.naming.directory.SearchResult;
43
import javax.naming.directory.SearchControls;
44
import javax.naming.ReferralException;
45
import javax.naming.ldap.InitialLdapContext;
46
import javax.naming.ldap.LdapContext;
47
import javax.naming.ldap.StartTlsRequest;
48
import javax.naming.ldap.StartTlsResponse;
49
import javax.net.ssl.SSLSession;
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
  
103
  public boolean authenticate(String user, String password) throws
104
      ConnectException {
105
    String ldapUrl = this.ldapUrl;
106
    String ldapsUrl = this.ldapsUrl;
107
    String ldapBase = this.ldapBase;
108
    boolean authenticated = false;
109
    String identifier = user;
110
    
111
    //get uid here.
112
    String uid=user.substring(0, user.indexOf(","));
113
    user = user.substring(user.indexOf(","), user.length());
114

    
115
    logMetacat.debug("identifier: " + identifier);
116
    logMetacat.debug("uid: " + uid);
117
    logMetacat.debug("user: " + user);
118
    
119
    try {
120
    	// Check the usename as passed in
121
        logMetacat.info("Calling ldapAuthenticate");
122
        logMetacat.info("with user as identifier: " + identifier);
123

    
124
        authenticated = ldapAuthenticate(identifier, password, 
125
        		(new Boolean(MetaCatUtil.getOption("onlySecureLDAPConnection"))).booleanValue());
126
        // if not found, try looking up a valid DN then auth again
127
        if (!authenticated) {
128
        	logMetacat.info("Not Authenticated");
129
        	logMetacat.info("Looking up DN for: " + identifier);
130
        	identifier = getIdentifyingName(identifier, ldapUrl, ldapBase);
131
        	if(identifier == null){
132
        		logMetacat.info("No DN found from getIdentifyingName");
133
        		return authenticated;
134
        	}
135
        	
136
           	logMetacat.info("DN found from getIdentifyingName: " + identifier);
137
        	String decoded = URLDecoder.decode(identifier);
138
        	logMetacat.info("DN decoded: " + decoded);
139
        	identifier = decoded;
140
        	String refUrl = "";
141
        	String refBase = "";
142
        	if (identifier.startsWith("ldap")) {
143
        		logMetacat.debug("identifier starts with ldap");
144

    
145
        		refUrl = identifier.substring(0, identifier.lastIndexOf("/") + 1);
146
        		int position = identifier.indexOf(",");
147
        		int position2 = identifier.indexOf(",", position + 1);
148
        		
149
        		refBase = identifier.substring(position2 + 1);
150
        		identifier = identifier.substring(identifier.lastIndexOf("/") + 1);
151
        		
152
        		logMetacat.info("Calling ldapAuthenticate");
153
        		logMetacat.info("with user as identifier: " + identifier);
154
        		logMetacat.info("and refUrl as: " + refUrl);
155
        		logMetacat.info("and refBase as: " + refBase);
156

    
157
        		authenticated = ldapAuthenticate(identifier, password, refUrl, refBase,
158
                		(new Boolean(MetaCatUtil.getOption("onlySecureLDAPReferalsConnection")))
159
                			.booleanValue());
160
        	} else {
161
        		logMetacat.info("identifier doesnt start with ldap");
162
        		identifier = identifier + "," + ldapBase;
163
        		
164
        		logMetacat.info("Calling ldapAuthenticate");
165
        		logMetacat.info("with user as identifier: " + identifier);
166
        		
167
        		authenticated = ldapAuthenticate(identifier, password,
168
            		(new Boolean(MetaCatUtil.getOption("onlySecureLDAPConnection"))).booleanValue());
169
        	}
170
        }
171
    }
172
    catch (NullPointerException e) {
173
    	logMetacat.error("NullPointerException while authenticating in " +
174
                        "AuthLdap.authenticate: " + e);
175
    	e.printStackTrace();
176

    
177
    	throw new ConnectException(
178
          "NullPointerException while authenticating in " +
179
          "AuthLdap.authenticate: " + e);
180
    } catch (NamingException e) {
181
    	logMetacat.error("Naming exception while authenticating in " +
182
                        "AuthLdap.authenticate: " + e);
183
    	e.printStackTrace();
184
    } catch (Exception e) {
185
    	logMetacat.error(e.getMessage());
186
    }
187
    
188
    return authenticated;
189
  }
190

    
191
  /**
192
   * Connect to the LDAP directory and do the authentication using the
193
   * username and password as passed into the routine.
194
   *
195
   * @param identifier the distinguished name to check against LDAP
196
   * @param password the password for authentication
197
   */
198
  private boolean ldapAuthenticate(String identifier, String password, 
199
		  boolean secureConnectionOnly) throws ConnectException, NamingException, 
200
		  NullPointerException {
201
    return ldapAuthenticate(identifier, password,
202
                            this.ldapsUrl, this.ldapBase, secureConnectionOnly);
203
  }
204

    
205
  /**
206
   * Connect to the LDAP directory and do the authentication using the
207
   * username and password as passed into the routine.
208
   *
209
   * @param identifier the distinguished name to check against LDAP
210
   * @param password the password for authentication
211
   */
212
  
213
  private boolean ldapAuthenticate(String dn, String password, String rootServer, 
214
		  String rootBase, boolean secureConnectionOnly){
215
	  
216
	  boolean authenticated = false;
217
		
218
	  String server = "";
219
	  String userDN = "";
220
	  logMetacat.info("dn is: " + dn);
221

    
222
	  int position = dn.lastIndexOf("/");
223
      logMetacat.debug("position is: " + position);
224
	  if (position == -1) {
225
		  server = rootServer;
226
		  if(dn.indexOf(userDN) < 0){
227
			  userDN = dn + "," + rootBase;
228
		  } else {
229
			  userDN = dn;
230
		  }
231
		  logMetacat.info("userDN is: " + userDN);
232

    
233
       } else {
234
		  server = dn.substring(0, position+1);
235
		  userDN = dn.substring(position+1);
236
		  logMetacat.info("server is: " + server);
237
		  logMetacat.info("userDN is: " + userDN);
238
	   }
239
		          
240
	   logMetacat.warn("Trying to authenticate: " + userDN);
241
	   logMetacat.warn("          Using server: " + server);
242
		          
243
	   LdapContext ctx = null;
244
	   double startTime;
245
	   double stopTime;
246
	   try {
247
		   Hashtable env = new Hashtable();
248
		   env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
249
		   env.put(Context.PROVIDER_URL, server);
250
		   env.put(Context.REFERRAL, "throw");
251

    
252
		   try {
253
			   
254
			   startTime = System.currentTimeMillis();
255
			   ctx = new InitialLdapContext(env, null);
256
			   
257
			   // Start up TLS here so that we don't pass our jewels in cleartext
258
		       StartTlsResponse tls =
259
		              (StartTlsResponse)ctx.extendedOperation(new StartTlsRequest());
260
		       //tls.setHostnameVerifier(new SampleVerifier());
261
		       SSLSession sess = tls.negotiate();
262
			   
263
		       ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, "simple");
264
			   ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, userDN);
265
			   ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, password);
266
			   ctx.reconnect(null);
267
			   
268
			   stopTime = System.currentTimeMillis();
269
			   logMetacat.info("Connection time thru " + ldapsUrl + " was: " +
270
                       	(stopTime - startTime) / 1000 + " seconds.");
271
			   
272
			   authenticated = true;
273
		   } catch (java.io.IOException ioe) {
274
			   logMetacat.warn("Caught IOException in login while negotiating TLS: "
275
	                                 + ioe.getMessage());
276
			   
277
			   if(secureConnectionOnly){
278
			   	  
279
				   return authenticated;
280
			   
281
			   } else {
282

    
283
				   logMetacat.info("Trying to authenticate without TLS");
284
				   env.put(Context.SECURITY_AUTHENTICATION, "simple");
285
				   env.put(Context.SECURITY_PRINCIPAL, userDN);
286
				   env.put(Context.SECURITY_CREDENTIALS, password);
287
				   
288
				   startTime = System.currentTimeMillis();
289
				   ctx = new InitialLdapContext(env, null);				
290
				   stopTime = System.currentTimeMillis();
291
				   logMetacat.info("Connection time thru " + ldapsUrl + " was: " +
292
	                       	(stopTime - startTime) / 1000 + " seconds.");
293
				   
294
				   authenticated = true;
295
			   }
296
		   }
297
	   } catch (AuthenticationException ae) {
298
		   authenticated = false;
299
	   } catch (javax.naming.InvalidNameException ine) {
300
	        logMetacat.error("An invalid DN was provided!");
301
	   } catch (NamingException e) {
302
		   logMetacat.warn("Caught NamingException in login: " + e.getClass().getName());
303
		   logMetacat.info(e.toString() + "  " + e.getRootCause());
304
       }
305

    
306
       return authenticated;
307
  }
308

    
309

    
310
  /**
311
   * Get the identifying name for a given userid or name.  This is the name
312
   * that is used in conjunction withthe LDAP BaseDN to create a
313
   * distinguished name (dn) for the record
314
   *
315
   * @param user the user for which the identifying name is requested
316
   * @returns String the identifying name for the user,
317
   *          or null if not found
318
   */
319
  private String getIdentifyingName(String user, String ldapUrl,
320
          String ldapBase) throws NamingException {
321
	  
322
      String identifier = null;
323
      Hashtable env = new Hashtable();
324
      env.put(Context.INITIAL_CONTEXT_FACTORY,
325
              "com.sun.jndi.ldap.LdapCtxFactory");
326
      env.put(Context.REFERRAL, "throw");
327
      env.put(Context.PROVIDER_URL, ldapUrl + ldapBase);
328
      try {
329
    	  int position = user.indexOf(",");
330
          String uid = user.substring(user.indexOf("=") + 1, position);
331
          logMetacat.info("uid is: " + uid);
332
          String org = user.substring(user.indexOf("=", position + 1) + 1,
333
                                        user.indexOf(",", position + 1));
334
          logMetacat.info("org is: " + org);
335
           
336
          DirContext sctx = new InitialDirContext(env);
337
          SearchControls ctls = new SearchControls();
338
          ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
339
          String filter = "(&(uid=" + uid + ")(o=" + org + "))";
340
          logMetacat.warn("Searching for DNs with following filter: " + filter);
341
          
342
          for (boolean moreReferrals = true; moreReferrals;) {
343
              try {
344
                  // Perform the search
345
                  NamingEnumeration answer = 
346
                      sctx.search("", filter, ctls);
347

    
348
                  // Return the answer
349
                  while (answer.hasMore()) {
350
                      SearchResult sr = (SearchResult)answer.next();
351
                      identifier = sr.getName();
352
                      return identifier;
353
                  }
354
                  // The search completes with no more referrals
355
                  moreReferrals = false;
356
              } catch (ReferralException e) {
357
            	  logMetacat.info("Got referral: " + e.getReferralInfo());
358
            	  // Point to the new context from the referral
359
                  if (moreReferrals) {
360
                      sctx = (DirContext) e.getReferralContext();
361
                  }
362
              }
363
          }
364
      } catch (NamingException e) {
365
    	     logMetacat.error("Naming exception while getting dn: " + e);
366
    	      throw new NamingException(
367
    	          "Naming exception in AuthLdap.getIdentifyingName: " + e);
368
    	      }
369
      return identifier;
370
  }
371
  
372
  /**
373
   * Get all users from the authentication service
374
   *
375
   * @param user the user for authenticating against the service
376
   * @param password the password for authenticating against the service
377
   * @returns string array of all of the user names
378
   */
379
  public String[][] getUsers(String user, String password) throws
380
      ConnectException {
381
    String[][] users = null;
382

    
383
    // Identify service provider to use
384
    Hashtable env = new Hashtable(11);
385
    env.put(Context.INITIAL_CONTEXT_FACTORY,
386
            "com.sun.jndi.ldap.LdapCtxFactory");
387
    env.put(Context.REFERRAL, referral);
388
    env.put(Context.PROVIDER_URL, ldapUrl);
389

    
390
    try {
391

    
392
      // Create the initial directory context
393
      DirContext ctx = new InitialDirContext(env);
394

    
395
      // Specify the attributes to match.
396
      // Users are objects that have the attribute objectclass=InetOrgPerson.
397
      SearchControls ctls = new SearchControls();
398
      String[] attrIDs = {
399
          "dn", "cn", "o", "ou", "mail"};
400
      ctls.setReturningAttributes(attrIDs);
401
      ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
402
      //ctls.setCountLimit(1000);
403
      String filter = "(objectClass=inetOrgPerson)";
404
      NamingEnumeration namingEnum = ctx.search(ldapBase, filter, ctls);
405

    
406
      // Store the users in a vector
407
      Vector uvec = new Vector();
408
      Vector uname = new Vector();
409
      Vector uorg = new Vector();
410
      Vector uou = new Vector();
411
      Vector umail = new Vector();
412
      Attributes tempAttr = null;
413
      try {
414
        while (namingEnum.hasMore()) {
415
          SearchResult sr = (SearchResult) namingEnum.next();
416
          tempAttr = sr.getAttributes();
417

    
418
          if ( (tempAttr.get("cn") + "").startsWith("cn: ")) {
419
            uname.add( (tempAttr.get("cn") + "").substring(4));
420
          }
421
          else {
422
            uname.add(tempAttr.get("cn") + "");
423
          }
424

    
425
          if ( (tempAttr.get("o") + "").startsWith("o: ")) {
426
            uorg.add( (tempAttr.get("o") + "").substring(3));
427
          }
428
          else {
429
            uorg.add(tempAttr.get("o") + "");
430
          }
431

    
432
          if ( (tempAttr.get("ou") + "").startsWith("ou: ")) {
433
            uou.add( (tempAttr.get("ou") + "").substring(4));
434
          }
435
          else {
436
            uou.add(tempAttr.get("ou") + "");
437
          }
438

    
439
          if ( (tempAttr.get("mail") + "").startsWith("mail: ")) {
440
            umail.add( (tempAttr.get("mail") + "").substring(6));
441
          }
442
          else {
443
            umail.add(tempAttr.get("mail") + "");
444
          }
445

    
446
          uvec.add(sr.getName() + "," + ldapBase);
447
        }
448
      }
449
      catch (SizeLimitExceededException slee) {
450
        logMetacat.error("LDAP Server size limit exceeded. " +
451
                          "Returning incomplete record set.");
452
      }
453

    
454
      // initialize users[]; fill users[]
455
      users = new String[uvec.size()][5];
456
      for (int i = 0; i < uvec.size(); i++) {
457
        users[i][0] = (String) uvec.elementAt(i);
458
        users[i][1] = (String) uname.elementAt(i);
459
        users[i][2] = (String) uorg.elementAt(i);
460
        users[i][3] = (String) uorg.elementAt(i);
461
        users[i][4] = (String) umail.elementAt(i);
462
      }
463

    
464
      // Close the context when we're done
465
      ctx.close();
466

    
467
    }
468
    catch (NamingException e) {
469
      logMetacat.error("Problem getting users in AuthLdap.getUsers:" + e);
470
      //e.printStackTrace(System.err);
471
      throw new ConnectException(
472
          "Problem getting users in AuthLdap.getUsers:" + e);
473
    }
474

    
475
    return users;
476
  }
477

    
478
  
479
  /**
480
   * Get all users from the authentication service
481
   *
482
   * @param user the user for authenticating against the service
483
   * @param password the password for authenticating against the service
484
   * @returns string array of all of the user names
485
   */
486
  public String[] getUserInfo(String user, String password) throws
487
      ConnectException {
488
    String[] userinfo = new String[3];
489

    
490
    // Identify service provider to use
491
    Hashtable env = new Hashtable(11);
492
    env.put(Context.INITIAL_CONTEXT_FACTORY,
493
            "com.sun.jndi.ldap.LdapCtxFactory");
494
    env.put(Context.REFERRAL, referral);
495
    env.put(Context.PROVIDER_URL, ldapUrl);
496

    
497
    try {
498
      
499
      // Create the initial directory context
500
      DirContext ctx = new InitialDirContext(env);
501
      // Specify the attributes to match.
502
      // Users are objects that have the attribute objectclass=InetOrgPerson.
503
      SearchControls ctls = new SearchControls();
504
      String[] attrIDs = {
505
          "cn", "o", "mail"};
506
      ctls.setReturningAttributes(attrIDs);
507
      ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
508
      //ctls.setCountLimit(1000);
509
      // create the filter based on the uid
510
      
511
      String filter = null;
512
      
513
      if(user.indexOf("o=")>0){
514
    	  String tempStr = user.substring(user.indexOf("o="));
515
    	  filter = "(&(" + user.substring(0, user.indexOf(",")) 
516
			+ ")(" + tempStr.substring(0, tempStr.indexOf(",")) 
517
			+ "))";      
518
      } else{
519
    	  filter = "(&(" + user.substring(0, user.indexOf(",")) 
520
			+ "))";          		  
521
      }
522
   	  filter = "(&(" + user.substring(0, user.indexOf(",")) 
523
		+ "))";          		  
524

    
525
      NamingEnumeration namingEnum = ctx.search(user, filter, ctls);
526
      
527
      Attributes tempAttr = null;
528
      try {
529
        while (namingEnum.hasMore()) {
530
          SearchResult sr = (SearchResult) namingEnum.next();
531
          tempAttr = sr.getAttributes();
532

    
533
          if ( (tempAttr.get("cn") + "").startsWith("cn: ")) {
534
        	  userinfo[0] = (tempAttr.get("cn") + "").substring(4);
535
          }
536
          else {
537
        	  userinfo[0] = (tempAttr.get("cn") + "");
538
          }
539

    
540
          if ( (tempAttr.get("o") + "").startsWith("o: ")) {
541
        	  userinfo[1] = (tempAttr.get("o") + "").substring(3);
542
          }
543
          else {
544
        	  userinfo[1] = (tempAttr.get("o") + "");
545
          }
546

    
547
          if ( (tempAttr.get("mail") + "").startsWith("mail: ")) {
548
        	  userinfo[2] =  (tempAttr.get("mail") + "").substring(6);
549
          }
550
          else {
551
        	  userinfo[2] = (tempAttr.get("mail") + "");
552
          }
553
        }
554
      }
555
      catch (SizeLimitExceededException slee) {
556
        logMetacat.error("LDAP Server size limit exceeded. " +
557
                          "Returning incomplete record set.");
558
      }
559

    
560
      // Close the context when we're done
561
      ctx.close();
562

    
563
    }
564
    catch (NamingException e) {
565
      logMetacat.error("Problem getting users in AuthLdap.getUsers:" + e);
566
      //e.printStackTrace(System.err);
567
      throw new ConnectException(
568
          "Problem getting users in AuthLdap.getUsers:" + e);
569
    }
570

    
571
    return userinfo;
572
  }
573

    
574
  /**
575
   * Get the users for a particular group from the authentication service
576
   *
577
   * @param user the user for authenticating against the service
578
   * @param password the password for authenticating against the service
579
   * @param group the group whose user list should be returned
580
   * @returns string array of the user names belonging to the group
581
   */
582
  public String[] getUsers(String user, String password, String group) throws
583
      ConnectException {
584
    String[] users = null;
585

    
586
    // Identify service provider to use
587
    Hashtable env = new Hashtable(11);
588
    env.put(Context.INITIAL_CONTEXT_FACTORY,
589
            "com.sun.jndi.ldap.LdapCtxFactory");
590
    env.put(Context.REFERRAL, referral);
591
    env.put(Context.PROVIDER_URL, ldapUrl);
592

    
593
    try {
594

    
595
      // Create the initial directory context
596
      DirContext ctx = new InitialDirContext(env);
597

    
598
      // Specify the ids of the attributes to return
599
      String[] attrIDs = {
600
          "uniqueMember"};
601

    
602
      Attributes answer = ctx.getAttributes(group, attrIDs);
603

    
604
      Vector uvec = new Vector();
605
      try {
606
        for (NamingEnumeration ae = answer.getAll(); ae.hasMore(); ) {
607
          Attribute attr = (Attribute) ae.next();
608
          for (NamingEnumeration e = attr.getAll();
609
               e.hasMore();
610
               uvec.add(e.next())
611
               ) {
612
            ;
613
          }
614
        }
615
      }
616
      catch (SizeLimitExceededException slee) {
617
        logMetacat.error("LDAP Server size limit exceeded. " +
618
                          "Returning incomplete record set.");
619
      }
620

    
621
      // initialize users[]; fill users[]
622
      users = new String[uvec.size()];
623
      for (int i = 0; i < uvec.size(); i++) {
624
        users[i] = (String) uvec.elementAt(i);
625
      }
626

    
627
      // Close the context when we're done
628
      ctx.close();
629

    
630
    }
631
    catch (NamingException e) {
632
      logMetacat.error("Problem getting users for a group in " +
633
                        "AuthLdap.getUsers:" + e);
634
      throw new ConnectException(
635
          "Problem getting users for a group in AuthLdap.getUsers:" + e);
636
    }
637

    
638
    return users;
639
  }
640

    
641
  /**
642
   * Get all groups from the authentication service
643
   *
644
   * @param user the user for authenticating against the service
645
   * @param password the password for authenticating against the service
646
   * @returns string array of the group names
647
   */
648
  public String[][] getGroups(String user, String password) throws
649
      ConnectException {
650
    return getGroups(user, password, null);
651
  }
652

    
653
  /**
654
   * Get the groups for a particular user from the authentication service
655
   *
656
   * @param user the user for authenticating against the service
657
   * @param password the password for authenticating against the service
658
   * @param foruser the user whose group list should be returned
659
   * @returns string array of the group names
660
   */
661
  public String[][] getGroups(String user, String password, String foruser) throws
662
      ConnectException {
663
    Vector gvec = new Vector();
664
    Vector desc = new Vector();
665
    Attributes tempAttr = null;
666

    
667
    //Pass the username and password to run() method
668
    userName = user;
669
    userPassword = password;
670
    // Identify service provider to use
671
    env.put(Context.INITIAL_CONTEXT_FACTORY,
672
            "com.sun.jndi.ldap.LdapCtxFactory");
673
    env.put(Context.REFERRAL, "throw");
674
    env.put(Context.PROVIDER_URL, ldapUrl);
675
    try {
676
      // Create the initial directory context
677
      DirContext ctx = new InitialDirContext(env);
678
      // Specify the ids of the attributes to return
679
      String[] attrIDs = {
680
          "cn", "o", "description"};
681
      // Specify the attributes to match.
682
      // Groups are objects with attribute objectclass=groupofuniquenames.
683
      // and have attribute uniquemember: uid=foruser,ldapbase.
684
      SearchControls ctls = new SearchControls();
685
      ctls.setReturningAttributes(attrIDs);
686
      ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
687

    
688
      String filter = null;
689
      String gfilter = "(objectClass=groupOfUniqueNames)";
690
      if (null == foruser) {
691
        filter = gfilter;
692
      }
693
      else {
694
        filter = "(& " + gfilter + "(uniqueMember=" + foruser + "))";
695
      }
696
      logMetacat.info("searching for groups: " + filter);
697
      NamingEnumeration namingEnum = ctx.search(ldapBase, filter, ctls);
698

    
699
      // Print the groups
700
      logMetacat.info("getting group results.");
701
      while (namingEnum.hasMore()) {
702
        SearchResult sr = (SearchResult) namingEnum.next();
703
        tempAttr = sr.getAttributes();
704

    
705
        if ( (tempAttr.get("description") + "").startsWith("description: ")) {
706
          desc.add( (tempAttr.get("description") + "").substring(13));
707
        }
708
        else {
709
          desc.add(tempAttr.get("description") + "");
710
        }
711

    
712
        gvec.add(sr.getName() + "," + ldapBase);
713
        logMetacat.info("group " + sr.getName() +
714
                                 " added to Group vector");
715
      }
716
      // Close the context when we're done
717
      ctx.close();
718

    
719
    }
720
    catch (ReferralException re) {
721
      refExc = re;
722
      Thread t = new Thread(new GetGroup());
723
      logMetacat.info("Starting thread...");
724
      t.start();
725
      logMetacat.info("sleeping for 5 seconds.");
726
      try {
727
        Thread.sleep(5000);
728
      }
729
      catch (InterruptedException ie) {
730
        logMetacat.error("main thread interrupted: " + ie.getMessage());
731
      }
732
      //this is a manual override of jndi's hideously long time
733
      //out period.
734
      logMetacat.info("Awake after 5 seconds.");
735
      if (referralContext == null) {
736
        logMetacat.info("thread timed out...returning groups: " +
737
                          gvec.toString());
738
        String groups[][] = new String[gvec.size()][2];
739
        for (int i = 0; i < gvec.size(); i++) {
740
          groups[i][0] = (String) gvec.elementAt(i);
741
          groups[i][1] = (String) desc.elementAt(i);
742
        }
743
        t.interrupt();
744
        return groups;
745
      }
746
      DirContext dc = (DirContext) referralContext;
747
      String[] attrIDs = {
748
          "cn", "o", "description"};
749
      // Specify the attributes to match.
750
      // Groups are objects with attribute objectclass=groupofuniquenames.
751
      // and have attribute uniquemember: uid=foruser,ldapbase.
752
      SearchControls ctls = new SearchControls();
753
      ctls.setReturningAttributes(attrIDs);
754
      ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
755

    
756
      String filter = null;
757
      String gfilter = "(objectClass=groupOfUniqueNames)";
758
      if (null == foruser) {
759
        filter = gfilter;
760
      }
761
      else {
762
        filter = "(& " + gfilter + "(uniqueMember=" + foruser + "))";
763
      }
764

    
765
      try {
766
        NamingEnumeration namingEnum = dc.search(ldapBase, filter, ctls);
767
        // Print the groups
768
        while (namingEnum.hasMore()) {
769
          SearchResult sr = (SearchResult) namingEnum.next();
770
          tempAttr = sr.getAttributes();
771

    
772
          if ( (tempAttr.get("description") + "").startsWith("description: ")) {
773
            desc.add( (tempAttr.get("description") + "").substring(13));
774
          }
775
          else {
776
            desc.add(tempAttr.get("description") + "");
777
          }
778

    
779
          gvec.add(sr.getName() + "," + ldapBase);
780
        }
781

    
782
        referralContext.close();
783
        dc.close();
784
      }
785
      catch (NamingException ne) {
786
        logMetacat.info("Naming Exception in AuthLdap.getGroups for referals" +
787
                                 ne.getExplanation() + ne.getMessage());
788
      }
789
    }
790
    catch (NamingException e) {
791
      e.printStackTrace(System.err);
792
      String groups[][] = new String[gvec.size()][2];
793
      for (int i = 0; i < gvec.size(); i++) {
794
        groups[i][0] = (String) gvec.elementAt(i);
795
        groups[i][1] = (String) desc.elementAt(i);
796
      }
797
      return groups;
798
      /*throw new ConnectException(
799
             "Problem getting groups for a user in AuthLdap.getGroups:" + e);*/
800
    }
801

    
802
    logMetacat.warn("The user is in the following groups: " +
803
                             gvec.toString());
804
    String groups[][] = new String[gvec.size()][2];
805
    for (int i = 0; i < gvec.size(); i++) {
806
      groups[i][0] = (String) gvec.elementAt(i);
807
      groups[i][1] = (String) desc.elementAt(i);
808
    }
809
    return groups;
810
  }
811

    
812
  /**
813
   * Get attributes describing a user or group
814
   *
815
   * @param foruser the user for which the attribute list is requested
816
   * @returns HashMap a map of attribute name to a Vector of values
817
   */
818
  public HashMap getAttributes(String foruser) throws ConnectException {
819
    return getAttributes(null, null, foruser);
820
  }
821

    
822
  /**
823
   * Get attributes describing a user or group
824
   *
825
   * @param user the user for authenticating against the service
826
   * @param password the password for authenticating against the service
827
   * @param foruser the user whose attributes should be returned
828
   * @returns HashMap a map of attribute name to a Vector of values
829
   */
830
  public HashMap getAttributes(String user, String password, String foruser) throws
831
      ConnectException {
832
    HashMap attributes = new HashMap();
833
    String ldapUrl = this.ldapUrl;
834
    String ldapBase = this.ldapBase;
835
    String userident = foruser;
836

    
837
    // Identify service provider to use
838
    Hashtable env = new Hashtable(11);
839
    env.put(Context.INITIAL_CONTEXT_FACTORY,
840
            "com.sun.jndi.ldap.LdapCtxFactory");
841
    env.put(Context.REFERRAL, referral);
842
    env.put(Context.PROVIDER_URL, ldapUrl);
843

    
844
    try {
845

    
846
      // Create the initial directory context
847
      DirContext ctx = new InitialDirContext(env);
848

    
849
      // Ask for all attributes of the user
850
      //Attributes attrs = ctx.getAttributes(userident);
851
      Attributes attrs = ctx.getAttributes(foruser);
852

    
853
      // Print all of the attributes
854
      NamingEnumeration en = attrs.getAll();
855
      while (en.hasMore()) {
856
        Attribute att = (Attribute) en.next();
857
        Vector values = new Vector();
858
        String attName = att.getID();
859
        NamingEnumeration attvalues = att.getAll();
860
        while (attvalues.hasMore()) {
861
          String value = (String) attvalues.next();
862
          values.add(value);
863
        }
864
        attributes.put(attName, values);
865
      }
866

    
867
      // Close the context when we're done
868
      ctx.close();
869
    }
870
    catch (NamingException e) {
871
      logMetacat.error("Problem getting attributes in " +
872
                        "AuthLdap.getAttributes:" + e);
873
      throw new ConnectException(
874
          "Problem getting attributes in AuthLdap.getAttributes:" + e);
875
    }
876

    
877
    return attributes;
878
  }
879

    
880
  /**
881
   * Get list of all subtrees holding Metacat's groups and users
882
   * starting from the Metacat LDAP root,
883
   * i.e. ldap://dev.nceas.ucsb.edu/dc=ecoinformatics,dc=org
884
   */
885
  private Hashtable getSubtrees(String user, String password,
886
                                String ldapUrl, String ldapBase) throws
887
      ConnectException {
888
    Hashtable trees = new Hashtable();
889

    
890
    // Identify service provider to use
891
    Hashtable env = new Hashtable(11);
892
    env.put(Context.INITIAL_CONTEXT_FACTORY,
893
            "com.sun.jndi.ldap.LdapCtxFactory");
894
    // env.put(Context.REFERRAL, referral);
895
    // Using 'ignore' here instead of 'follow' as 'ignore' seems
896
    // to do the job better. 'follow' was not bringing up the UCNRS
897
    // and PISCO tree whereas 'ignore' brings up the tree.
898

    
899
    env.put(Context.REFERRAL, "ignore");
900
    env.put(Context.PROVIDER_URL, ldapUrl + ldapBase);
901

    
902
    try {
903

    
904
      // Create the initial directory context
905
      DirContext ctx = new InitialDirContext(env);
906

    
907
      // Specify the ids of the attributes to return
908
      String[] attrIDs = {
909
          "o", "ref"};
910
      SearchControls ctls = new SearchControls();
911
      ctls.setReturningAttributes(attrIDs);
912
      ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
913

    
914
      // Specify the attributes to match.
915
      // Subtrees from the main server are found as objects with attribute
916
      // objectclass=organization or objectclass=referral to the subtree
917
      // resided on other server.
918
      String filter = "(|(objectclass=organization)(objectclass=referral))";
919

    
920
      // Search for objects in the current context
921
      NamingEnumeration namingEnum = ctx.search("", filter, ctls);
922

    
923
      // Print the subtrees' <ldapURL, baseDN>
924
      while (namingEnum.hasMore()) {
925

    
926
        SearchResult sr = (SearchResult) namingEnum.next();
927

    
928
        Attributes attrs = sr.getAttributes();
929
        NamingEnumeration enum1 = attrs.getAll(); // "dc" and "ref" attrs
930

    
931
        if (enum1.hasMore()) {
932
          Attribute attr = (Attribute) enum1.next();
933
          String attrValue = (String) attr.get();
934
          String attrName = (String) attr.getID();
935

    
936
          if (enum1.hasMore()) {
937
            attr = (Attribute) enum1.next();
938
            String refValue = (String) attr.get();
939
            String refName = (String) attr.getID();
940
            if (ldapBase.startsWith(refName + "=" + refValue)) {
941
              trees.put(ldapBase,
942
                        attrValue.substring(0, attrValue.lastIndexOf("/") + 1));
943
            }
944
            else {
945
              // this is a referral - so organization name is appended in
946
              // front of the ldapbase.... later it is stripped out
947
              // in getPrincipals
948
              trees.put("[" + refName + "=" + refValue + "]" +
949
                        attrValue.substring(attrValue.lastIndexOf("/") + 1,
950
                                            attrValue.length()),
951
                        attrValue.substring(0, attrValue.lastIndexOf("/") + 1));
952

    
953
              // trees.put(refName + "=" + refValue + "," + ldapBase,
954
              //           attrValue.substring(0, attrValue.lastIndexOf("/") + 1));
955
            }
956

    
957
          }
958
          else if (ldapBase.startsWith(attrName + "=" + attrValue)) {
959
            trees.put(ldapBase, ldapUrl);
960
          }
961
          else {
962
            if (sr.isRelative()) {
963
              trees.put(attrName + "=" + attrValue + "," + ldapBase, ldapUrl);
964
            }
965
            else {
966
              String referenceURL = sr.getName();
967
              referenceURL = referenceURL.substring(0,
968
                  referenceURL.lastIndexOf("/") + 1);
969
              trees.put(attrName + "=" + attrValue + "," + ldapBase,
970
                        referenceURL);
971
            }
972

    
973
          }
974
        }
975
      }
976

    
977
      // Close the context when we're done
978
      ctx.close();
979

    
980
    }
981
    catch (NamingException e) {
982
      logMetacat.error("Problem getting subtrees in AuthLdap.getSubtrees:"
983
                        + e);
984
      throw new ConnectException(
985
          "Problem getting subtrees in AuthLdap.getSubtrees:" + e);
986
    }
987

    
988
    return trees;
989
  }
990

    
991
  /**
992
   * Get all groups and users from authentication scheme.
993
   * The output is formatted in XML.
994
   * @param user the user which requests the information
995
   * @param password the user's password
996
   */
997
  public String getPrincipals(String user, String password) throws
998
      ConnectException {
999
    StringBuffer out = new StringBuffer();
1000
   
1001
    out.append("<?xml version=\"1.0\" encoding=\"US-ASCII\"?>\n");
1002
    out.append("<principals>\n");
1003

    
1004
    /*
1005
     * get all subtrees first in the current dir context
1006
     * and then the Metacat users under them
1007
     */
1008
    Hashtable subtrees = getSubtrees(user, password, this.ldapUrl,
1009
                                     this.ldapBase);
1010

    
1011
    Enumeration keyEnum = subtrees.keys();
1012
    while (keyEnum.hasMoreElements()) {
1013
      this.ldapBase = (String) keyEnum.nextElement();
1014
      this.ldapUrl = (String) subtrees.get(ldapBase);
1015

    
1016
      /*
1017
       * code to get the organization name from ldapBase
1018
       */
1019
      String orgName = this.ldapBase;
1020
      if (orgName.startsWith("[")) {
1021
        // if orgName starts with [ then it is a referral URL...
1022
        // (see code in getSubtress)
1023
        // hence orgName can be retrieved  by getting the string between
1024
        // 'o=' and ']'
1025
        // also the string between [ and ] needs to be striped out from
1026
        // this.ldapBase
1027
        this.ldapBase = orgName.substring(orgName.indexOf("]") + 1);
1028
        if (orgName != null && orgName.indexOf("o=") > -1) {
1029
          orgName = orgName.substring(orgName.indexOf("o=") + 2);
1030
          orgName = orgName.substring(0, orgName.indexOf("]"));
1031
        }
1032
      }
1033
      else {
1034
        // else it is not referral
1035
        // hence orgName can be retrieved  by getting the string between
1036
        // 'o=' and ','
1037
        if (orgName != null && orgName.indexOf("o=") > -1) {
1038
          orgName = orgName.substring(orgName.indexOf("o=") + 2);
1039
          if (orgName.indexOf(",") > -1) {
1040
            orgName = orgName.substring(0, orgName.indexOf(","));
1041
          }
1042
        }
1043
      }
1044

    
1045
      out.append("  <authSystem URI=\"" +
1046
                 this.ldapUrl + this.ldapBase + "\" organization=\"" + orgName +
1047
                 "\">\n");
1048

    
1049
      // get all groups for directory context
1050
      String[][] groups = getGroups(user, password);
1051
      String[][] users = getUsers(user, password);
1052
      int userIndex = 0;
1053

    
1054
      // for the groups and users that belong to them
1055
      if (groups != null && groups.length > 0) {
1056
        for (int i = 0; i < groups.length; i++) {
1057
          out.append("    <group>\n");
1058
          out.append("      <groupname>" + groups[i][0] + "</groupname>\n");
1059
          out.append("      <description>" + groups[i][1] + "</description>\n");
1060
          String[] usersForGroup = getUsers(user, password, groups[i][0]);
1061
          for (int j = 0; j < usersForGroup.length; j++) {
1062
            
1063
            userIndex = searchUser(usersForGroup[j], users);
1064
            out.append("      <user>\n");
1065

    
1066
            if (userIndex < 0) {
1067
              out.append("        <username>" + usersForGroup[j] +
1068
                         "</username>\n");
1069
            }
1070
            else {
1071
              out.append("        <username>" + users[userIndex][0] +
1072
                         "</username>\n");
1073
              out.append("        <name>" + users[userIndex][1] + "</name>\n");
1074
              out.append("        <organization>" + users[userIndex][2] +
1075
                         "</organization>\n");
1076
              if (users[userIndex][3].compareTo("null") != 0) {
1077
                out.append("      <organizationUnitName>" + users[userIndex][3] +
1078
                           "</organizationUnitName>\n");
1079
              }
1080
              out.append("        <email>" + users[userIndex][4] + "</email>\n");
1081
            }
1082

    
1083
            out.append("      </user>\n");
1084
          }
1085
          out.append("    </group>\n");
1086
        }
1087
      }
1088

    
1089
      // for the users not belonging to any grou8p
1090
      for (int j = 0; j < users.length; j++) {
1091
          out.append("    <user>\n");
1092
          out.append("      <username>" + users[j][0] + "</username>\n");
1093
          out.append("      <name>" + users[j][1] + "</name>\n");
1094
          out.append("      <organization>" + users[j][2] +
1095
                     "</organization>\n");
1096
          if (users[j][3].compareTo("null") != 0) {
1097
            out.append("      <organizationUnitName>" + users[j][3] +
1098
                       "</organizationUnitName>\n");
1099
          }
1100
          out.append("      <email>" + users[j][4] + "</email>\n");
1101
          out.append("    </user>\n");
1102
      }
1103

    
1104
      out.append("  </authSystem>\n");
1105
    }
1106
    out.append("</principals>");
1107
    return out.toString();
1108
  }
1109

    
1110
  /**
1111
   * Method for getting index of user DN in User info array
1112
   */
1113
  int searchUser(String user, String userGroup[][]) {
1114
    for (int j = 0; j < userGroup.length; j++) {
1115
      if (user.compareTo(userGroup[j][0]) == 0) {
1116
        return j;
1117
      }
1118
    }
1119
    return -1;
1120
  }
1121

    
1122
  /**
1123
   * Test method for the class
1124
   */
1125
  public static void main(String[] args) {
1126

    
1127
    // Provide a user, such as: "Matt Jones", or "jones"
1128
    String user = args[0];
1129
    String password = args[1];
1130

    
1131
    logMetacat.warn("Creating session...");
1132
    AuthLdap authservice = new AuthLdap();
1133
    logMetacat.warn("Session exists...");
1134

    
1135
    boolean isValid = false;
1136
    try {
1137
      logMetacat.warn("Authenticating...");
1138
      isValid = authservice.authenticate(user, password);
1139
      if (isValid) {
1140
    	  logMetacat.warn("Authentication successful for: " + user);
1141
      }
1142
      else {
1143
        logMetacat.warn("Authentication failed for: " + user);
1144
      }
1145

    
1146
      // Get attributes for the user
1147
      if (isValid) {
1148
        logMetacat.info("\nGetting attributes for user....");
1149
        HashMap userInfo = authservice.getAttributes(user, password, user);
1150
        // Print all of the attributes
1151
        Iterator attList = (Iterator) ( ( (Set) userInfo.keySet()).iterator());
1152
        while (attList.hasNext()) {
1153
          String att = (String) attList.next();
1154
          Vector values = (Vector) userInfo.get(att);
1155
          Iterator attvalues = values.iterator();
1156
          while (attvalues.hasNext()) {
1157
            String value = (String) attvalues.next();
1158
            logMetacat.warn(att + ": " + value);
1159
          }
1160
        }
1161
      }
1162

    
1163
      // get the groups
1164
      if (isValid) {
1165
        logMetacat.warn("\nGetting all groups....");
1166
        String[][] groups = authservice.getGroups(user, password);
1167
        logMetacat.info("Groups found: " + groups.length);
1168
        for (int i = 0; i < groups.length; i++) {
1169
          logMetacat.info("Group " + i + ": " + groups[i][0]);
1170
        }
1171
      }
1172

    
1173
      // get the groups for the user
1174
      String savedGroup = null;
1175
      if (isValid) {
1176
        logMetacat.warn("\nGetting groups for user....");
1177
        String[][] groups = authservice.getGroups(user, password, user);
1178
        logMetacat.info("Groups found: " + groups.length);
1179
        for (int i = 0; i < groups.length; i++) {
1180
          logMetacat.info("Group " + i + ": " + groups[i][0]);
1181
          savedGroup = groups[i][0];
1182
        }
1183
      }
1184

    
1185
      // get the users for a group
1186
      if (isValid) {
1187
        logMetacat.warn("\nGetting users for group....");
1188
        logMetacat.info("Group: " + savedGroup);
1189
        String[] users = authservice.getUsers(user, password, savedGroup);
1190
        logMetacat.info("Users found: " + users.length);
1191
        for (int i = 0; i < users.length; i++) {
1192
          logMetacat.warn("User " + i + ": " + users[i]);
1193
        }
1194
      }
1195

    
1196
      // get all users
1197
      if (isValid) {
1198
        logMetacat.warn("\nGetting all users ....");
1199
        String[][] users = authservice.getUsers(user, password);
1200
        logMetacat.info("Users found: " + users.length);
1201

    
1202
      }
1203

    
1204
      // get the whole list groups and users in XML format
1205
      if (isValid) {
1206
        logMetacat.warn("\nTrying principals....");
1207
        authservice = new AuthLdap();
1208
        String out = authservice.getPrincipals(user, password);
1209
        java.io.File f = new java.io.File("principals.xml");
1210
        java.io.FileWriter fw = new java.io.FileWriter(f);
1211
        java.io.BufferedWriter buff = new java.io.BufferedWriter(fw);
1212
        buff.write(out);
1213
        buff.flush();
1214
        buff.close();
1215
        fw.close();
1216
        logMetacat.warn("\nFinished getting principals.");
1217
      }
1218

    
1219
    }
1220
    catch (ConnectException ce) {
1221
      logMetacat.error(ce.getMessage());
1222
    }
1223
    catch (java.io.IOException ioe) {
1224
      logMetacat.error("I/O Error writing to file principals.txt");
1225
    }
1226
  }
1227

    
1228
  /**
1229
   * This method will be called by start a thread.
1230
   * It can handle if a referral exception happend.
1231
   */
1232
  public void run() {
1233
    referralContext = null;
1234
    DirContext refDirContext = null;
1235
    boolean moreReferrals = true;
1236
    String referralInfo = null;
1237
    //set a while loop is because we don't know if a referral excption contains
1238
    //another referral exception
1239
    while (moreReferrals) {
1240
      try {
1241
        //revise environment variable
1242
        referralInfo = (String) refExc.getReferralInfo();
1243
        logMetacat.info("Processing referral (pr0): ");
1244
        logMetacat.info("PROVIDER_URL set to (pr1): " + referralInfo);
1245
        //env.put(Context.PROVIDER_URL,referralInfo);
1246
        //env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
1247
        //env.put(Context.SECURITY_PRINCIPAL, userName);
1248
        //env.put(Context.SECURITY_CREDENTIALS, userPassword);
1249
        //env.put(Context.REFERRAL, "throw");
1250
        //logMetacat.info("Processing referral (pr1.info): " + userName,35);
1251
        //logMetacat.info("Processing referral (pr2)",35);
1252
        //rContext = refExc.getReferralContext(env);
1253
        rContext = refExc.getReferralContext();
1254
        logMetacat.info("Processing referral (pr3)");
1255
        //casting the context to dircontext and it will create a
1256
        //autherntication or naming exception if DN and password is incorrect
1257
        referralContext = rContext;
1258
        refDirContext = (DirContext) rContext;
1259
        refDirContext.close();
1260
        //get context and jump out the while loop
1261
        moreReferrals = false;
1262
        logMetacat.info("Processing referral (pr4)");
1263
      } //try
1264
      //if referral have another referral excption
1265
      catch (ReferralException re) {
1266
        logMetacat.warn("GOT referral exception (re1): " + re.getMessage());
1267
        logMetacat.warn("RE details (re2): " + re.toString(true));
1268
        //keep running in while loop
1269
        moreReferrals = true;
1270
        //assign refExc to new referral exception re
1271
        refExc = re;
1272
      }
1273
      //catch a authentication exception
1274
      catch (AuthenticationException ae) {
1275
        logMetacat.error("Error running referral handler thread (ae1): " +
1276
                          ae.getMessage());
1277
        //check if has another referral
1278
        moreReferrals = refExc.skipReferral();
1279
        //don't get the context
1280
        referralContext = null;
1281
      }
1282
      //catch a naming exception
1283
      catch (NamingException ne) {
1284
        logMetacat.error("Error running referral handler thread (ne1): " +
1285
                          ne.getMessage());
1286
        //check if has another referral
1287
        moreReferrals = refExc.skipReferral();
1288
        //don't get context
1289
        referralContext = null;
1290
      }
1291
    } //while
1292
  } //run()
1293

    
1294
  private class GetGroup
1295
      implements Runnable {
1296
    public void run() {
1297
      referralContext = null;
1298
      logMetacat.info("getting groups context");
1299
      DirContext refDirContext = null;
1300
      boolean moreReferrals = true;
1301
      //set a while loop is because we don't know if a referral excption
1302
      //contains another referral exception
1303
      while (moreReferrals) {
1304
        try {
1305
          //revise environment variable
1306
          String refInfo = null;
1307
          refInfo = (String) refExc.getReferralInfo();
1308
          if (refInfo != null) {
1309
            logMetacat.info("Referral in thread to: " +
1310
                                     refInfo.toString());
1311
          }
1312
          else {
1313
            logMetacat.info("getting refInfo Manually");
1314
            refInfo = (String) refExc.getReferralContext().getEnvironment().
1315
                get(Context.PROVIDER_URL);
1316
          }
1317
          logMetacat.info("refInfo: " + refInfo);
1318

    
1319
          env.put(Context.INITIAL_CONTEXT_FACTORY,
1320
                  "com.sun.jndi.ldap.LdapCtxFactory");
1321
          env.put(Context.REFERRAL, "throw");
1322
          env.put(Context.PROVIDER_URL, refInfo);
1323

    
1324
          logMetacat.info("creating referralContext");
1325
          referralContext = new InitialDirContext(env);
1326
          logMetacat.info("referralContext created");
1327
          //get context and jump out the while loop
1328
          moreReferrals = false;
1329
        } //try
1330
        catch (ReferralException re) {
1331
          //keep running in while loop
1332
          moreReferrals = true;
1333
          //assign refExc to new referral exception re
1334
          refExc = re;
1335
        }
1336
        catch (AuthenticationException ae) {
1337
          logMetacat.error("Error running referral handler thread (ae2): " +
1338
                            ae.getMessage());
1339
          //check if has another referral
1340
          moreReferrals = refExc.skipReferral();
1341
          //don't get the context
1342
          referralContext = null;
1343
        }
1344
        catch (NamingException ne) {
1345
          logMetacat.error("Error running referral handler thread (ne2): " +
1346
                            ne.getMessage());
1347
          //check if has another referral
1348
          moreReferrals = refExc.skipReferral();
1349
          //don't get context
1350
          referralContext = null;
1351
        }
1352
      } //while
1353
    } //run()
1354
  }
1355
}
(11-11/65)