Project

General

Profile

« Previous | Next » 

Revision 934

Added by Jing Tao almost 23 years ago

The bug was fixed.
After a referral exception happend, we should set enviroment properties again before creating a contex. These environment properties include PROVIDER_URL, SECURITY_PRINCIPLE, SECURITY_CREDENTIALS, REFERRAL, and INITIAL_CONTEXT_FACOTRY. Otherwise, you couldn't get a naming exception.

View differences:

src/edu/ucsb/nceas/metacat/AuthLdap.java
30 30
package edu.ucsb.nceas.metacat;
31 31

  
32 32
import java.net.ConnectException;
33

  
34 33
import javax.naming.AuthenticationException;
35 34
import javax.naming.Context;
36 35
import javax.naming.NamingEnumeration;
......
62 61
 * is authenticated, and whether they are a member of a particular group.
63 62
 */
64 63
public class AuthLdap implements AuthInterface, Runnable {
65
  
66 64
  private MetaCatUtil util = new MetaCatUtil();
67 65
  private String ldapUrl;
68 66
  private String ldapsUrl;
69 67
  private String ldapBase;
70 68
  private String referral;
71
	private Context referralContext;
69
  private Context referralContext;
72 70
  Hashtable env = new Hashtable(11);
73 71
  private Context rContext;
74
	private String userName;
75
	private String userPassword;
72
  private String userName;
73
  private String userPassword;
76 74
  ReferralException refExc;
77 75

  
78 76
  /** 
79 77
   * Construct an AuthLdap
80 78
   */
81 79
  public AuthLdap() {
82

  
83 80
    // Read LDAP URI for directory service information
84 81
    this.ldapUrl = MetaCatUtil.getOption("ldapurl");
85 82
    this.ldapsUrl = MetaCatUtil.getOption("ldapsurl");
86 83
    this.ldapBase = MetaCatUtil.getOption("ldapbase");
87 84
    this.referral = MetaCatUtil.getOption("referral");
88
    //this.referral = "ignore";
89
    //System.out.println("LDAPBASE is: " + ldapBase);
90 85
  }
91 86

  
92 87
  /**
......
100 95
  public boolean authenticate(String user, String password)
101 96
                    throws ConnectException
102 97
  {
103
    System.out.println("ldap authenticating");
104 98
    String ldapUrl = this.ldapUrl;
105 99
    String ldapsUrl = this.ldapsUrl;
106 100
    String ldapBase = this.ldapBase;
......
108 102
    String identifier = user;
109 103

  
110 104
    try {
111
   
112 105
        // Check the usename as passed in
113 106
        authenticated = ldapAuthenticate(identifier, password);
114
				//System.out.println("Identifier: "+ identifier);
115

  
116
        // if not found, try looking up a valid DN then auth again
117
        //Because identifier already has url and idapbase information,
118
				//we don't need check again.
119
				/*if (!authenticated) 
120
				{
121
	    			
122
	    			System.out.println("Check  againg!");
123
            System.out.println("idenfier: "+identifier);
124
						System.out.println("ldapUrl: "+ldapUrl);
125
						System.out.println("ldapBase: "+ldapBase);
126
            identifier = getIdentifyingName(identifier,ldapUrl,ldapBase);
127
					
128
						System.out.println("In Check again and after getIdenName, identifier: "+identifier+","
129
						+ldapBase);
130
            authenticated = ldapAuthenticate(identifier+","+ldapBase, password);
131
        }*/
132

  
133 107
    } catch (NullPointerException e) {
134 108
      util.debugMessage("NullPointerException b' password is null");
135 109
      util.debugMessage("NullPointerException while authenticating in " + 
......
142 116
                        "AuthLdap.authenticate: " + e);
143 117
      e.printStackTrace();
144 118
    } catch (Exception e) {
145
      System.out.println(e.getMessage());
119
      util.debugMessage(e.getMessage());
146 120
    }
147

  
148 121
    return authenticated;
149 122
  }
150 123

  
......
161 134
    double totStartTime = System.currentTimeMillis();
162 135
    boolean authenticated = false;
163 136
    if (identifier != null && !password.equals("")) 
164
		{
137
    {
165 138
    
166
        //Pass the username and password to run()
167
				userName=identifier;
168
				userPassword=password;
169
				// Identify service provider to use
139
        //Pass the username and password to run() method
140
        userName=identifier;
141
        userPassword=password;
142
        // Identify service provider to use
170 143
        Hashtable env = new Hashtable(11);
171 144
        env.put(Context.INITIAL_CONTEXT_FACTORY, 
172
            "com.sun.jndi.ldap.LdapCtxFactory");
173

  
174
        //System.out.println("referral: " + referral);
175
        // Now that we have the dn, we can authenticate, so
176
        // authenticate this time when opening the DirContext
177
        //System.out.println("referral=throw");
178
        
179
        //Change the vaule of Context.REFERRAL from "throw" to "follow"
180
        //Jing Tao 02/06/02
181
        //env.put(Context.REFERRAL, "follow");
145
              "com.sun.jndi.ldap.LdapCtxFactory");
182 146
        env.put(Context.REFERRAL, "throw");
183
        /*CB:  Note that the above env.put statement does not use the referral 
184
          variable.  it is hard coded to 'throw'.  Matt: Is it ok to do this
185
          only here and not in every method?
186
        */
187
        //System.out.println("ldapsUrl: " + ldapsUrl + " ldapBase: " + ldapBase);
188 147
        env.put(Context.PROVIDER_URL, ldapsUrl + ldapBase);
189 148
        if ( !ldapsUrl.equals(ldapUrl) ) 
190
				{
149
        {
191 150
          // ldap is set on default port 389
192 151
          // ldaps is set on second port - 636 by default
193 152
          env.put(Context.SECURITY_PROTOCOL, "ssl");
194 153
        }
195 154
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
196
				//System.out.println("provider_url: "+env.get(Context.PROVIDER_URL));
197 155
        env.put(Context.SECURITY_PRINCIPAL, identifier);
198
        //System.out.println("Trying DN: " + identifier);
199 156
        env.put(Context.SECURITY_CREDENTIALS, password);
200
				
201 157
        // If our auth credentials are invalid, an exception will be thrown
202 158
        DirContext ctx = null;
203 159
        try 
204 160
        {
205 161
          double startTime = System.currentTimeMillis();
206
          //System.out.println("Before creating ctx");
207 162
          //Here to check the autheration
208 163
          ctx = new InitialDirContext(env);
209
					//Keep track the value of provider url
210
					//System.out.println("I am before getEnvironment()");
211
					//System.out.println("Here is the provider url from enviroment: "+
212
					//(ctx.getEnvironment()).get("Context.PROVIDER_URL"));
213
					
214
          //System.out.println("After creating ctx");
215 164
          double stopTime = System.currentTimeMillis();
216
          System.out.println("Connection time thru " + ldapsUrl + " was: " +
165
          util.debugMessage("Connection time thru " + ldapsUrl + " was: " +
217 166
                             (stopTime-startTime)/1000 + " seconds.");
218 167
          authenticated = true;
219 168
          //tls.close();
......
224 173
        } 
225 174
        catch (AuthenticationException ae) 
226 175
        {
227
          //To keep tracking Jing Tao, 02/06/02
228
          //System.out.println("AuthernticationException happened!");
229 176
          authenticated = false;
230 177
          if ( ctx != null ) 
231 178
          {
......
234 181
        } 
235 182
        catch (javax.naming.InvalidNameException ine) 
236 183
        {
237
            System.out.println("An invalid DN was provided!");
184
            util.debugMessage("An invalid DN was provided!");
238 185
        } 
239 186
        catch(javax.naming.ReferralException re) 
240 187
        {
241
          System.out.println("referral during authentication");
242
					System.out.println("Referral information: "+re.getReferralInfo());
243
	        try
188
          util.debugMessage("referral during authentication");
189
          util.debugMessage("Referral information: "+re.getReferralInfo());
190
          try
244 191
          {
245 192
            refExc = re;
246
						
193

  
247 194
            Thread t = new Thread(this);
248
            System.out.println("Starting thread...");
249 195
            t.start();
250
            System.out.println("sleeping for 5 seconds.");
251 196
            Thread.sleep(5000); //this is a manual override of ldap's 
252 197
                                //hideously long time out period.
253
            System.out.println("Awake after 5 seconds.");
198
            util.debugMessage("Awake after 5 seconds.");
254 199
            if(referralContext == null)
255 200
            {
256
              System.out.println("killing thread....not authenticated.");
257 201
              t.interrupt();
258
              System.out.println("thread killed.");
259 202
              authenticated = false;
260 203
            }
261 204
            else
262 205
            {
263 206
              authenticated = true;
264
							
207

  
265 208
            }
266 209
          }
267 210
          catch(Exception e)
......
270 213
          }
271 214
        }
272 215
    } 
273
		else 
274
		{ 
216
    else 
217
    { 
275 218
        util.debugMessage("User not found");
276 219
    }
277 220
    double totStopTime = System.currentTimeMillis();
278
    System.out.println("total ldap authentication time: " + 
221
    util.debugMessage("total ldap authentication time: " + 
279 222
                      (totStopTime - totStartTime)/1000 + " seconds");
280 223
    return authenticated;
281 224
  }
282 225
  
283
  /**
284
   * handles a referral exception.  this method should be called from
285
   * within the catch statement of a ReferralException 
286
   */
287
  private Context handleReferral(Hashtable env, Context rContext) throws
288
                                                                  Exception
289
  {
290
    System.out.println("Referral to(rContext) : " + rContext.toString());
291
    boolean referralSuccess = false;
292
    while(referralSuccess != true)
293
    {
294
      try
295
      {
296
        /*
297
         Matt, I think this is right but I'm not sure...please check me to make
298
         sure I didn't do something wrong here.
299
        */
300
        double refStartTime = System.currentTimeMillis();
301
        Context refctx = rContext;
302
        referralSuccess = true;
303
        refctx.close();
304
        this.ldapUrl = ldapUrl;
305
        this.ldapBase = ldapBase;
306
        double refStopTime = System.currentTimeMillis();
307
        System.out.println("total referral time: " + 
308
                          (refStopTime - refStartTime)/1000 + "seconds");
309
        return refctx;
310
      }
311
      catch(ReferralException e)
312
      {
313
          System.out.println("Referring to: " + 
314
                             rContext.toString());
315
      }
316
      catch(Exception e)
317
      {
318
        throw e;
319
      }
320
    }
321
    return null; //this should never get called
322
  }
226
  
323 227

  
324 228
  /**
325 229
   * Get the identifying name for a given userid or name.  This is the name
......
330 234
   * @returns String the identifying name for the user, 
331 235
   *          or null if not found
332 236
   */
333
  private String getIdentifyingName(String user, String ldapUrl, String ldapBase) 
334
         throws NamingException
237
  private String getIdentifyingName(String user, String ldapUrl,
238
                                    String ldapBase) throws NamingException
335 239
  {
336 240
    String identifier = null;
337

  
338 241
    // Identify service provider to use
339 242
    Hashtable env = new Hashtable(11);
340 243
    env.put(Context.INITIAL_CONTEXT_FACTORY,
......
343 246
    env.put(Context.REFERRAL, referral);
344 247
    env.put(Context.PROVIDER_URL, ldapUrl + ldapBase);
345 248
    //    non-secure LDAP context; dn are publicly readable
346
    //    env.put(Context.SECURITY_PROTOCOL, "ssl");
347 249
    try {
348 250
      
349 251
      // Bind to the LDAP server, in order to search for the right
......
351 253
      DirContext ctx = new InitialDirContext(env);
352 254
      SearchControls ctls = new SearchControls();
353 255
      ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
354
      // Search for the user id or name using the uid, then cn and sn attributes
256
      // Search for the user id or name using the uid, then cn and sn 
257
      //attributes
355 258
      // If we find a record, determine the dn for the record
356
      //System.out.println("Starting search phase...");
357 259

  
358 260
      String filter = "(" + user + ")";
359 261
      NamingEnumeration answer;
......
363 265
          SearchResult sr = (SearchResult)answer.next();
364 266
          identifier = sr.getName();
365 267
          if ( !sr.isRelative() ) { 
366
            this.ldapUrl = identifier.substring(0,identifier.lastIndexOf("/")+1);
268
            this.ldapUrl = identifier.substring(0,
269
                                                identifier.lastIndexOf("/")+1);
367 270
            this.ldapBase = identifier.substring(identifier.indexOf(",")+1);
368 271
            identifier = identifier.substring(identifier.lastIndexOf("/")+1,
369 272
                                              identifier.indexOf(","));
......
385 288
        }
386 289
        util.debugMessage("Found: " + identifier);
387 290
      } else {
388
        //Attributes matchAttrs2 = new BasicAttributes(true);
389
        //matchAttrs2.put(new BasicAttribute("cn", user));
390
        //NamingEnumeration answer2 = ctx.search("", matchAttrs2);
391 291
        filter = "(cn=" + user + ")";
392 292
        NamingEnumeration answer2 = ctx.search("", filter, ctls);
393 293
        if (answer2.hasMore()) {
394 294
          SearchResult sr = (SearchResult)answer2.next();
395 295
          identifier = sr.getName();
396 296
          if ( !sr.isRelative() ) { 
397
            this.ldapUrl = identifier.substring(0,identifier.lastIndexOf("/")+1);
297
            this.ldapUrl = identifier.substring(0,
298
                                                identifier.lastIndexOf("/")+1);
398 299
            this.ldapBase = identifier.substring(identifier.indexOf(",")+1);
399 300
            identifier = identifier.substring(identifier.lastIndexOf("/")+1,
400 301
                                              identifier.indexOf(","));
401 302
          }
402 303
          util.debugMessage("Found: " + identifier);
403 304
        } else {
404
          //Attributes matchAttrs3 = new BasicAttributes(true);
405
          //matchAttrs3.put(new BasicAttribute("sn", user));
406
          //NamingEnumeration answer3 = ctx.search("", matchAttrs3);
407 305
          filter = "(sn=" + user + ")";
408 306
          NamingEnumeration answer3 = ctx.search("", filter, ctls);
409 307
          if (answer3.hasMore()) {
410 308
            SearchResult sr = (SearchResult)answer3.next();
411 309
            identifier = sr.getName();
412 310
            if ( !sr.isRelative() ) { 
413
              this.ldapUrl = identifier.substring(0,identifier.lastIndexOf("/")+1);
311
              this.ldapUrl = identifier.substring(0,
312
                                                identifier.lastIndexOf("/")+1);
414 313
              this.ldapBase = identifier.substring(identifier.indexOf(",")+1);
415 314
              identifier = identifier.substring(identifier.lastIndexOf("/")+1,
416 315
                                                identifier.indexOf(","));
......
447 346
            "com.sun.jndi.ldap.LdapCtxFactory");
448 347
    env.put(Context.REFERRAL, referral);
449 348
    env.put(Context.PROVIDER_URL, ldapUrl);
450
    //env.put(Context.BATCHSIZE, "500");
451

  
349
 
452 350
    try {
453 351

  
454 352
        // Create the initial directory context
......
486 384
        ctx.close();
487 385

  
488 386
    } catch (NamingException e) {
489
      System.err.println("Problem getting users in AuthLdap.getUsers:" + e);
387
      util.debugMessage("Problem getting users in AuthLdap.getUsers:" + e);
490 388
      e.printStackTrace(System.err);
491 389
      throw new ConnectException(
492 390
      "Problem getting users in AuthLdap.getUsers:" + e);
......
549 447
        ctx.close();
550 448

  
551 449
    } catch (NamingException e) {
552
      System.err.println("Problem getting users for a group in " +
450
      util.debugMessage("Problem getting users for a group in " +
553 451
              "AuthLdap.getUsers:" + e);
554 452
      throw new ConnectException(
555 453
      "Problem getting users for a group in AuthLdap.getUsers:" + e);
......
582 480
  public String[] getGroups(String user, String password, String foruser) 
583 481
         throws ConnectException
584 482
  {
585
    //System.err.println("GG in get groups 2");
586 483
    String[] groups = null;
587 484

  
588 485
    // Identify service provider to use
......
629 526
        ctx.close();
630 527

  
631 528
    } catch(ReferralException re) {
632
      System.out.println("caught a referral to " + re.toString());
633 529
      try
634 530
      {
635 531
        refExc = re;
636 532
        Thread t = new Thread(this);
637
        System.out.println("Starting thread...");
533
        util.debugMessage("Starting thread...");
638 534
        t.start();
639
        System.out.println("sleeping for 5 seconds.");
640
        Thread.sleep(5000); //this is a manual override of ldap's hideously long time
641
                     //out period.
642
        System.out.println("Awake after 5 seconds.");
535
        util.debugMessage("sleeping for 5 seconds.");
536
        Thread.sleep(5000); 
537
        //this is a manual override of ldap's hideously long time
538
        //out period.
539
        util.debugMessage("Awake after 5 seconds.");
643 540
        if(referralContext == null)
644 541
        {
645
          System.out.println("killing thread....returning null.");
646 542
          t.interrupt();
647
          System.out.println("thread killed.");
648 543
          return null;
649 544
        }
650 545
        DirContext dc = (DirContext)referralContext;
......
682 577
      }
683 578
      catch(Exception e)
684 579
      {
685
        System.out.println("returning groups as null");
686 580
        return groups;
687 581
      }
688 582
    } catch (NamingException e) {
689
      System.err.println("Problem getting groups in AuthLdap.getGroups 2:" + e);
690 583
      e.printStackTrace(System.err);
691 584
      throw new ConnectException(
692 585
      "Problem getting groups for a user in AuthLdap.getGroups:" + e);
......
721 614
    String ldapUrl = this.ldapUrl;
722 615
    String ldapBase = this.ldapBase;
723 616
    String userident = foruser;
724
    /*
725
    try { 
726
      this.ldapBase = userident.substring(userident.indexOf(",")+1);
727
      userident = userident.substring(0,userident.indexOf(","));
728
    } catch (StringIndexOutOfBoundsException e) {}
729
*/
617
   
730 618
    // Identify service provider to use
731 619
    Hashtable env = new Hashtable(11);
732 620
    env.put(Context.INITIAL_CONTEXT_FACTORY, 
......
739 627
      // Create the initial directory context
740 628
      DirContext ctx = new InitialDirContext(env);
741 629
        
742
      // Find out the identifying attribute for the user
743
      //userident = getIdentifyingName(userident,ldapUrl,ldapBase);
744

  
745 630
      // Ask for all attributes of the user 
746 631
      //Attributes attrs = ctx.getAttributes(userident);
747 632
      Attributes attrs = ctx.getAttributes(foruser);
......
763 648
      // Close the context when we're done
764 649
      ctx.close();
765 650
    } catch (NamingException e) {
766
      System.err.println("Problem getting attributes in " + 
651
      util.debugMessage("Problem getting attributes in " + 
767 652
              "AuthLdap.getAttributes:" + e);
768 653
      throw new ConnectException(
769 654
      "Problem getting attributes in AuthLdap.getAttributes:" + e);
......
819 704
            Attribute attr = (Attribute)enum1.next();
820 705
            String attrValue = (String)attr.get();
821 706
            String attrName = (String)attr.getID();
822
            //System.out.println(attrName + "=" + attrValue);
707
 
823 708
            if ( enum1.hasMore() ) {
824 709
              attr = (Attribute)enum1.next();
825 710
              String refValue = (String)attr.get();
826 711
              String refName = (String)attr.getID();
827
              //System.out.println(refName + "=" + refValue);
828
              if ( ldapBase.startsWith(refName + "=" + refValue) ) {
712
               if ( ldapBase.startsWith(refName + "=" + refValue) ) {
829 713
                trees.put(ldapBase,
830
                          attrValue.substring(0,attrValue.lastIndexOf("/")+1) );
714
                         attrValue.substring(0,attrValue.lastIndexOf("/")+1) );
831 715
              } else {
832 716
                trees.put(refName + "=" + refValue + "," + ldapBase,
833
                          attrValue.substring(0,attrValue.lastIndexOf("/")+1) );
717
                         attrValue.substring(0,attrValue.lastIndexOf("/")+1) );
834 718
              }
835
              //System.out.println("REFERRAL:" + attrValue);
719
 
836 720
            } else if ( ldapBase.startsWith(attrName + "=" + attrValue) ) {
837 721
                trees.put(ldapBase, ldapUrl);
838 722
            } else {              
839
                trees.put(attrName + "=" + attrValue + "," + ldapBase, ldapUrl);
840
                //System.out.println(ldapUrl + attrName + "=" + attrValue + "," + ldapBase);
723
                trees.put(attrName + "=" + attrValue + "," + ldapBase, ldapUrl);               
841 724
            }
842 725
          }
843 726
        }
......
846 729
        ctx.close();
847 730

  
848 731
    } catch (NamingException e) {
849
      System.err.println("Problem getting subtrees in AuthLdap.getSubtrees:" + e);
732
      util.debugMessage("Problem getting subtrees in AuthLdap.getSubtrees:" 
733
                        + e);
850 734
      throw new ConnectException(
851 735
      "Problem getting subtrees in AuthLdap.getSubtrees:" + e);
852 736
    }
853 737

  
854
    //System.out.println("number of subtrees:" + trees.size());
855 738
    return trees;
856 739
  }
857 740

  
......
896 779
          for (int j=0; j < usersForGroup.length; j++ ) {
897 780
            usersIn.addElement(usersForGroup[j]);
898 781
            out.append("      <user>\n");
899
            out.append("        <username>" + usersForGroup[j] + "</username>\n");
782
            out.append("        <username>" + usersForGroup[j] + 
783
                        "</username>\n");
900 784
            out.append("      </user>\n");
901 785
          }
902 786
          out.append("    </group>\n");
......
934 818

  
935 819
    AuthLdap authservice = new AuthLdap();
936 820

  
937
/*
938
    // Get the list of supported controls
939
    try {
940
        // Create initial context
941
        DirContext dctx = new InitialDirContext();
942
        
943
        // Read supportedcontrol from root DSE
944
        MetaCatUtil util = new MetaCatUtil();
945
        String ldapurl = util.getOption("ldapurl");
946
        Attributes attrs = dctx.getAttributes(
947
            ldapurl, new String[]{"supportedcontrol"});
948
        
949
        System.out.println(attrs);
950
        // Close the context when we're done
951
        dctx.close();
952
    } catch (NamingException e) {
953
        e.printStackTrace();
954
    }
955
*/               
956 821
                
957 822
    boolean isValid = false;
958 823
    try {
959 824
      isValid = authservice.authenticate(user, password);
960 825
      if (isValid) {
961
        System.out.println("Authentication successful for: " + user );
826
        MetaCatUtil.debugMessage("Authentication successful for: " + user );
962 827
      } else {
963
        System.out.println("Authentication failed for: " + user);
828
        MetaCatUtil.debugMessage("Authentication failed for: " + user);
964 829
      }
965 830

  
966 831
      // Get attributes for the user
967 832
      if (isValid) {
968
        System.out.println("\nGetting attributes for user....");
833
        MetaCatUtil.debugMessage("\nGetting attributes for user....");
969 834
        HashMap userInfo = authservice.getAttributes(user, password, user);
970 835
        // Print all of the attributes
971 836
        Iterator attList = (Iterator)(((Set)userInfo.keySet()).iterator());
......
975 840
          Iterator attvalues = values.iterator();
976 841
          while (attvalues.hasNext()) {
977 842
            String value = (String)attvalues.next();
978
            System.out.println(att + ": " + value);
843
            MetaCatUtil.debugMessage(att + ": " + value);
979 844
          }
980 845
        }
981 846
      }
982 847

  
983 848
      // get the groups
984 849
      if (isValid) {
985
        System.out.println("\nGetting all groups....");
850
        MetaCatUtil.debugMessage("\nGetting all groups....");
986 851
        String[] groups = authservice.getGroups(user, password);
987
        System.out.println("Groups found: " + groups.length);
852
        MetaCatUtil.debugMessage("Groups found: " + groups.length);
988 853
        for (int i=0; i < groups.length; i++) {
989
            System.out.println("Group " + i + ": " + groups[i]);
854
            MetaCatUtil.debugMessage("Group " + i + ": " + groups[i]);
990 855
        }
991 856
      }
992 857

  
993 858
      // get the groups for the user
994 859
      String savedGroup = null;
995 860
      if (isValid) {
996
        System.out.println("\nGetting groups for user....");
861
        MetaCatUtil.debugMessage("\nGetting groups for user....");
997 862
        String[] groups = authservice.getGroups(user, password, user);
998
        System.out.println("Groups found: " + groups.length);
863
        MetaCatUtil.debugMessage("Groups found: " + groups.length);
999 864
        for (int i=0; i < groups.length; i++) {
1000
            System.out.println("Group " + i + ": " + groups[i]);
865
            MetaCatUtil.debugMessage("Group " + i + ": " + groups[i]);
1001 866
            savedGroup = groups[i];
1002 867
        }
1003 868
      }
1004 869

  
1005 870
      // get the users for a group
1006 871
      if (isValid) {
1007
        System.out.println("\nGetting users for group....");
1008
        System.out.println("Group: " + savedGroup);
872
        MetaCatUtil.debugMessage("\nGetting users for group....");
873
        MetaCatUtil.debugMessage("Group: " + savedGroup);
1009 874
        String[] users = authservice.getUsers(user, password, savedGroup);
1010
        System.out.println("Users found: " + users.length);
875
        MetaCatUtil.debugMessage("Users found: " + users.length);
1011 876
        for (int i=0; i < users.length; i++) {
1012
            System.out.println("User " + i + ": " + users[i]);
877
            MetaCatUtil.debugMessage("User " + i + ": " + users[i]);
1013 878
        }
1014 879
      }
1015 880

  
1016 881
      // get all users
1017 882
      if (isValid) {
1018
        System.out.println("\nGetting all users ....");
883
        MetaCatUtil.debugMessage("\nGetting all users ....");
1019 884
        String[] users = authservice.getUsers(user, password);
1020
        System.out.println("Users found: " + users.length);
1021
        for (int i=0; i < users.length; i++) {
1022
            //System.out.println("User " + i + ": " + users[i]);
1023
        }
885
        MetaCatUtil.debugMessage("Users found: " + users.length);
886
        
1024 887
      }
1025 888

  
1026 889
      // get the whole list groups and users in XML format
1027 890
      if (isValid) {
1028
        System.out.println("\nTrying principals....");
891
        MetaCatUtil.debugMessage("\nTrying principals....");
1029 892
        authservice = new AuthLdap();
1030 893
        String out = authservice.getPrincipals(user, password);
1031 894
        java.io.File f = new java.io.File("principals.xml");
......
1035 898
        buff.flush();
1036 899
        buff.close();
1037 900
        fw.close();
1038
        System.out.println("\nFinished getting principals.");
901
        MetaCatUtil.debugMessage("\nFinished getting principals.");
1039 902
      }
1040 903

  
1041 904
    } catch (ConnectException ce) {
1042
      System.err.println(ce.getMessage());
905
      MetaCatUtil.debugMessage(ce.getMessage());
1043 906
    } catch (java.io.IOException ioe) {
1044
      System.err.println("I/O Error writing to file principals.txt");
907
      MetaCatUtil.debugMessage("I/O Error writing to file principals.txt");
1045 908
    }
1046 909
  }
1047 910
  
911
  /**
912
   * This method will be called by start a thread.
913
   * It can handle if a referral exception happend.
914
   */ 
1048 915
  public void run()
1049 916
  {
1050 917
    referralContext = null;
1051
		DirContext refDirContext=null;
1052
		boolean moreReferrals=true;
1053
		while(moreReferrals)
1054
		{
1055
    	try
1056
    	{
1057
      	System.out.println("running thread....");
1058
				//Revise environment variable
1059
				env.put(Context.PROVIDER_URL, refExc.getReferralInfo());
1060
				env.put(Context.INITIAL_CONTEXT_FACTORY, 
1061
            "com.sun.jndi.ldap.LdapCtxFactory");
1062
				env.put(Context.SECURITY_PRINCIPAL, userName);
1063
				env.put(Context.SECURITY_CREDENTIALS, userPassword);
1064
    		env.put(Context.REFERRAL, "throw");
1065
				//Get a context object for referral in the new envriment
1066
      	rContext = refExc.getReferralContext(env);
1067
				/*System.out.println("After revsing env, referral povider_url: "+
1068
				env.get(Context.PROVIDER_URL));*/
1069
				/*System.out.println("Here is environment for rContext: ");
1070
				System.out.println(rContext.getEnvironment());*/
1071
				//Casting the context to dircontext and hopelly will create a
1072
				//autherntication or naming exception if DN and password is incorrect
1073
				referralContext=rContext;
1074
				refDirContext=(DirContext)rContext;
1075
				refDirContext.close();
1076
				//Get context and jump out the while loop
1077
				moreReferrals=false;
1078
				//System.out.println("rContext.PROVIDER_URL: "+rContext.PROVIDER_URL);
1079
				//Hashtable tempenv=rContext.getEnvironment();
1080
				//If running the above line, we will get a java.long.NullPointerException
1081
				System.out.println("exiting thread...");
1082
    	}//try
1083
			//If referral have a referral excption
1084
			catch(ReferralException re)
1085
			{
1086
				//Keep running in while loop
1087
				moreReferrals=true;
1088
				//Assign refExc to new referral exception re
1089
				refExc=re;
1090
				//System.out.println("Referral Exception again");
1091
			}//catch ref
1092
			//catch a authentication exception
1093
			catch(AuthenticationException ae)
1094
			{	
1095
				System.out.println("In referral authentication exception");
1096
				System.out.println("Error running referral handler thread: " + 
918
    DirContext refDirContext=null;
919
    boolean moreReferrals=true;
920
    //set a while loop is because we don't know if a referral excption contains
921
    //another referral exception
922
    while(moreReferrals)
923
    {
924
      try
925
      {
926
        //revise environment variable
927
        env.put(Context.PROVIDER_URL, refExc.getReferralInfo());
928
        env.put(Context.INITIAL_CONTEXT_FACTORY, 
929
                "com.sun.jndi.ldap.LdapCtxFactory");
930
        env.put(Context.SECURITY_PRINCIPAL, userName);
931
        env.put(Context.SECURITY_CREDENTIALS, userPassword);
932
        env.put(Context.REFERRAL, "throw");
933
        //get a context object for referral in the new envriment
934
        rContext = refExc.getReferralContext(env);
935
        //casting the context to dircontext and it will create a
936
        //autherntication or naming exception if DN and password is incorrect
937
        referralContext=rContext;
938
        refDirContext=(DirContext)rContext;
939
        refDirContext.close();
940
        //get context and jump out the while loop
941
        moreReferrals=false;
942
      }//try
943
      //if referral have another referral excption
944
      catch(ReferralException re)
945
      {
946
        //keep running in while loop
947
        moreReferrals=true;
948
        //assign refExc to new referral exception re
949
        refExc=re;
950
      }
951
      //catch a authentication exception
952
      catch(AuthenticationException ae)
953
      {
954
        util.debugMessage("Error running referral handler thread: " + 
1097 955
                          ae.getMessage());
1098
      	//ae.printStackTrace();
1099
				//Jump out the while loop
1100
				moreReferrals=false;
1101
				//Don't get the context
1102
      	referralContext = null;
1103
			}//catch ather exception
1104
			//catch a naming exception
1105
			catch(NamingException ne)
1106
			{
1107
				System.out.println("Error running referral handler thread: " + 
956
        //check if has another referral
957
        moreReferrals=refExc.skipReferral();
958
        //don't get the context
959
        referralContext = null;
960
      }
961
      //catch a naming exception
962
      catch(NamingException ne)
963
      {
964
        util.debugMessage("Error running referral handler thread: " + 
1108 965
                          ne.getMessage());
1109
     	 //ne.printStackTrace();
1110
			 //Jump out the loop
1111
			 moreReferrals=false;
1112
			 //Don't get context
1113
     	 referralContext = null;		
1114
			}//catch naming exception
1115
		}//while
1116
		//System.out.println("Out of while loop!");
966
        //check if has another referral
967
        moreReferrals=refExc.skipReferral();
968
        //don't get context
969
        referralContext = null;		
970
      }
971
    }//while
1117 972
  }//run()
1118 973
}

Also available in: Unified diff