KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > ca > commons > naming > CBOpenConWin


1 package com.ca.commons.naming;
2
3 import java.awt.Color JavaDoc;
4 import java.awt.Frame JavaDoc;
5 import java.awt.event.ActionEvent JavaDoc;
6 import java.awt.event.ActionListener JavaDoc;
7 import java.net.URISyntaxException JavaDoc;
8 import java.util.logging.Logger JavaDoc;
9
10
11 import javax.swing.JLabel JavaDoc;
12 import javax.swing.JPasswordField JavaDoc;
13 import javax.swing.JTextField JavaDoc;
14 import javax.swing.border.TitledBorder JavaDoc;
15
16 import com.ca.commons.jndi.ConnectionData;
17 import com.ca.commons.cbutil.*;
18
19 /**
20  * CBOpenConWin displays connection info to the user, allowing them
21  * to open a connection to an ldap server.
22  */

23
24
25 // Programming note: this class is a bit of an interloper; but it requires classes from both com.ca.commons.cbutil and
26
// com.ca.commons.jndi, so it get stuck in naming...
27

28 public abstract class CBOpenConWin extends CBDialog
29 {
30     /**
31      * stores the users connection data for passing to the 'connect()' method.
32      */

33
34     protected ConnectionData newCon; //ConnectionData newCon;
35

36     protected JTextField JavaDoc hostName, port, baseDN, managerDN;
37     protected CBJComboBox version, level;
38     //protected JCheckBox useSSL; // whether to use SSL
39
protected JPasswordField JavaDoc password;
40     protected JLabel JavaDoc hostLabel, portLabel, userMessage;
41     protected CBSaveLoadTemplate myTemplater;
42
43     static int threadID = 1; // naming variable for thread debugging
44
static final boolean DEBUGTHREADS = false;
45
46     // Security Levels ...
47
static final int NONE = 0;
48     static final int USER_AUTH = 1;
49     static final int SSL_NO_AUTH = 2;
50     static final int SSL_USER_AUTH = 3;
51     static final int SASL = 4;
52     static final int GSSAPI = 5; // Vadim: GSSAPI
53

54     // Protocols + Version strings for combo selection box
55
protected static final String JavaDoc LDAPV2 = CBIntText.get("LDAP v2");
56     protected static final String JavaDoc LDAPV3 = CBIntText.get("LDAP v3");
57
58
59     protected SecurityActionListener securityListener;
60
61     private final static Logger JavaDoc log = Logger.getLogger(CBOpenConWin.class.getName());
62
63
64     /**
65      * <p>CBOpenConWin allows the user to open an ldap connection. The jndiBroker
66      * that the connection is opened through is attached to a tree display, and
67      * a separate schema tree display. An attribute viewer is linked with the
68      * main tree display. A JLabel allows the connection window to communicate
69      * status to the user. These parameters are all obtained directly from the
70      * main JXplorer object</p>
71      * <p/>
72      *
73      * @param owner the owning frame (used for look and feel propagation etc.)
74      * @param statusDisplay a label used to give status feedback to the user.
75      * @param clientcerts the client certificate keystore (optional if 'simple ssl' is used).
76      * @param cacerts the trusted server certificate keystore (required for ssl)
77      * @param referral the jndi referral handling method ("follow" is default).
78      * @param aliasType the jndi alias handling - whether aliases are searched or not.
79      * (default is "searching");
80      * @deprecated use constructor that takes Help ID.
81      */

82
83     public CBOpenConWin(Frame JavaDoc owner, JLabel JavaDoc statusDisplay, String JavaDoc clientcerts, String JavaDoc cacerts,
84                         String JavaDoc referral, String JavaDoc aliasType)
85     {
86         this(owner, statusDisplay, clientcerts, cacerts, referral, aliasType, null);
87     }
88
89
90     /**
91      * <p>CBOpenConWin allows the user to open an ldap connection. The jndiBroker
92      * that the connection is opened through is attached to a tree display, and
93      * a separate schema tree display. An attribute viewer is linked with the
94      * main tree display. A JLabel allows the connection window to communicate
95      * status to the user. These parameters are all obtained directly from the
96      * main JXplorer object</p>
97      * <p/>
98      *
99      * @param owner the owning frame (used for look and feel propagation etc.)
100      * @param statusDisplay a label used to give status feedback to the user.
101      * @param clientcerts the client certificate keystore (optional if 'simple ssl' is used).
102      * @param cacerts the trusted server certificate keystore (required for ssl)
103      * @param referral the jndi referral handling method ("follow" is default).
104      * @param aliasType the jndi alias handling - whether aliases are searched or not.
105      * (default is "searching");
106      * @param helpID the help ID to attach to the Help button.
107      */

108     public CBOpenConWin(Frame JavaDoc owner, JLabel JavaDoc statusDisplay, String JavaDoc clientcerts, String JavaDoc cacerts,
109                         String JavaDoc referral, String JavaDoc aliasType, String JavaDoc helpID)
110     {
111         this(owner, statusDisplay, clientcerts, cacerts, helpID);
112
113         newCon.referralType = referral;
114         newCon.aliasType = aliasType;
115     }
116
117
118     /**
119      * <p>CBOpenConWin allows the user to open an ldap connection. The jndiBroker
120      * that the connection is opened through is attached to a tree display, and
121      * a separate schema tree display. An attribute viewer is linked with the
122      * main tree display. A JLabel allows the connection window to communicate
123      * status to the user. These parameters are all obtained directly from the
124      * main JXplorer object.</p>
125      * <p/>
126      * <p/>
127      * <p>This constructor allows for setting up ssl connections, by
128      * passing details of keystores through.</p>
129      *
130      * @param owner the owning frame (used for look and feel propagation etc.)
131      * @param statusDisplay a label used to give status feedback to the user.
132      * @param clientcerts the client certificate keystore (optional if 'simple ssl' is used).
133      * @param cacerts the trusted server certificate keystore (required for ssl)
134      * @deprecated use constructor that takes Help ID.
135      */

136
137     public CBOpenConWin(Frame JavaDoc owner, JLabel JavaDoc statusDisplay, String JavaDoc clientcerts, String JavaDoc cacerts)
138     {
139         this(owner, statusDisplay, clientcerts, cacerts, null);
140     }
141
142     /**
143      * <p>CBOpenConWin allows the user to open an ldap connection. The jndiBroker
144      * that the connection is opened through is attached to a tree display, and
145      * a separate schema tree display. An attribute viewer is linked with the
146      * main tree display. A JLabel allows the connection window to communicate
147      * status to the user. These parameters are all obtained directly from the
148      * main JXplorer object.</p>
149      * <p/>
150      * <p/>
151      * <p>This constructor allows for setting up ssl connections, by
152      * passing details of keystores through.</p>
153      *
154      * @param owner the owning frame (used for look and feel propagation etc.)
155      * @param statusDisplay a label used to give status feedback to the user.
156      * @param clientcerts the client certificate keystore (optional if 'simple ssl' is used).
157      * @param cacerts the trusted server certificate keystore (required for ssl)
158      * @param helpID the help ID to attach to the Help button.
159      */

160     public CBOpenConWin(Frame JavaDoc owner, JLabel JavaDoc statusDisplay, String JavaDoc clientcerts, String JavaDoc cacerts, String JavaDoc helpID)
161     {
162         super(owner, CBIntText.get("Open LDAP connection"), helpID); // create modal dialog ...
163

164         newCon = new ConnectionData();//ConnectionData();
165

166         newCon.clientcerts = clientcerts;
167         newCon.cacerts = cacerts;
168
169         initGUI(statusDisplay);
170     }
171
172     protected void initGUI(JLabel JavaDoc statusDisplay)
173     {
174         String JavaDoc oldConnection = "";
175         int oldPortNo = 19389;
176         String JavaDoc oldBaseDN = "";
177         //String oldUseSSL = CBIntText.get("false");
178

179         userMessage = statusDisplay;
180
181
182         /**
183          * Host / port and ldap version details
184          */

185
186         display.makeHeavy();
187         JLabel JavaDoc temp;
188         display.add(hostLabel = new JLabel JavaDoc(" " + CBIntText.get("Host") + ": "));
189         display.addWide(hostName = new JTextField JavaDoc(oldConnection, 30), 2);
190         hostLabel.setToolTipText(CBIntText.get("The url of the server; e.g. ") + "'www.cai.com'");
191
192         display.add(portLabel = new JLabel JavaDoc(" " + CBIntText.get("Port") + ": "));
193         display.addLine(port = new JTextField JavaDoc(String.valueOf(oldPortNo), 5));
194         portLabel.setToolTipText(CBIntText.get("The port number of the LDAP server; often 389."));
195
196         display.add(temp = new JLabel JavaDoc(" " + CBIntText.get("Protocol") + (": ")));
197         display.add(version = new CBJComboBox(new String JavaDoc[]{LDAPV2, LDAPV3}));
198         version.setSelectedIndex(1);
199         temp.setToolTipText(CBIntText.get("For all but the oldest servers, this should be 'Ldap v3'."));
200         version.setToolTipText(CBIntText.get("For all but the oldest servers, this should be 'Ldap v3'."));
201
202         display.addLine(new JLabel JavaDoc("")); // padding
203

204         display.newLine(); //TE: hack to add space for an extra component to be added in...ie. the DSML URL field...DO NOT REMOVE (see addExtraComponent).
205

206         /**
207          * Optional Panel for base DN.
208          */

209
210         CBPanel inset = new CBPanel();
211         inset.setBorder(new TitledBorder JavaDoc(CBIntText.get("Optional Values")));
212
213         inset.add(temp = new JLabel JavaDoc(CBIntText.get("Base DN") + ": "));
214         temp.setToolTipText(CBIntText.get("The base to start browsing from; e.g. ") + "'o=Democorp,c=au'");
215         inset.makeWide();
216         inset.addln(baseDN = new JTextField JavaDoc(String.valueOf(oldBaseDN), 30));
217
218
219         display.addLines(inset, 1);
220
221
222         /*
223          * Security Panel for anonymous vs user/password vs SASL
224          */

225
226         CBPanel ssl = new CBPanel();
227
228         String JavaDoc[] securityOptions = {
229             CBIntText.get("Anonymous"),
230             CBIntText.get("User + Password"),
231             CBIntText.get("SSL + Anonymous"),
232             CBIntText.get("SSL + User + Password"),
233             CBIntText.get("SSL + SASL + Keystore Password"),
234             CBIntText.get("GSSAPI") // Vadim: GSSAPI
235
};
236
237         ssl.setBorder(new TitledBorder JavaDoc(CBIntText.get("Security")));
238
239         ssl.makeLight();
240         ssl.add(temp = new JLabel JavaDoc(CBIntText.get("Level") + ":"));
241         temp.setToolTipText(CBIntText.get("The level of authentication."));
242
243         level = new CBJComboBox(securityOptions);
244         level.setToolTipText(CBIntText.get("Before using SSL, make sure you've set up your keystores in the 'Security' menu."));
245         ssl.addln(level);
246
247         ssl.add(temp = new JLabel JavaDoc(CBIntText.get("User DN") + ": "));
248         ssl.addln(managerDN = new JTextField JavaDoc(30));
249         temp.setToolTipText(CBIntText.get("To log on as an authenticated user, enter your user dn here."));
250
251         ssl.add(temp = new JLabel JavaDoc(CBIntText.get("Password") + ": "));
252         ssl.addLine(password = new JPasswordField JavaDoc(30));
253         temp.setToolTipText(CBIntText.get("Set your user password (or SASL keystore password) here."));
254
255         display.addLines(ssl, 3);
256
257         OK.setToolTipText(CBIntText.get("Click here to connect using current settings."));
258
259         /*
260          * ca.commons.cbutil.CBSaveLoadTemplate is a fairly cunning component (see)
261          * that allows the user to save and restore the state of edit fields in a dialog
262          */

263
264         display.addWide(myTemplater = new CBSaveLoadTemplate("connections.txt"), 5);
265
266         addExtraComponent(); //TE: allows the user to insert a component and not mess up the template handling.
267

268         display.newLine();
269
270         display.add(new JLabel JavaDoc("")); // padding
271

272         display.doLayout();
273
274         getContentPane().add(display);
275
276         doLayout();
277
278         myTemplater.loadDefault();
279
280         checkSecurityLevel();
281
282         /*
283          * Add a listener that checks the security level (and hence
284          * which fields are greyed out) everytime something changes
285          * which might affect stuff.
286          */

287
288         securityListener = new SecurityActionListener();
289         level.addActionListener(securityListener);
290         //TE: get the combo box that has the names of the templates to load and add an action listener to it...
291
(myTemplater.getLoadComboBox()).addActionListener(securityListener);
292     }
293
294
295     /**
296      * Use this method to insert an extra component. It is intended for
297      * adding the DSML label and field under protocol version. Hopefully
298      * there has been a space provided (via display.newLine()) in the
299      * initGUI method. So use something like
300      * display.add(urlLabel = new JLabel(" DSML: "), 0,2,1,1);
301      * display.addWide(dsmlService = new JTextField("", 30),4);
302      * in the overriding method.
303      * NOTE: the reason for not just sticking this method call after adding
304      * the protocol stuff is so that we don't stuff up the save/load template
305      * coordinates that users may have previously saved. I.e if we did it this
306      * way, the rest of the components that are added after the DSML stuff
307      * wont have the saved data loaded. Using display.newLine() acts as
308      * a place holder.
309      */

310
311     public void addExtraComponent()
312     {
313     }
314
315
316     /**
317      * Implements ActionListener to call the checkSecurityLevel method.
318      *
319      * @author Trudi.
320      */

321
322     class SecurityActionListener implements ActionListener JavaDoc
323     {
324
325         /**
326          * Calls the checkSecurityLevel method.
327          */

328
329         public void actionPerformed(ActionEvent JavaDoc event)
330         {
331             checkSecurityLevel();
332         }
333     }
334
335
336     /**
337      * this simply checks the state of the security level combo box,
338      * and grays out components accordingly.
339      */

340
341     protected int checkSecurityLevel()
342     {
343
344         int selected = level.getSelectedIndex();
345         switch (selected)
346         {
347             case 0: // anonymous
348

349                 setState(false, false);
350                 return NONE;
351
352             case 1: // user + password
353

354                 setState(true, true);
355                 return USER_AUTH;
356
357             case 2: // ssl + anonymous
358

359                 //XXX Big Dirty Hack - use password for non-JKS keystores...
360
/*
361                 String caKeystoreType = JXplorer.getProperty("keystoreType.cacerts", "JKS");
362                 if ("JKS".equals(caKeystoreType) == false)
363                     setState(false, true); // XXX HACK XXX
364                 else
365                 */

366                 
367                 setState(false, false);
368                 return SSL_NO_AUTH;
369
370             case 3: // ssl + user + password
371

372                 setState(true, true);
373                 return SSL_USER_AUTH;
374
375             case 4: // ssl + sasl + password
376

377                 setState(false, true);
378                 return SASL;
379
380             case 5: // Vadim: GSSAPI
381

382                 setState(false, false);
383                 return GSSAPI;
384         }
385
386         return NONE;
387     }
388
389     /**
390      * Small utility ftn to handle graying out components at the same time
391      * as disabling them. (real graphics toolkits do this for you...)
392      */

393
394     private void setState(boolean user, boolean pwd)
395     {
396         managerDN.setEnabled(user);
397         managerDN.setBackground(user ? Color.white : Color.lightGray);
398
399         if (pwd == false)
400             password.setText("");
401
402         password.setEnabled(pwd);
403         password.setBackground(pwd ? Color.white : Color.lightGray);
404     }
405
406
407     /**
408      * Set's title back to 'open ldap connection'/clears password
409      */

410
411     public void resetTitleAndPassword()
412     {
413         this.setTitle(CBIntText.get("Open LDAP Connection"));
414         password.setText("");
415     }
416
417     protected String JavaDoc getURL()
418             throws NumberFormatException JavaDoc, URISyntaxException JavaDoc
419     {
420         String JavaDoc host = null;
421         String JavaDoc portString = null;
422         if (hostName != null)
423             host = hostName.getText();
424         if (port != null)
425             portString = port.getText();
426
427         if (host != null) host = host.trim();
428         if (portString != null) portString = portString.trim();
429
430         if (host == null || host.length() < 1)
431         {
432             throw new URISyntaxException JavaDoc("", CBIntText.get("A host name must be entered for JXplorer to connect to."));
433         }
434
435         if (portString == null || portString.length() < 1)
436         {
437             throw new URISyntaxException JavaDoc("", CBIntText.get("A port number must be entered for JXplorer to connect to."));
438         }
439
440         int port = Integer.parseInt(portString); // may throw exception
441

442         if (port < 0) throw new NumberFormatException JavaDoc(CBIntText.get("Negative Port Number is illegal"));
443
444         if (port > 65536) throw new NumberFormatException JavaDoc(CBIntText.get("Port Number {0} is illegal", new String JavaDoc[] {portString}));
445
446         return "ldap://" + host + ":" + port;
447     }
448
449
450     /**
451      * Over-ride base class method that is called when the OK button is hit.
452      */

453
454     public void doOK()
455     {
456
457         try
458         {
459             log.fine("read values: " + hostName.getText() + ":" + port.getText());
460
461             /*
462              * Read Host and Port
463              */

464
465             String JavaDoc url = getURL(); // throws exceptions if URL is bad.
466

467             newCon.setURL(url);
468
469             userMessage.setText(CBIntText.get("Opening Connection To ") + url);
470
471             /*
472              * ldap version number
473              */

474
475             if (version.getSelectedItem() == LDAPV2)
476                 newCon.version = 2;
477             else // default for both ldap and dsml
478
newCon.version = 3;
479
480
481             /*
482              * Security Magic
483              */

484
485             int securityLevel = checkSecurityLevel();
486
487             newCon.userDN = null;
488             newCon.clearPasswords();
489
490             newCon.useGSSAPI = false;
491
492             if (securityLevel == USER_AUTH || securityLevel == SSL_USER_AUTH)
493             {
494                 newCon.userDN = managerDN.getText().trim();
495                 newCon.pwd = password.getPassword();
496                 if ((newCon.pwd.length) == 0)
497                 { //TE: make sure the user has entered a password.
498
throw new Exception JavaDoc(CBIntText.get("No Password Provided. Please enter a password."));
499                 }
500             }
501             else if (securityLevel == SASL)
502             {
503                 newCon.clientKeystorePwd = password.getPassword();
504                 if ((newCon.clientKeystorePwd.length) == 0)
505                 { //TE: make sure the user has entered a password.
506
throw new Exception JavaDoc(CBIntText.get("No Password Provided. Please enter a password."));
507                 }
508             }
509             //Vadim: GSSAPI
510
else if (securityLevel == GSSAPI)
511             {
512                 // username & password are only used if an existing kerberos keystore cannot be found;
513
// we'll prompt the user for them elsewhere if neccessary.
514

515                 newCon.useGSSAPI = true;
516             }
517
518             setVisible(false);
519
520             newCon.useSSL = (securityLevel >= SSL_NO_AUTH && securityLevel != GSSAPI);
521
522             newCon.baseDN = baseDN.getText();
523
524
525         }
526         catch (Exception JavaDoc err)
527         { // a bunch of things may throw exceptions; at this stage we haven't tried
528
// to contact the directory, so just reset defaults and carry on...
529

530             new CBErrorWin(this, "Error in data provided: " + err.getMessage(), err); // automatically visible one-shot.
531

532             //JOptionPane.showMessageDialog(this.getContentPane(),
533
// CBIntText.get("Error in data provided. (probably unable to parse " +
534
// " the port number, or password.) "),
535
// CBIntText.get("Couldn't Connect"), JOptionPane.ERROR_MESSAGE);
536
err.printStackTrace();
537
538             password.setText("");
539             setVisible(true);
540
541             this.setTitle(CBIntText.get("Couldn't Connect : Try Again"));
542             log.warning("User error in openconwin: " + err);
543             userMessage.setText(CBIntText.get("Error Opening Connection."));
544
545             return;
546         }
547
548         // DO THE ACTUAL WORK!
549
// Now the data has been read, send it off to the connect method to make the connection.
550

551         connect(newCon);
552
553     }
554
555     /**
556      * This method is called when the user connection data
557      * has been gathered and (roughly) checked.
558      *
559      * @param connectData the parsed connection data containing
560      * host and port details, security info, etc.
561      */

562
563     public abstract void connect(ConnectionData connectData);
564 }
Popular Tags