Project

General

Profile

« Previous | Next » 

Revision 2121

Added by sgarg over 20 years ago

Fixed getprincipals output. Earlier DNs for LTER were in URL form. Now they appear in DN form.
Earlier:
ldap://knb.lternet.edu:389/DN,base
Now:
DN

Have to make changes so that PISCO and NRS also show up.

View differences:

src/edu/ucsb/nceas/metacat/AuthLdap.java
61 61
 * The LDAP authentication service is used to determine if a user
62 62
 * is authenticated, and whether they are a member of a particular group.
63 63
 */
64
public class AuthLdap implements AuthInterface, Runnable {
64
public class AuthLdap
65
    implements AuthInterface, Runnable {
65 66
  private MetaCatUtil util = new MetaCatUtil();
66 67
  private String ldapUrl;
67 68
  private String ldapsUrl;
......
94 95
   * @param password the password to use for authentication
95 96
   * @returns boolean true if authentication successful, false otherwise
96 97
   */
97
  public boolean authenticate(String user, String password)
98
                    throws ConnectException
99
  {
98
  public boolean authenticate(String user, String password) throws
99
      ConnectException {
100 100
    String ldapUrl = this.ldapUrl;
101 101
    String ldapsUrl = this.ldapsUrl;
102 102
    String ldapBase = this.ldapBase;
......
106 106
    //uid=user.substring(0, user.indexOf(","));
107 107

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

  
142
    } catch (NullPointerException e) {
143
    }
144
    catch (NullPointerException e) {
143 145
      util.debugMessage("NullPointerException b' password is null", 30);
144 146
      util.debugMessage("NullPointerException while authenticating in " +
145 147
                        "AuthLdap.authenticate: " + e, 30);
146 148
      throw new ConnectException(
147
      "NullPointerException while authenticating in " +
148
                        "AuthLdap.authenticate: " + e);
149
    } catch (NamingException e) {
149
          "NullPointerException while authenticating in " +
150
          "AuthLdap.authenticate: " + e);
151
    }
152
    catch (NamingException e) {
150 153
      util.debugMessage("Naming exception while authenticating in " +
151 154
                        "AuthLdap.authenticate: " + e, 30);
152 155
      e.printStackTrace();
153
    } catch (Exception e) {
156
    }
157
    catch (Exception e) {
154 158
      util.debugMessage(e.getMessage(), 30);
155 159
    }
156 160
    return authenticated;
......
163 167
   * @param identifier the distinguished name to check against LDAP
164 168
   * @param password the password for authentication
165 169
   */
166
  private boolean ldapAuthenticate(String identifier, String password)
167
            throws ConnectException, NamingException, NullPointerException
168
  {
169
      return ldapAuthenticate(identifier, password,
170
                              this.ldapsUrl, this.ldapBase);
170
  private boolean ldapAuthenticate(String identifier, String password) throws
171
      ConnectException, NamingException, NullPointerException {
172
    return ldapAuthenticate(identifier, password,
173
                            this.ldapsUrl, this.ldapBase);
171 174
  }
172 175

  
173 176
  /**
......
178 181
   * @param password the password for authentication
179 182
   */
180 183
  private boolean ldapAuthenticate(String identifier, String password,
181
            String directoryUrl, String searchBase)
182
            throws ConnectException, NamingException, NullPointerException
183
  {
184
                                   String directoryUrl, String searchBase) throws
185
      ConnectException, NamingException, NullPointerException {
184 186
    double totStartTime = System.currentTimeMillis();
185 187
    boolean authenticated = false;
186 188
    if (identifier != null && !password.equals("")) {
187 189

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

  
234
            Thread t = new Thread(this);
235
            t.start();
236
            Thread.sleep(5000); //this is a manual override of ldap's
237
                                //hideously long time out period.
238
            util.debugMessage("Awake after 5 seconds.", 35);
239
            if (referralContext == null) {
240
              t.interrupt();
241
              authenticated = false;
242
            } else {
243
              authenticated = true;
244
            }
245
          } catch (Exception e) {
239
          Thread t = new Thread(this);
240
          t.start();
241
          Thread.sleep(5000); //this is a manual override of ldap's
242
          //hideously long time out period.
243
          util.debugMessage("Awake after 5 seconds.", 35);
244
          if (referralContext == null) {
245
            t.interrupt();
246 246
            authenticated = false;
247 247
          }
248
          else {
249
            authenticated = true;
250
          }
248 251
        }
249
    } else {
250
        util.debugMessage("User not found", 30);
252
        catch (Exception e) {
253
          authenticated = false;
254
        }
255
      }
251 256
    }
257
    else {
258
      util.debugMessage("User not found", 30);
259
    }
252 260
    double totStopTime = System.currentTimeMillis();
253 261
    util.debugMessage("total ldap authentication time: " +
254
                      (totStopTime - totStartTime)/1000 + " seconds", 35);
262
                      (totStopTime - totStartTime) / 1000 + " seconds", 35);
255 263
    return authenticated;
256 264
  }
257 265

  
258

  
259

  
260 266
  /**
261 267
   * Get the identifying name for a given userid or name.  This is the name
262 268
   * that is used in conjunction withthe LDAP BaseDN to create a
......
267 273
   *          or null if not found
268 274
   */
269 275
  private String getIdentifyingName(String user, String ldapUrl,
270
                                    String ldapBase) throws NamingException
271
  {
276
                                    String ldapBase) throws NamingException {
272 277
    String identifier = null;
273 278
    // Identify service provider to use
274 279
    Hashtable env = new Hashtable(11);
......
296 301
      int position = user.indexOf(",");
297 302
      String comp1 = user.substring(0, position);
298 303
      MetaCatUtil.debugMessage("First comp is: " + comp1, 35);
299
      String comp2 = user.substring(position+1,
300
                                    user.indexOf(",", position+1));
304
      String comp2 = user.substring(position + 1,
305
                                    user.indexOf(",", position + 1));
301 306
      MetaCatUtil.debugMessage("Second comp is: " + comp2, 35);
302 307

  
303 308
      //String filter = "(&(" + comp1 + "))";
......
310 315
        answer = ctx.search("", filter, ctls);
311 316
        util.debugMessage("Search 1 complete", 35);
312 317
        if (answer == null) {
313
            util.debugMessage("Search 1 answer is null.", 35);
318
          util.debugMessage("Search 1 answer is null.", 35);
314 319
        }
315 320
        if (answer.hasMore()) {
316 321
          util.debugMessage("Search 1 has answers.", 35);
317
          SearchResult sr = (SearchResult)answer.next();
322
          SearchResult sr = (SearchResult) answer.next();
318 323
          identifier = sr.getName();
319 324
          util.debugMessage("Originally Found: " + identifier, 35);
320 325
          return identifier;
321 326
        }
322
      } catch (InvalidSearchFilterException e) {
323
          util.debugMessage("Invalid Filter exception thrown (if1)", 35);
324 327
      }
328
      catch (InvalidSearchFilterException e) {
329
        util.debugMessage("Invalid Filter exception thrown (if1)", 35);
330
      }
325 331

  
326 332
      // That failed, so check if it is just a username
327 333
      filter = "(" + user + ")";
......
329 335
        MetaCatUtil.debugMessage("Trying again: " + filter, 35);
330 336
        answer = ctx.search("", filter, ctls);
331 337
        if (answer.hasMore()) {
332
          SearchResult sr = (SearchResult)answer.next();
338
          SearchResult sr = (SearchResult) answer.next();
333 339
          identifier = sr.getName();
334
          if ( !sr.isRelative() ) {
340
          if (!sr.isRelative()) {
335 341
            this.ldapUrl = identifier.substring(0,
336
                                                identifier.lastIndexOf("/")+1);
337
            this.ldapBase = identifier.substring(identifier.indexOf(",")+1);
338
            identifier = identifier.substring(identifier.lastIndexOf("/")+1,
342
                                                identifier.lastIndexOf("/") + 1);
343
            this.ldapBase = identifier.substring(identifier.indexOf(",") + 1);
344
            identifier = identifier.substring(identifier.lastIndexOf("/") + 1,
339 345
                                              identifier.indexOf(","));
340 346
          }
341 347
          util.debugMessage("Found: " + identifier, 35);
342 348
          return identifier;
343 349
        }
344
      } catch (InvalidSearchFilterException e) {}
350
      }
351
      catch (InvalidSearchFilterException e) {}
345 352

  
346 353
      // Maybe its a user id (uid)
347 354
      filter = "(uid=" + user + ")";
348 355
      MetaCatUtil.debugMessage("Trying again: " + filter, 35);
349 356
      answer = ctx.search("", filter, ctls);
350 357
      if (answer.hasMore()) {
351
        SearchResult sr = (SearchResult)answer.next();
358
        SearchResult sr = (SearchResult) answer.next();
352 359
        identifier = sr.getName();
353
        if ( !sr.isRelative() ) {
354
          this.ldapUrl = identifier.substring(0,identifier.lastIndexOf("/")+1);
355
          this.ldapBase = identifier.substring(identifier.indexOf(",")+1);
356
          identifier = identifier.substring(identifier.lastIndexOf("/")+1,
360
        if (!sr.isRelative()) {
361
          this.ldapUrl = identifier.substring(0,
362
                                              identifier.lastIndexOf("/") + 1);
363
          this.ldapBase = identifier.substring(identifier.indexOf(",") + 1);
364
          identifier = identifier.substring(identifier.lastIndexOf("/") + 1,
357 365
                                            identifier.indexOf(","));
358 366
        }
359 367
        util.debugMessage("Found: " + identifier, 35);
360
      } else {
368
      }
369
      else {
361 370

  
362 371
        // maybe its just a common name
363 372
        filter = "(cn=" + user + ")";
364 373
        MetaCatUtil.debugMessage("Trying again: " + filter, 35);
365 374
        NamingEnumeration answer2 = ctx.search("", filter, ctls);
366 375
        if (answer2.hasMore()) {
367
          SearchResult sr = (SearchResult)answer2.next();
376
          SearchResult sr = (SearchResult) answer2.next();
368 377
          identifier = sr.getName();
369
          if ( !sr.isRelative() ) {
378
          if (!sr.isRelative()) {
370 379
            this.ldapUrl = identifier.substring(0,
371
                                                identifier.lastIndexOf("/")+1);
372
            this.ldapBase = identifier.substring(identifier.indexOf(",")+1);
373
            identifier = identifier.substring(identifier.lastIndexOf("/")+1,
380
                                                identifier.lastIndexOf("/") + 1);
381
            this.ldapBase = identifier.substring(identifier.indexOf(",") + 1);
382
            identifier = identifier.substring(identifier.lastIndexOf("/") + 1,
374 383
                                              identifier.indexOf(","));
375 384
          }
376 385
          util.debugMessage("Found: " + identifier, 35);
377
        } else {
386
        }
387
        else {
378 388

  
379 389
          // ok, last resort, is it a surname?
380 390
          filter = "(sn=" + user + ")";
381 391
          MetaCatUtil.debugMessage("Trying again: " + filter, 35);
382 392
          NamingEnumeration answer3 = ctx.search("", filter, ctls);
383 393
          if (answer3.hasMore()) {
384
            SearchResult sr = (SearchResult)answer3.next();
394
            SearchResult sr = (SearchResult) answer3.next();
385 395
            identifier = sr.getName();
386
            if ( !sr.isRelative() ) {
396
            if (!sr.isRelative()) {
387 397
              this.ldapUrl = identifier.substring(0,
388
                                                identifier.lastIndexOf("/")+1);
389
              this.ldapBase = identifier.substring(identifier.indexOf(",")+1);
390
              identifier = identifier.substring(identifier.lastIndexOf("/")+1,
398
                                                  identifier.lastIndexOf("/") +
399
                                                  1);
400
              this.ldapBase = identifier.substring(identifier.indexOf(",") + 1);
401
              identifier = identifier.substring(identifier.lastIndexOf("/") + 1,
391 402
                                                identifier.indexOf(","));
392 403
            }
393 404
            util.debugMessage("Found: " + identifier, 35);
......
396 407
      }
397 408
      // Close the context when we're done the initial search
398 409
      ctx.close();
399
    } catch (NamingException e) {
410
    }
411
    catch (NamingException e) {
400 412
      util.debugMessage("Naming exception while getting dn: " + e, 35);
401 413
      throw new NamingException(
402
      "Naming exception in AuthLdap.getIdentifyingName: " + e);
414
          "Naming exception in AuthLdap.getIdentifyingName: " + e);
403 415
    }
404 416
    MetaCatUtil.debugMessage("Returning found identifier as: " + identifier, 35);
405 417
    return identifier;
......
412 424
   * @param password the password for authenticating against the service
413 425
   * @returns string array of all of the user names
414 426
   */
415
  public String[][] getUsers(String user, String password)
416
         throws ConnectException
417
  {
427
  public String[][] getUsers(String user, String password) throws
428
      ConnectException {
418 429
    String[][] users = null;
419 430

  
420 431
    // Identify service provider to use
......
426 437

  
427 438
    try {
428 439

  
429
        // Create the initial directory context
430
        DirContext ctx = new InitialDirContext(env);
440
      // Create the initial directory context
441
      DirContext ctx = new InitialDirContext(env);
431 442

  
432
        // Specify the attributes to match.
433
        // Users are objects that have the attribute objectclass=InetOrgPerson.
434
        SearchControls ctls = new SearchControls();
435
        String[] attrIDs = {"dn", "cn", "o", "mail"};
436
        ctls.setReturningAttributes(attrIDs);
437
        ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
438
        //ctls.setCountLimit(1000);
439
        String filter = "(objectClass=inetOrgPerson)";
440
        NamingEnumeration enum = ctx.search(ldapBase, filter, ctls);
443
      // Specify the attributes to match.
444
      // Users are objects that have the attribute objectclass=InetOrgPerson.
445
      SearchControls ctls = new SearchControls();
446
      String[] attrIDs = {
447
          "dn", "cn", "o", "mail"};
448
      ctls.setReturningAttributes(attrIDs);
449
      ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
450
      //ctls.setCountLimit(1000);
451
      String filter = "(objectClass=inetOrgPerson)";
452
      NamingEnumeration enum = ctx.search(ldapBase, filter, ctls);
441 453

  
442
        // Store the users in a vector
443
        Vector uvec = new Vector();
444
        Vector uname = new Vector();
445
        Vector uorg = new Vector();
446
        Vector umail = new Vector();
447
        Attributes tempAttr = null;
448
        try {
449
            while (enum.hasMore()) {
450
                SearchResult sr = (SearchResult)enum.next();
451
                tempAttr = sr.getAttributes();
454
      // Store the users in a vector
455
      Vector uvec = new Vector();
456
      Vector uname = new Vector();
457
      Vector uorg = new Vector();
458
      Vector umail = new Vector();
459
      Attributes tempAttr = null;
460
      try {
461
        while (enum.hasMore()) {
462
          SearchResult sr = (SearchResult) enum.next();
463
          tempAttr = sr.getAttributes();
452 464

  
453
                if((tempAttr.get("cn")+"").startsWith("cn: ")){
454
                  uname.add( (tempAttr.get("cn") + "").substring(4));
455
                } else {
456
                  uname.add( tempAttr.get("cn") + "");
457
                }
465
          if ( (tempAttr.get("cn") + "").startsWith("cn: ")) {
466
            uname.add( (tempAttr.get("cn") + "").substring(4));
467
          }
468
          else {
469
            uname.add(tempAttr.get("cn") + "");
470
          }
458 471

  
459
                if((tempAttr.get("o")+"").startsWith("o: ")){
460
                  uorg.add( (tempAttr.get("o") + "").substring(3));
461
                } else {
462
                  uorg.add( tempAttr.get("o") + "");
463
                }
472
          if ( (tempAttr.get("o") + "").startsWith("o: ")) {
473
            uorg.add( (tempAttr.get("o") + "").substring(3));
474
          }
475
          else {
476
            uorg.add(tempAttr.get("o") + "");
477
          }
464 478

  
465
                if((tempAttr.get("mail")+"").startsWith("mail: ")){
466
                  umail.add((tempAttr.get("mail") + "").substring(6));
467
                } else {
468
                  umail.add(tempAttr.get("mail") + "");
469
                }
479
          if ( (tempAttr.get("mail") + "").startsWith("mail: ")) {
480
            umail.add( (tempAttr.get("mail") + "").substring(6));
481
          }
482
          else {
483
            umail.add(tempAttr.get("mail") + "");
484
          }
470 485

  
471
                uvec.add(sr.getName()+","+ldapBase);
472
            }
473
        } catch (SizeLimitExceededException slee) {
474
            util.debugMessage("LDAP Server size limit exceeded. " +
475
                    "Returning incomplete record set.", 35);
486
          uvec.add(sr.getName() + "," + ldapBase);
476 487
        }
488
      }
489
      catch (SizeLimitExceededException slee) {
490
        util.debugMessage("LDAP Server size limit exceeded. " +
491
                          "Returning incomplete record set.", 35);
492
      }
477 493

  
478
        // initialize users[]; fill users[]
479
        users = new String[uvec.size()][4];
480
        for (int i=0; i < uvec.size(); i++) {
481
          users[i][0] = (String)uvec.elementAt(i);
482
          users[i][1] = (String)uname.elementAt(i);
483
          users[i][2]   = (String)uorg.elementAt(i);
484
          users[i][3] = (String)umail.elementAt(i);
485
        }
494
      // initialize users[]; fill users[]
495
      users = new String[uvec.size()][4];
496
      for (int i = 0; i < uvec.size(); i++) {
497
        users[i][0] = (String) uvec.elementAt(i);
498
        users[i][1] = (String) uname.elementAt(i);
499
        users[i][2] = (String) uorg.elementAt(i);
500
        users[i][3] = (String) umail.elementAt(i);
501
      }
486 502

  
487
        // Close the context when we're done
488
        ctx.close();
503
      // Close the context when we're done
504
      ctx.close();
489 505

  
490
    } catch (NamingException e) {
506
    }
507
    catch (NamingException e) {
491 508
      util.debugMessage("Problem getting users in AuthLdap.getUsers:" + e, 35);
492 509
      //e.printStackTrace(System.err);
493 510
      throw new ConnectException(
494
      "Problem getting users in AuthLdap.getUsers:" + e);
511
          "Problem getting users in AuthLdap.getUsers:" + e);
495 512
    }
496 513

  
497 514
    return users;
......
505 522
   * @param group the group whose user list should be returned
506 523
   * @returns string array of the user names belonging to the group
507 524
   */
508
  public String[] getUsers(String user, String password, String group)
509
         throws ConnectException
510
  {
525
  public String[] getUsers(String user, String password, String group) throws
526
      ConnectException {
511 527
    String[] users = null;
512 528

  
513 529
    // Identify service provider to use
......
519 535

  
520 536
    try {
521 537

  
522
        // Create the initial directory context
523
        DirContext ctx = new InitialDirContext(env);
538
      // Create the initial directory context
539
      DirContext ctx = new InitialDirContext(env);
524 540

  
525
        // Specify the ids of the attributes to return
526
        String[] attrIDs = {"uniqueMember"};
541
      // Specify the ids of the attributes to return
542
      String[] attrIDs = {
543
          "uniqueMember"};
527 544

  
528
        Attributes answer = ctx.getAttributes(group, attrIDs);
545
      Attributes answer = ctx.getAttributes(group, attrIDs);
529 546

  
530
        Vector uvec = new Vector();
531
        try {
532
            for (NamingEnumeration ae = answer.getAll(); ae.hasMore();) {
533
                Attribute attr = (Attribute)ae.next();
534
                for (NamingEnumeration e = attr.getAll();
535
                     e.hasMore();
536
                     uvec.add(e.next())
537
                    );
538
            }
539
        } catch (SizeLimitExceededException slee) {
540
            util.debugMessage("LDAP Server size limit exceeded. " +
541
                    "Returning incomplete record set.", 35);
547
      Vector uvec = new Vector();
548
      try {
549
        for (NamingEnumeration ae = answer.getAll(); ae.hasMore(); ) {
550
          Attribute attr = (Attribute) ae.next();
551
          for (NamingEnumeration e = attr.getAll();
552
               e.hasMore();
553
               uvec.add(e.next())
554
               ) {
555
            ;
556
          }
542 557
        }
558
      }
559
      catch (SizeLimitExceededException slee) {
560
        util.debugMessage("LDAP Server size limit exceeded. " +
561
                          "Returning incomplete record set.", 35);
562
      }
543 563

  
544
        // initialize users[]; fill users[]
545
        users = new String[uvec.size()];
546
        for (int i=0; i < uvec.size(); i++) {
547
          users[i] = (String)uvec.elementAt(i);
548
        }
564
      // initialize users[]; fill users[]
565
      users = new String[uvec.size()];
566
      for (int i = 0; i < uvec.size(); i++) {
567
        users[i] = (String) uvec.elementAt(i);
568
      }
549 569

  
550
        // Close the context when we're done
551
        ctx.close();
570
      // Close the context when we're done
571
      ctx.close();
552 572

  
553
    } catch (NamingException e) {
573
    }
574
    catch (NamingException e) {
554 575
      util.debugMessage("Problem getting users for a group in " +
555
              "AuthLdap.getUsers:" + e, 30);
576
                        "AuthLdap.getUsers:" + e, 30);
556 577
      throw new ConnectException(
557
      "Problem getting users for a group in AuthLdap.getUsers:" + e);
578
          "Problem getting users for a group in AuthLdap.getUsers:" + e);
558 579
    }
559 580

  
560 581
    return users;
......
567 588
   * @param password the password for authenticating against the service
568 589
   * @returns string array of the group names
569 590
   */
570
  public String[][] getGroups(String user, String password)
571
         throws ConnectException
572
  {
573
      return getGroups(user, password, null);
591
  public String[][] getGroups(String user, String password) throws
592
      ConnectException {
593
    return getGroups(user, password, null);
574 594
  }
575 595

  
576 596
  /**
......
581 601
   * @param foruser the user whose group list should be returned
582 602
   * @returns string array of the group names
583 603
   */
584
  public String[][] getGroups(String user, String password, String foruser)
585
         throws ConnectException
586
  {
604
  public String[][] getGroups(String user, String password, String foruser) throws
605
      ConnectException {
587 606
    Vector gvec = new Vector();
588 607
    Vector desc = new Vector();
589 608
    Attributes tempAttr = null;
590 609

  
591 610
    //Pass the username and password to run() method
592
    userName=user;
593
    userPassword=password;
611
    userName = user;
612
    userPassword = password;
594 613
    // Identify service provider to use
595 614
    env.put(Context.INITIAL_CONTEXT_FACTORY,
596 615
            "com.sun.jndi.ldap.LdapCtxFactory");
597 616
    env.put(Context.REFERRAL, "throw");
598 617
    env.put(Context.PROVIDER_URL, ldapUrl);
599 618
    try {
600
        // Create the initial directory context
601
        DirContext ctx = new InitialDirContext(env);
602
        // Specify the ids of the attributes to return
603
        String[] attrIDs = {"cn", "o", "description"};
604
        // Specify the attributes to match.
605
        // Groups are objects with attribute objectclass=groupofuniquenames.
606
        // and have attribute uniquemember: uid=foruser,ldapbase.
607
        SearchControls ctls = new SearchControls();
608
        ctls.setReturningAttributes(attrIDs);
609
        ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
619
      // Create the initial directory context
620
      DirContext ctx = new InitialDirContext(env);
621
      // Specify the ids of the attributes to return
622
      String[] attrIDs = {
623
          "cn", "o", "description"};
624
      // Specify the attributes to match.
625
      // Groups are objects with attribute objectclass=groupofuniquenames.
626
      // and have attribute uniquemember: uid=foruser,ldapbase.
627
      SearchControls ctls = new SearchControls();
628
      ctls.setReturningAttributes(attrIDs);
629
      ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
610 630

  
611
        String filter = null;
612
        String gfilter = "(objectClass=groupOfUniqueNames)";
613
        if (null == foruser) {
614
            filter = gfilter;
615
        } else {
616
            filter = "(& " + gfilter + "(uniqueMember=" + foruser + "))";
617
        }
618
        MetaCatUtil.debugMessage("searching for groups: " + filter, 35);
619
        NamingEnumeration enum = ctx.search(ldapBase, filter, ctls);
631
      String filter = null;
632
      String gfilter = "(objectClass=groupOfUniqueNames)";
633
      if (null == foruser) {
634
        filter = gfilter;
635
      }
636
      else {
637
        filter = "(& " + gfilter + "(uniqueMember=" + foruser + "))";
638
      }
639
      MetaCatUtil.debugMessage("searching for groups: " + filter, 35);
640
      NamingEnumeration enum = ctx.search(ldapBase, filter, ctls);
620 641

  
621
        // Print the groups
622
        MetaCatUtil.debugMessage("getting group results.", 50);
623
        while (enum.hasMore()) {
624
          SearchResult sr = (SearchResult)enum.next();
625
          tempAttr = sr.getAttributes();
642
      // Print the groups
643
      MetaCatUtil.debugMessage("getting group results.", 50);
644
      while (enum.hasMore()) {
645
        SearchResult sr = (SearchResult) enum.next();
646
        tempAttr = sr.getAttributes();
626 647

  
627
          if((tempAttr.get("description")+"").startsWith("description: ")){
628
            desc.add( (tempAttr.get("description") + "").substring(13));
629
          } else {
630
            desc.add( tempAttr.get("description") + "");
631
          }
632

  
633
          gvec.add(sr.getName()+","+ldapBase);
634
          MetaCatUtil.debugMessage("group " + sr.getName() +
635
                                  " added to Group vector", 35);
648
        if ( (tempAttr.get("description") + "").startsWith("description: ")) {
649
          desc.add( (tempAttr.get("description") + "").substring(13));
636 650
        }
637
        // Close the context when we're done
638
        ctx.close();
651
        else {
652
          desc.add(tempAttr.get("description") + "");
653
        }
639 654

  
655
        gvec.add(sr.getName() + "," + ldapBase);
656
        MetaCatUtil.debugMessage("group " + sr.getName() +
657
                                 " added to Group vector", 35);
658
      }
659
      // Close the context when we're done
660
      ctx.close();
661

  
640 662
    }
641
    catch (ReferralException re)
642
    {
663
    catch (ReferralException re) {
643 664
      refExc = re;
644 665
      Thread t = new Thread(new GetGroup());
645 666
      util.debugMessage("Starting thread...", 50);
646 667
      t.start();
647 668
      util.debugMessage("sleeping for 5 seconds.", 50);
648
      try
649
      {
669
      try {
650 670
        Thread.sleep(5000);
651 671
      }
652
      catch(InterruptedException ie)
653
      {
654
        MetaCatUtil.debugMessage("main thread interrupted: " + ie.getMessage(), 30);
672
      catch (InterruptedException ie) {
673
        MetaCatUtil.debugMessage("main thread interrupted: " + ie.getMessage(),
674
                                 30);
655 675
      }
656 676
      //this is a manual override of jndi's hideously long time
657 677
      //out period.
658 678
      util.debugMessage("Awake after 5 seconds.", 40);
659
      if (referralContext == null)
660
      {
661
        util.debugMessage("thread timed out...returning groups: " + gvec.toString(), 35);
679
      if (referralContext == null) {
680
        util.debugMessage("thread timed out...returning groups: " +
681
                          gvec.toString(), 35);
662 682
        String groups[][] = new String[gvec.size()][2];
663
        for(int i=0; i<gvec.size(); i++)
664
        {
665
          groups[i][0] = (String)gvec.elementAt(i);
666
          groups[i][1] = (String)desc.elementAt(i);
683
        for (int i = 0; i < gvec.size(); i++) {
684
          groups[i][0] = (String) gvec.elementAt(i);
685
          groups[i][1] = (String) desc.elementAt(i);
667 686
        }
668 687
        t.interrupt();
669 688
        return groups;
670 689
      }
671
      DirContext dc = (DirContext)referralContext;
672
      String[] attrIDs = {"cn", "o", "description"};
690
      DirContext dc = (DirContext) referralContext;
691
      String[] attrIDs = {
692
          "cn", "o", "description"};
673 693
      // Specify the attributes to match.
674 694
      // Groups are objects with attribute objectclass=groupofuniquenames.
675 695
      // and have attribute uniquemember: uid=foruser,ldapbase.
......
680 700
      String filter = null;
681 701
      String gfilter = "(objectClass=groupOfUniqueNames)";
682 702
      if (null == foruser) {
683
          filter = gfilter;
684
      } else {
685
          filter = "(& " + gfilter + "(uniqueMember=" + foruser + "))";
703
        filter = gfilter;
686 704
      }
705
      else {
706
        filter = "(& " + gfilter + "(uniqueMember=" + foruser + "))";
707
      }
687 708

  
688
      try
689
      {
709
      try {
690 710
        NamingEnumeration enum = dc.search(ldapBase, filter, ctls);
691 711
        // Print the groups
692 712
        while (enum.hasMore()) {
693
          SearchResult sr = (SearchResult)enum.next();
713
          SearchResult sr = (SearchResult) enum.next();
694 714
          tempAttr = sr.getAttributes();
695 715

  
696
          if((tempAttr.get("description")+"").startsWith("description: ")){
716
          if ( (tempAttr.get("description") + "").startsWith("description: ")) {
697 717
            desc.add( (tempAttr.get("description") + "").substring(13));
698
          } else {
699
            desc.add( tempAttr.get("description") + "");
700 718
          }
719
          else {
720
            desc.add(tempAttr.get("description") + "");
721
          }
701 722

  
702
          gvec.add(sr.getName()+","+ldapBase);
723
          gvec.add(sr.getName() + "," + ldapBase);
703 724
        }
704 725

  
705 726
        referralContext.close();
706 727
        dc.close();
707 728
      }
708
      catch(NamingException ne)
709
      {
710
        MetaCatUtil.debugMessage("Naming Exception in AuthLdap.getGroups" + ne.getExplanation() + ne.getMessage(), 30);
729
      catch (NamingException ne) {
730
        MetaCatUtil.debugMessage("Naming Exception in AuthLdap.getGroups" +
731
                                 ne.getExplanation() + ne.getMessage(), 30);
711 732
      }
712
    } catch (NamingException e) {
733
    }
734
    catch (NamingException e) {
713 735
      e.printStackTrace(System.err);
714 736
      String groups[][] = new String[gvec.size()][2];
715
      for(int i=0; i<gvec.size(); i++)
716
      {
717
        groups[i][0] = (String)gvec.elementAt(i);
718
        groups[i][1] = (String)desc.elementAt(i);
737
      for (int i = 0; i < gvec.size(); i++) {
738
        groups[i][0] = (String) gvec.elementAt(i);
739
        groups[i][1] = (String) desc.elementAt(i);
719 740
      }
720 741
      return groups;
721
       /*throw new ConnectException(
722
      "Problem getting groups for a user in AuthLdap.getGroups:" + e);*/
742
      /*throw new ConnectException(
743
             "Problem getting groups for a user in AuthLdap.getGroups:" + e);*/
723 744
    }
724 745

  
725 746
    MetaCatUtil.debugMessage("The user is in the following groups: " +
726
                              gvec.toString(), 35);
747
                             gvec.toString(), 35);
727 748
    String groups[][] = new String[gvec.size()][2];
728
    for(int i=0; i<gvec.size(); i++)
729
    {
730
      groups[i][0] = (String)gvec.elementAt(i);
731
      groups[i][1] = (String)desc.elementAt(i);
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);
732 752
    }
733 753
    return groups;
734 754
  }
......
739 759
   * @param foruser the user for which the attribute list is requested
740 760
   * @returns HashMap a map of attribute name to a Vector of values
741 761
   */
742
  public HashMap getAttributes(String foruser)
743
         throws ConnectException
744
  {
762
  public HashMap getAttributes(String foruser) throws ConnectException {
745 763
    return getAttributes(null, null, foruser);
746 764
  }
747 765

  
......
753 771
   * @param foruser the user whose attributes should be returned
754 772
   * @returns HashMap a map of attribute name to a Vector of values
755 773
   */
756
  public HashMap getAttributes(String user, String password, String foruser)
757
         throws ConnectException
758
  {
774
  public HashMap getAttributes(String user, String password, String foruser) throws
775
      ConnectException {
759 776
    HashMap attributes = new HashMap();
760 777
    String ldapUrl = this.ldapUrl;
761 778
    String ldapBase = this.ldapBase;
......
764 781
    // Identify service provider to use
765 782
    Hashtable env = new Hashtable(11);
766 783
    env.put(Context.INITIAL_CONTEXT_FACTORY,
767
        "com.sun.jndi.ldap.LdapCtxFactory");
784
            "com.sun.jndi.ldap.LdapCtxFactory");
768 785
    env.put(Context.REFERRAL, referral);
769 786
    env.put(Context.PROVIDER_URL, ldapUrl);
770 787

  
......
780 797
      // Print all of the attributes
781 798
      NamingEnumeration en = attrs.getAll();
782 799
      while (en.hasMore()) {
783
        Attribute att = (Attribute)en.next();
800
        Attribute att = (Attribute) en.next();
784 801
        Vector values = new Vector();
785 802
        String attName = att.getID();
786 803
        NamingEnumeration attvalues = att.getAll();
787 804
        while (attvalues.hasMore()) {
788
          String value = (String)attvalues.next();
805
          String value = (String) attvalues.next();
789 806
          values.add(value);
790 807
        }
791 808
        attributes.put(attName, values);
......
793 810

  
794 811
      // Close the context when we're done
795 812
      ctx.close();
796
    } catch (NamingException e) {
813
    }
814
    catch (NamingException e) {
797 815
      util.debugMessage("Problem getting attributes in " +
798
              "AuthLdap.getAttributes:" + e, 35);
816
                        "AuthLdap.getAttributes:" + e, 35);
799 817
      throw new ConnectException(
800
      "Problem getting attributes in AuthLdap.getAttributes:" + e);
818
          "Problem getting attributes in AuthLdap.getAttributes:" + e);
801 819
    }
802 820

  
803 821
    return attributes;
......
809 827
   * i.e. ldap://dev.nceas.ucsb.edu/dc=ecoinformatics,dc=org
810 828
   */
811 829
  private Hashtable getSubtrees(String user, String password,
812
                                String ldapUrl, String ldapBase)
813
                throws ConnectException
814
  {
830
                                String ldapUrl, String ldapBase) throws
831
      ConnectException {
815 832
    Hashtable trees = new Hashtable();
816 833

  
817 834
    // Identify service provider to use
......
823 840

  
824 841
    try {
825 842

  
826
        // Create the initial directory context
827
        DirContext ctx = new InitialDirContext(env);
843
      // Create the initial directory context
844
      DirContext ctx = new InitialDirContext(env);
828 845

  
829
        // Specify the ids of the attributes to return
830
        String[] attrIDs = {"o","ref"};
831
        SearchControls ctls = new SearchControls();
832
        ctls.setReturningAttributes(attrIDs);
833
        ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
846
      // Specify the ids of the attributes to return
847
      String[] attrIDs = {
848
          "o", "ref"};
849
      SearchControls ctls = new SearchControls();
850
      ctls.setReturningAttributes(attrIDs);
851
      ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
834 852

  
835
        // Specify the attributes to match.
836
        // Subtrees from the main server are found as objects with attribute
837
        // objectclass=organization or objectclass=referral to the subtree
838
        // resided on other server.
839
        String filter = "(|(objectclass=organization)(objectclass=referral))";
853
      // Specify the attributes to match.
854
      // Subtrees from the main server are found as objects with attribute
855
      // objectclass=organization or objectclass=referral to the subtree
856
      // resided on other server.
857
      String filter = "(|(objectclass=organization)(objectclass=referral))";
840 858

  
841
        // Search for objects in the current context
842
        NamingEnumeration enum = ctx.search("", filter, ctls);
859
      // Search for objects in the current context
860
      NamingEnumeration enum = ctx.search("", filter, ctls);
843 861

  
844
        // Print the subtrees' <ldapURL, baseDN>
845
        while (enum.hasMore()) {
846
          SearchResult sr = (SearchResult)enum.next();
847
          Attributes attrs = sr.getAttributes();
848
          NamingEnumeration enum1 = attrs.getAll(); // "dc" and "ref" attrs
862
      // Print the subtrees' <ldapURL, baseDN>
863
      while (enum.hasMore()) {
864

  
865
        SearchResult sr = (SearchResult) enum.next();
866

  
867
   //     util.debugMessage("SSSSSSSSSGGGGG: enum " + sr.toString() , 9);
868
   //     util.debugMessage("SSSSSSSSSGGGGG: enum " + sr.getName() , 9);
869
        Attributes attrs = sr.getAttributes();
870
        NamingEnumeration enum1 = attrs.getAll(); // "dc" and "ref" attrs
871

  
872
//        while (enum1.hasMore()) {
873
  //        Attribute attr = (Attribute) enum1.next();
874
    //      String attrValue = (String) attr.get();
875
     //     String attrName = (String) attr.getID();
876
     //   }
877

  
878
        if (enum1.hasMore()) {
879
          Attribute attr = (Attribute) enum1.next();
880
          String attrValue = (String) attr.get();
881
          String attrName = (String) attr.getID();
882

  
849 883
          if (enum1.hasMore()) {
850
            Attribute attr = (Attribute)enum1.next();
851
            String attrValue = (String)attr.get();
852
            String attrName = (String)attr.getID();
884
            attr = (Attribute) enum1.next();
885
            String refValue = (String) attr.get();
886
            String refName = (String) attr.getID();
887
            if (ldapBase.startsWith(refName + "=" + refValue)) {
888
              trees.put(ldapBase,
889
                        attrValue.substring(0, attrValue.lastIndexOf("/") + 1));
890
            }
891
            else {
892
              trees.put(refName + "=" + refValue + "," + ldapBase,
893
                        attrValue.substring(0, attrValue.lastIndexOf("/") + 1));
894
            }
853 895

  
854
            if ( enum1.hasMore() ) {
855
              attr = (Attribute)enum1.next();
856
              String refValue = (String)attr.get();
857
              String refName = (String)attr.getID();
858
               if ( ldapBase.startsWith(refName + "=" + refValue) ) {
859
                trees.put(ldapBase,
860
                         attrValue.substring(0,attrValue.lastIndexOf("/")+1) );
861
              } else {
862
                trees.put(refName + "=" + refValue + "," + ldapBase,
863
                         attrValue.substring(0,attrValue.lastIndexOf("/")+1) );
864
              }
865

  
866
            } else if ( ldapBase.startsWith(attrName + "=" + attrValue) ) {
867
                trees.put(ldapBase, ldapUrl);
896
          }
897
          else if (ldapBase.startsWith(attrName + "=" + attrValue)) {
898
            trees.put(ldapBase, ldapUrl);
899
          }
900
          else {
901
            if(sr.isRelative()){
902
              trees.put(attrName + "=" + attrValue + "," + ldapBase, ldapUrl);
868 903
            } else {
869
                trees.put(attrName + "=" + attrValue + "," + ldapBase, ldapUrl);
904
              String referenceURL = sr.getName();
905
              referenceURL = referenceURL.substring(0, referenceURL.lastIndexOf("/") + 1);
906
              trees.put(attrName + "=" + attrValue + "," + ldapBase, referenceURL);
870 907
            }
908

  
871 909
          }
872 910
        }
911
      }
873 912

  
874
        // Close the context when we're done
875
        ctx.close();
913
      // Close the context when we're done
914
      ctx.close();
876 915

  
877
    } catch (NamingException e) {
916
    }
917
    catch (NamingException e) {
878 918
      util.debugMessage("Problem getting subtrees in AuthLdap.getSubtrees:"
879 919
                        + e, 30);
880 920
      throw new ConnectException(
881
      "Problem getting subtrees in AuthLdap.getSubtrees:" + e);
921
          "Problem getting subtrees in AuthLdap.getSubtrees:" + e);
882 922
    }
883 923

  
924
  //  util.debugMessage("SSSSSSSSSGGGGG: trees: " + trees.toString() , 9);
884 925
    return trees;
885 926
  }
886 927

  
......
890 931
   * @param user the user which requests the information
891 932
   * @param password the user's password
892 933
   */
893
  public String getPrincipals(String user, String password)
894
                throws ConnectException
895
  {
934
  public String getPrincipals(String user, String password) throws
935
      ConnectException {
896 936
    StringBuffer out = new StringBuffer();
897 937
    Vector usersIn = new Vector();
898 938

  
......
903 943
     * get all subtrees first in the current dir context
904 944
     * and then the Metacat users under them
905 945
     */
906
    Hashtable subtrees = getSubtrees(user,password,this.ldapUrl,this.ldapBase);
946
    Hashtable subtrees = getSubtrees(user, password, this.ldapUrl,
947
                                     this.ldapBase);
907 948

  
908 949
    Enumeration enum = subtrees.keys();
909
    while ( enum.hasMoreElements() ) {
910
      this.ldapBase = (String)enum.nextElement();
911
      this.ldapUrl = (String)subtrees.get(ldapBase);
950
    while (enum.hasMoreElements()) {
951
      this.ldapBase = (String) enum.nextElement();
952
      this.ldapUrl = (String) subtrees.get(ldapBase);
912 953

  
913 954
      String orgName = this.ldapBase;
914
      if(orgName != null && orgName.indexOf("o=") > -1){
915
        orgName = orgName.substring(orgName.indexOf("o=") +2);
955
      if (orgName != null && orgName.indexOf("o=") > -1) {
956
        orgName = orgName.substring(orgName.indexOf("o=") + 2);
916 957
        orgName = orgName.substring(0, orgName.indexOf(","));
917
      } else {
958
      }
959
      else {
918 960
        orgName = "";
919 961
      }
920
      
962

  
921 963
      out.append("  <authSystem URI=\"" +
922
                 this.ldapUrl + this.ldapBase + "\" organization=\"" + orgName +"\">\n");
964
                 this.ldapUrl + this.ldapBase + "\" organization=\"" + orgName +
965
                 "\">\n");
923 966

  
924 967
      // get all groups for directory context
925 968
      String[][] groups = getGroups(user, password);
......
927 970
      int userIndex = 0;
928 971

  
929 972
      // for the groups and users that belong to them
930
      if ( groups!=null && groups.length > 0 ) {
931
        for (int i=0; i < groups.length; i++ ) {
973
      if (groups != null && groups.length > 0) {
974
        for (int i = 0; i < groups.length; i++) {
932 975
          out.append("    <group>\n");
933 976
          out.append("      <groupname>" + groups[i][0] + "</groupname>\n");
934 977
          out.append("      <description>" + groups[i][1] + "</description>\n");
935
          String[] usersForGroup = getUsers(user,password,groups[i][0]);
936
          for (int j=0; j < usersForGroup.length; j++ ) {
978
          String[] usersForGroup = getUsers(user, password, groups[i][0]);
979
          for (int j = 0; j < usersForGroup.length; j++) {
937 980
            usersIn.addElement(usersForGroup[j]);
938 981

  
939 982
            userIndex = searchUser(usersForGroup[j], users);
940 983
            out.append("      <user>\n");
941 984

  
942
            if(userIndex < 0){
985
            if (userIndex < 0) {
943 986
              out.append("        <username>" + usersForGroup[j] +
944 987
                         "</username>\n");
945
            } else {
946
              out.append("      <username>" + users[userIndex][0] + "</username>\n");
988
            }
989
            else {
990
              out.append("      <username>" + users[userIndex][0] +
991
                         "</username>\n");
947 992
              out.append("      <name>" + users[userIndex][1] + "</name>\n");
948
              out.append("      <organization>" + users[userIndex][2] + "</organization>\n");
993
              out.append("      <organization>" + users[userIndex][2] +
994
                         "</organization>\n");
949 995
              out.append("      <email>" + users[userIndex][3] + "</email>\n");
950 996
            }
951 997

  
......
956 1002
      }
957 1003

  
958 1004
      // for the users not belonging to any group
959
      for (int j=0; j < users.length; j++ ) {
960
        if ( !usersIn.contains(users[j][0]) ) {
1005
      for (int j = 0; j < users.length; j++) {
1006
        if (!usersIn.contains(users[j][0])) {
961 1007
          out.append("    <user>\n");
962 1008
          out.append("      <username>" + users[j][0] + "</username>\n");
963 1009
          out.append("      <name>" + users[j][1] + "</name>\n");
......
968 1014
      }
969 1015

  
970 1016
      out.append("  </authSystem>\n");
971
      if ( !usersIn.isEmpty() ) {
1017
      if (!usersIn.isEmpty()) {
972 1018
        usersIn.removeAllElements();
973 1019
        usersIn.trimToSize();
974 1020
      }
......
978 1024
    return out.toString();
979 1025
  }
980 1026

  
981

  
982 1027
  /**
983 1028
   * Method for getting index of user DN in User info array
984 1029
   */
985
  int searchUser(String user, String userGroup[][]){
986
    for (int j=0; j < userGroup.length; j++ ) {
987
      if (user.compareTo(userGroup[j][0]) == 0){
1030
  int searchUser(String user, String userGroup[][]) {
1031
    for (int j = 0; j < userGroup.length; j++) {
1032
      if (user.compareTo(userGroup[j][0]) == 0) {
988 1033
        return j;
989 1034
      }
990 1035
    }
......
1009 1054
      MetaCatUtil.debugMessage("Authenticating...", 20);
1010 1055
      isValid = authservice.authenticate(user, password);
1011 1056
      if (isValid) {
1012
        MetaCatUtil.debugMessage("Authentication successful for: " + user, 20 );
1013
      } else {
1057
        MetaCatUtil.debugMessage("Authentication successful for: " + user, 20);
1058
      }
1059
      else {
1014 1060
        MetaCatUtil.debugMessage("Authentication failed for: " + user, 20);
1015 1061
      }
1016 1062

  
......
1019 1065
        MetaCatUtil.debugMessage("\nGetting attributes for user....", 20);
1020 1066
        HashMap userInfo = authservice.getAttributes(user, password, user);
1021 1067
        // Print all of the attributes
1022
        Iterator attList = (Iterator)(((Set)userInfo.keySet()).iterator());
1068
        Iterator attList = (Iterator) ( ( (Set) userInfo.keySet()).iterator());
1023 1069
        while (attList.hasNext()) {
1024
          String att = (String)attList.next();
1025
          Vector values = (Vector)userInfo.get(att);
1070
          String att = (String) attList.next();
1071
          Vector values = (Vector) userInfo.get(att);
1026 1072
          Iterator attvalues = values.iterator();
1027 1073
          while (attvalues.hasNext()) {
1028
            String value = (String)attvalues.next();
1074
            String value = (String) attvalues.next();
1029 1075
            MetaCatUtil.debugMessage(att + ": " + value, 20);
1030 1076
          }
1031 1077
        }
......
1036 1082
        MetaCatUtil.debugMessage("\nGetting all groups....", 20);
1037 1083
        String[][] groups = authservice.getGroups(user, password);
1038 1084
        MetaCatUtil.debugMessage("Groups found: " + groups.length, 20);
1039
        for (int i=0; i < groups.length; i++) {
1040
            MetaCatUtil.debugMessage("Group " + i + ": " + groups[i][0], 20);
1085
        for (int i = 0; i < groups.length; i++) {
1086
          MetaCatUtil.debugMessage("Group " + i + ": " + groups[i][0], 20);
1041 1087
        }
1042 1088
      }
1043 1089

  
......
1047 1093
        MetaCatUtil.debugMessage("\nGetting groups for user....", 20);
1048 1094
        String[][] groups = authservice.getGroups(user, password, user);
1049 1095
        MetaCatUtil.debugMessage("Groups found: " + groups.length, 20);
1050
        for (int i=0; i < groups.length; i++) {
1051
            MetaCatUtil.debugMessage("Group " + i + ": " + groups[i][0], 20);
1052
            savedGroup = groups[i][0];
1096
        for (int i = 0; i < groups.length; i++) {
1097
          MetaCatUtil.debugMessage("Group " + i + ": " + groups[i][0], 20);
1098
          savedGroup = groups[i][0];
1053 1099
        }
1054 1100
      }
1055 1101

  
......
1059 1105
        MetaCatUtil.debugMessage("Group: " + savedGroup, 20);
1060 1106
        String[] users = authservice.getUsers(user, password, savedGroup);
1061 1107
        MetaCatUtil.debugMessage("Users found: " + users.length, 20);
1062
        for (int i=0; i < users.length; i++) {
1063
            MetaCatUtil.debugMessage("User " + i + ": " + users[i], 20);
1108
        for (int i = 0; i < users.length; i++) {
1109
          MetaCatUtil.debugMessage("User " + i + ": " + users[i], 20);
1064 1110
        }
1065 1111
      }
1066 1112

  
......
1087 1133
        MetaCatUtil.debugMessage("\nFinished getting principals.", 20);
1088 1134
      }
1089 1135

  
1090
    } catch (ConnectException ce) {
1136
    }
1137
    catch (ConnectException ce) {
1091 1138
      MetaCatUtil.debugMessage(ce.getMessage(), 30);
1092
    } catch (java.io.IOException ioe) {
1139
    }
1140
    catch (java.io.IOException ioe) {
1093 1141
      MetaCatUtil.debugMessage("I/O Error writing to file principals.txt", 20);
1094 1142
    }
1095 1143
  }
......
1098 1146
   * This method will be called by start a thread.
1099 1147
   * It can handle if a referral exception happend.
1100 1148
   */
1101
  public void run()
1102
  {
1149
  public void run() {
1103 1150
    referralContext = null;
1104
    DirContext refDirContext=null;
1105
    boolean moreReferrals=true;
1106
    String referralInfo=null;
1151
    DirContext refDirContext = null;
1152
    boolean moreReferrals = true;
1153
    String referralInfo = null;
1107 1154
    //set a while loop is because we don't know if a referral excption contains
1108 1155
    //another referral exception
1109
    while (moreReferrals)
1110
    {
1111
      try
1112
      {
1156
    while (moreReferrals) {
1157
      try {
1113 1158
        //revise environment variable
1114
        referralInfo=(String)refExc.getReferralInfo();
1159
        referralInfo = (String) refExc.getReferralInfo();
1115 1160
        util.debugMessage("Processing referral (pr0): ", 35);
1116 1161
        util.debugMessage("PROVIDER_URL set to (pr1): " + referralInfo, 35);
1117 1162
        //env.put(Context.PROVIDER_URL,referralInfo);
......
1123 1168
        //util.debugMessage("Processing referral (pr2)",35);
1124 1169
        //rContext = refExc.getReferralContext(env);
1125 1170
        rContext = refExc.getReferralContext();
1126
        util.debugMessage("Processing referral (pr3)",35);
1171
        util.debugMessage("Processing referral (pr3)", 35);
1127 1172
        //casting the context to dircontext and it will create a
1128 1173
        //autherntication or naming exception if DN and password is incorrect
1129
        referralContext=rContext;
1130
        refDirContext=(DirContext)rContext;
1174
        referralContext = rContext;
1175
        refDirContext = (DirContext) rContext;
1131 1176
        refDirContext.close();
1132 1177
        //get context and jump out the while loop
1133
        moreReferrals=false;
1134
        util.debugMessage("Processing referral (pr4)",35);
1135
      }//try
1178
        moreReferrals = false;
1179
        util.debugMessage("Processing referral (pr4)", 35);
1180
      } //try
1136 1181
      //if referral have another referral excption
1137
      catch (ReferralException re)
1138
      {
1139
        util.debugMessage("GOT referral exception (re1): " + re.getMessage(),35);
1140
        util.debugMessage("RE details (re2): " + re.toString(true),35);
1182
      catch (ReferralException re) {
1183
        util.debugMessage("GOT referral exception (re1): " + re.getMessage(),
1184
                          35);
1185
        util.debugMessage("RE details (re2): " + re.toString(true), 35);
1141 1186
        //keep running in while loop
1142
        moreReferrals=true;
1187
        moreReferrals = true;
1143 1188
        //assign refExc to new referral exception re
1144
        refExc=re;
1189
        refExc = re;
1145 1190
      }
1146 1191
      //catch a authentication exception
1147
      catch (AuthenticationException ae)
1148
      {
1192
      catch (AuthenticationException ae) {
1149 1193
        util.debugMessage("Error running referral handler thread (ae1): " +
1150 1194
                          ae.getMessage(), 20);
1151 1195
        //check if has another referral
1152
        moreReferrals=refExc.skipReferral();
1196
        moreReferrals = refExc.skipReferral();
1153 1197
        //don't get the context
1154 1198
        referralContext = null;
1155 1199
      }
1156 1200
      //catch a naming exception
1157
      catch (NamingException ne)
1158
      {
1201
      catch (NamingException ne) {
1159 1202
        util.debugMessage("Error running referral handler thread (ne1): " +
1160 1203
                          ne.getMessage(), 20);
1161 1204
        //check if has another referral
1162
        moreReferrals=refExc.skipReferral();
1205
        moreReferrals = refExc.skipReferral();
1163 1206
        //don't get context
1164 1207
        referralContext = null;
1165 1208
      }
1166
    }//while
1167
  }//run()
1209
    } //while
1210
  } //run()
1168 1211

  
1169
  private class GetGroup implements Runnable
1170
  {
1171
    public void run()
1172
    {
1212
  private class GetGroup
1213
      implements Runnable {
1214
    public void run() {
1173 1215
      referralContext = null;
1174 1216
      MetaCatUtil.debugMessage("getting groups context", 50);
1175
      DirContext refDirContext=null;
1176
      boolean moreReferrals=true;
1217
      DirContext refDirContext = null;
1218
      boolean moreReferrals = true;
1177 1219
      //set a while loop is because we don't know if a referral excption
1178 1220
      //contains another referral exception
1179
      while (moreReferrals)
1180
      {
1181
        try
1182
        {
1221
      while (moreReferrals) {
1222
        try {
1183 1223
          //revise environment variable
1184 1224
          String refInfo = null;
1185
          refInfo = (String)refExc.getReferralInfo();
1186
          if(refInfo != null)
1187
          {
1225
          refInfo = (String) refExc.getReferralInfo();
1226
          if (refInfo != null) {
1188 1227
            MetaCatUtil.debugMessage("Referral in thread to: " +
1189
                              refInfo.toString(), 40);
1228
                                     refInfo.toString(), 40);
1190 1229
          }
1191
          else
1192
          {
1230
          else {
1193 1231
            MetaCatUtil.debugMessage("getting refInfo Manually", 50);
1194
            refInfo = (String)refExc.getReferralContext().getEnvironment().
1195
                                                  get(Context.PROVIDER_URL);
1232
            refInfo = (String) refExc.getReferralContext().getEnvironment().
1233
                get(Context.PROVIDER_URL);
1196 1234
          }
1197 1235
          MetaCatUtil.debugMessage("refInfo: " + refInfo, 40);
1198 1236

  
1199 1237
          env.put(Context.INITIAL_CONTEXT_FACTORY,
1200
              "com.sun.jndi.ldap.LdapCtxFactory");
1238
                  "com.sun.jndi.ldap.LdapCtxFactory");
1201 1239
          env.put(Context.REFERRAL, "throw");
1202 1240
          env.put(Context.PROVIDER_URL, refInfo);
1203 1241

  
......
1205 1243
          referralContext = new InitialDirContext(env);
1206 1244
          MetaCatUtil.debugMessage("referralContext created", 40);
1207 1245
          //get context and jump out the while loop
1208
          moreReferrals=false;
1209
        }//try
1210
        catch (ReferralException re)
1211
        {
1246
          moreReferrals = false;
1247
        } //try
1248
        catch (ReferralException re) {
1212 1249
          //keep running in while loop
1213
          moreReferrals=true;
1250
          moreReferrals = true;
1214 1251
          //assign refExc to new referral exception re
1215
          refExc=re;
1252
          refExc = re;
1216 1253
        }
1217
        catch (AuthenticationException ae)
1218
        {
1254
        catch (AuthenticationException ae) {
1219 1255
          util.debugMessage("Error running referral handler thread (ae2): " +
1220
                          ae.getMessage(), 50);
1256
                            ae.getMessage(), 50);
1221 1257
          //check if has another referral
1222
          moreReferrals=refExc.skipReferral();
1258
          moreReferrals = refExc.skipReferral();
1223 1259
          //don't get the context
1224 1260
          referralContext = null;
1225 1261
        }
1226
        catch (NamingException ne)
1227
        {
1262
        catch (NamingException ne) {
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff