KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > ca > directory > jxplorer > search > ReturnAttributesDialog


1 package com.ca.directory.jxplorer.search;
2
3 import java.awt.*;
4 import java.awt.event.*;
5 import java.util.*;
6 import java.util.logging.Logger JavaDoc;
7 import java.util.logging.Level JavaDoc;
8 import javax.swing.*;
9 import javax.naming.NamingException JavaDoc;
10 import java.io.*;
11
12 import com.ca.commons.cbutil.*;
13 import com.ca.directory.jxplorer.JXplorer;
14 import com.ca.directory.jxplorer.HelpIDs;
15 import com.ca.directory.jxplorer.broker.JNDIBroker;
16
17 /**
18 * This class acts as a item selector. It sets up a dialog that lets you select items
19 * from one list and add them to another list. It also allows you to remove selected
20 * items from the list.
21 */

22 public class ReturnAttributesDialog extends CBDialog
23 {
24     private static Logger JavaDoc log = Logger.getLogger(ReturnAttributesDialog.class.getName());
25
26     private JList availableList, selectedList;
27     private CBButton btnAdd, btnRemove, btnSave, btnLoad, btnDelete;
28     private JTextField nameField;
29     private JCheckBox includeDNCheckBox;
30     private ArrayList arrayList = new ArrayList();
31     private Properties properties;
32     private String JavaDoc localDir="";
33     private JXplorer jx;
34
35     /**
36      * Flag for save prompt.
37      */

38     private boolean hasSaved = false;
39
40     /**
41      * The property file which stores the return attributes list.
42      */

43     public static final String JavaDoc FILENAME = "return_attributes.txt";
44
45     /**
46      * Flag that indicates that the DN should be included in the results window.
47      */

48     public static final String JavaDoc INCLUDE_DN = "[DN]";
49
50     /**
51      * Used to indicate no return attributes.
52      */

53     public static final String JavaDoc DEFAULT_RETURN_ATTRS = "None";
54
55    /**
56     * Static method that should be used rather than creating an object directly if
57     * you wish to get the user input after the user has finished making selections and
58     * has closed the window.
59     * <p>
60     * This method creates a CBListSelector object and calls its 'show' method. When the
61     * user is finished with the dialog this method returns the user's selections.
62     * @param jx the parent frame (JXplorer).
63     * @return a list of user selections.
64     */

65     public static ArrayList getSelectedValues(JXplorer jx)
66     {
67         ReturnAttributesDialog listSelector = new ReturnAttributesDialog(jx);
68
69         listSelector.setVisible(true);
70
71         return listSelector.getSelectedValues();
72     }
73
74    /**
75     * Returns the names of all the saved return-attributes lists from the property file
76     * 'return_attributes.txt'.
77     * @param name the name of the return attribute list.
78     * @return an array containing all the names of the lists.
79     */

80     public static String JavaDoc[] getReturnAttributes(String JavaDoc name)
81     {
82         ArrayList list = new ArrayList(0);
83
84         Properties prop = getProperties();
85
86         if(prop == null)
87             return new String JavaDoc[] {"objectClass"}; // as a default, get the object class rather than nothing ("1.1")
88

89         String JavaDoc value = prop.getProperty(name);
90
91         if(value == null)
92             return new String JavaDoc[] {"objectClass"}; // as a default, get the object class rather than nothing ("1.1")
93

94         getReturnAttributes(value, list);
95
96         return (String JavaDoc[]) list.toArray(new String JavaDoc[list.size()]);
97     }
98
99    /**
100     * Returns the names of all the saved return-attributes lists from the property file
101     * 'return_attributes.txt'.
102     * @param value the list of return attributes.
103     * @param list a list of return attributes that are obtained from the value.
104     */

105     public static void getReturnAttributes(String JavaDoc value, ArrayList list)
106     {
107         if ((value.indexOf(";")>-1)==true)
108         {
109             list.add(value.substring(0, value.indexOf(";")));
110             getReturnAttributes(value.substring(value.indexOf(";")+1), list);
111         }
112     }
113
114    /**
115     * Returns the names of all the saved return-attributes lists from the property file
116     * 'return_attributes.txt'.
117     * @return an array containing all the names of the lists.
118     */

119     public static Object JavaDoc[] getSavedListNames()
120     {
121         Enumeration en = null;
122         ArrayList list = new ArrayList(0);
123
124         try
125         {
126             en = (getProperties()).propertyNames();
127         }
128         catch(Exception JavaDoc e)
129         {
130             list.add(DEFAULT_RETURN_ATTRS);
131             return list.toArray();
132         }
133
134         list.add(DEFAULT_RETURN_ATTRS);
135
136         while (en.hasMoreElements())
137         {
138             list.add(en.nextElement().toString());
139         }
140
141         return list.toArray();
142     }
143
144    /**
145     * Sets up the property file called 'return_attributes.txt' in the user dir.
146     */

147     public static Properties getProperties()
148     {
149         Properties myProperties = new Properties();
150
151         String JavaDoc temp = System.getProperty("user.dir") + File.separator;
152         if (temp==null) { log.warning("Unable to read user home directory."); return null;}
153
154         myProperties = CBUtility.readPropertyFile(temp + FILENAME);
155         if (myProperties.size()==0) { log.info("Initialising config file: " + temp + FILENAME); return null;}
156
157         return myProperties;
158     }
159
160    /**
161     * Sets up a dialog with two lists. The list on the left displays all available values
162     * that the user can select from. When the user selects a value it is displayed in the
163     * list on the right either by double clicking on the value or clicking the '>' button.
164     * The user can also remove a value from the selection list either by double clicking on
165     * it or clicking the '<' button.
166     * @param jx the parent frame (JXplorer).
167     */

168     public ReturnAttributesDialog(JXplorer jx)
169     {
170         super(jx, CBIntText.get("Return Attributes"), HelpIDs.SEARCH_RETURN_ATTRIBUTES);
171
172         this.jx = jx;
173         setUpPropertyFile();
174
175         CBPanel topPanel = new CBPanel();
176         CBPanel leftPanel = new CBPanel();
177         CBPanel middlePanel = new CBPanel();
178         CBPanel rightPanel = new CBPanel();
179         CBPanel bottomPanel = new CBPanel();
180
181         // Top panel...
182
topPanel.makeLight();
183         topPanel.add(new JLabel(CBIntText.get("Name: ")));
184         topPanel.makeWide();
185         topPanel.add(nameField = new JTextField(CBIntText.get("Untitled")));
186         topPanel.makeLight();
187         topPanel.add(btnSave = new CBButton(CBIntText.get("Save"),
188                 CBIntText.get("Save your selected return attributes for use in the Search dialog.")));
189         topPanel.add(btnLoad = new CBButton(CBIntText.get("Load"),
190                 CBIntText.get("Load an already saved list of return attributes.")));
191         topPanel.add(btnDelete = new CBButton(CBIntText.get("Delete"),
192                 CBIntText.get("Delete a already saved list of return attributes.")));
193
194         btnSave.setPreferredSize(new Dimension(62, 20));
195         btnSave.addActionListener(new ActionListener(){
196                 public void actionPerformed(ActionEvent e){
197                     save();
198                     hasSaved = true;
199         }});
200
201         btnLoad.setPreferredSize(new Dimension(62, 20));
202         btnLoad.addActionListener(new ActionListener(){
203                 public void actionPerformed(ActionEvent e){
204                     load();
205                     hasSaved = false;
206         }});
207
208         btnDelete.setPreferredSize(new Dimension(70, 20));
209         btnDelete.addActionListener(new ActionListener(){
210                 public void actionPerformed(ActionEvent e){
211                     delete();
212                     hasSaved = true;
213         }});
214
215         // Left panel...
216
leftPanel.addln(new JLabel(CBIntText.get("Available Attributes:")));
217         leftPanel.makeHeavy();
218
219         availableList = new JList(getAttributes());
220
221         // Only one item can be selected at anyone time...
222
availableList.setSelectionMode(0);
223
224         // Tries to ensure that the selected item is visible...
225
availableList.setSelectionModel(new CBSingleSelectionModel(availableList));
226
227         leftPanel.addln(new JScrollPane(availableList));
228
229         // Middle panel...
230
btnAdd = new CBButton(CBIntText.get(">"),
231                 CBIntText.get("Add an attribute from the attribute list on the left to the selection list on the right."));
232         btnAdd.addActionListener(new ActionListener(){
233                 public void actionPerformed(ActionEvent e){
234                     add();
235                     hasSaved = false;
236         }});
237
238         btnRemove = new CBButton(CBIntText.get("<"),
239                 CBIntText.get("Remove an attribute from the selection list on the right."));
240         btnRemove.addActionListener(new ActionListener(){
241                 public void actionPerformed(ActionEvent e){
242                     remove();
243                     hasSaved = false;
244         }});
245
246         middlePanel.makeHeavy();
247         middlePanel.addln(new JLabel(" "));
248         middlePanel.makeLight();
249         middlePanel.addln(btnAdd);
250         middlePanel.addln(btnRemove);
251         middlePanel.makeHeavy();
252         middlePanel.addln(new JLabel(" "));
253
254         // Right panel...
255
rightPanel.addln(new JLabel(CBIntText.get("Selected Attributes:")));
256         rightPanel.makeHeavy();
257
258         selectedList = new JList();
259
260         // Only one item can be selected at anyone time...
261
selectedList.setSelectionMode(0);
262
263         // Tries to ensure that the selected item is visible...
264
selectedList.setSelectionModel(new CBSingleSelectionModel(selectedList));
265
266         rightPanel.addln(new JScrollPane(selectedList));
267
268         // Bottom panel...
269
includeDNCheckBox = new JCheckBox(CBIntText.get("Include DN in search results."));
270         includeDNCheckBox.setToolTipText(
271                 CBIntText.get("Click the checkbox if you want the DN of each result displayed in the results window."));
272
273         bottomPanel.makeLight();
274         bottomPanel.add(includeDNCheckBox);
275         bottomPanel.makeHeavy();
276         bottomPanel.addln(new JLabel(" "));
277
278         // Main panel...
279
display.addln(new JLabel(" "));
280         display.makeWide();
281         display.addln(topPanel);
282         display.makeHeavy();
283         display.add(leftPanel);
284         display.makeLight();
285         display.add(middlePanel);
286         display.makeHeavy();
287         display.add(rightPanel);
288         display.newLine();
289         display.makeLight();
290         display.addln(bottomPanel);
291
292         setSize(400, 350);
293         CBUtility.center(this, owner);
294
295         registerMouseListeners();
296     }
297
298    /**
299     * Gets a list of attributes that are available in the schema which can be used for
300     * searching. These are used in the availableList part of the list.
301     * @return a string array of the available attributes to JX (null - if no schema publishing i.e. LDAP V2).
302     */

303     protected String JavaDoc[] getAttributes()
304     {
305         try
306         {
307             JNDIBroker searchBroker = jx.getSearchBroker();
308             ArrayList en = searchBroker.getSchemaOps().listEntryNames("schema=AttributeDefinition,cn=schema");
309
310             // Check for no schema publishing i.e. LDAP V2...
311
if(en==null)
312                 return null;
313
314             String JavaDoc[] temp = (String JavaDoc[]) en.toArray(new String JavaDoc[] {});
315             Arrays.sort(temp, new CBUtility.IgnoreCaseStringComparator());
316
317             return temp;
318         }
319         catch (NamingException JavaDoc e)
320         {
321             log.log(Level.WARNING, "Error accessing attribute defs in ReturnAttributesDialog ", e);
322             return null;
323         }
324     }
325
326    /**
327     * Sets up the property file called 'return_attributes.txt' in the user dir.
328     */

329     protected void setUpPropertyFile()
330     {
331         properties = new Properties();
332
333         String JavaDoc temp = System.getProperty("user.dir") + File.separator;
334         if (temp==null) { log.warning("Unable to read user home directory."); return;}
335         localDir = temp;
336
337         properties = CBUtility.readPropertyFile(temp + FILENAME);
338         if (properties.size()==0) { log.info("Initialising config file: " + temp + FILENAME); return;}
339     }
340
341    /**
342     * Adds a double click mouse listener to both lists in this dialog.
343     * If the double click occurs in the list on the left, the 'add' method is
344     * called. If the double click occurs in the list on the right, the
345     * remove method is called.
346     */

347     protected void registerMouseListeners()
348     {
349         availableList.addMouseListener(new MouseAdapter()
350         {
351             public void mouseClicked(MouseEvent e)
352             {
353                 if (e.getClickCount() == 2)
354                     add();
355                     hasSaved = false;
356             }
357         });
358
359         selectedList.addMouseListener(new MouseAdapter()
360         {
361             public void mouseClicked(MouseEvent e)
362             {
363                 if (e.getClickCount() == 2)
364                     remove();
365                     hasSaved = false;
366             }
367         });
368     }
369
370    /**
371     * Gets the selected item from the list on the left and adds it to
372     * the list on the right. It uses a global array list to keep track
373     * of the selections in the right hand list.
374     */

375     public void add()
376     {
377         try
378         {
379             if(!arrayList.contains(availableList.getSelectedValue()))
380                 arrayList.add(availableList.getSelectedValue());
381
382             selectedList.setListData(arrayList.toArray());
383         }
384         catch(Exception JavaDoc e)
385         {
386             log.warning("No selection to add.");
387         }
388     }
389
390    /**
391     * Removes the selected item from the list on the left. It uses a
392     * global array list to keep track of the selections in the right hand list.
393     */

394     public void remove()
395     {
396         try
397         {
398             arrayList.remove(selectedList.getSelectedIndex());
399             selectedList.setListData(arrayList.toArray());
400         }
401         catch(Exception JavaDoc e)
402         {
403             log.warning("No selection to remove.");
404         }
405     }
406
407    /**
408     * Saves a list to the property file called 'return_attributes.txt'. Saves the list
409     * by 'name=value', where 'value' is the list of attributes to return separated by a ';'.
410     * For example myList=attr1;attr2;attr3;
411     * <p>
412     * Before saving some quick checks are done...
413     * <br>attributes have been selected,
414     * <br>the name is valid (not null, not empty and not 'Untitled),
415     * <br>the name doesn't already exist.
416     */

417     public void save()
418     {
419         if(properties == null)
420             setUpPropertyFile();
421
422         ArrayList list = getSelectedValues();
423
424         // Any attributes selected?
425
if (list==null)
426         {
427             JOptionPane.showMessageDialog(this,
428                     CBIntText.get("Please select the return attributes that you want to save in your list"),
429                     CBIntText.get("Nothing to Save"), JOptionPane.INFORMATION_MESSAGE );
430             return;
431         }
432
433         String JavaDoc name = nameField.getText();
434
435         // Valid name?
436
if (name==null || name.trim().length() <= 0 || name.equalsIgnoreCase("Untitled"))
437         {
438             JOptionPane.showMessageDialog(this, CBIntText.get("Please enter a name for your list."),
439                     CBIntText.get("Name Not Supplied"), JOptionPane.INFORMATION_MESSAGE );
440             return;
441         }
442
443         // Name exists?
444
if (exists(name))
445         {
446             int response = JOptionPane.showConfirmDialog(this, CBIntText.get("Do you want to replace it?"),
447                     CBIntText.get("List Exists"), JOptionPane.OK_CANCEL_OPTION);
448
449             if (response != JOptionPane.OK_OPTION)
450                 return;
451         }
452
453         StringBuffer JavaDoc buffy = new StringBuffer JavaDoc(0);
454
455         // Check if user wants to include the DN in the search results, if so add to list...
456
if(includeDNCheckBox.isSelected())
457             buffy.append(INCLUDE_DN + ";");
458
459         for(int i=0; i<list.size();i++)
460             buffy.append(list.get(i)+";");
461
462         properties.setProperty(name, buffy.toString());
463         CBUtility.writePropertyFile(localDir + FILENAME, properties, "");
464
465         JOptionPane.showMessageDialog(this,
466                 CBIntText.get("Your return attributes list has been saved as ''{0}''.",new String JavaDoc[] {name}),
467                 CBIntText.get("Saved"), JOptionPane.INFORMATION_MESSAGE );
468
469         // Set the search GUI to null so that it is forced to re-read it's config and pick up new lists...
470
jx.getTree().setSearchGUI(null);
471         jx.getSearchTree().setSearchGUI(null);
472         jx.getSchemaTree().setSearchGUI(null);
473     }
474
475    /**
476     * Gets all the names of the saved list from the property file 'return_attributes.txt', then
477     * pops up a JOptionPane dialog that has a combo box displaying these names. Gets the user selection
478     * then retreves the value from the property file. Recall that in the property file the value is saved
479     * as a group of attribute names that are separated by a ';'. This method calls the 'getListAttrs' method
480     * that recursively extracts the attribute names. Once the names come back they are dropped into the
481     * selectedList (JList).
482     */

483     public void load()
484     {
485         Enumeration en = properties.propertyNames();
486
487         ArrayList list = new ArrayList(0);
488
489         while (en.hasMoreElements())
490         {
491             list.add((String JavaDoc)en.nextElement());
492         }
493
494         if (list.size()==0)
495         {
496             JOptionPane.showMessageDialog(this,
497                     CBIntText.get("There are no filters available to load."),
498                     CBIntText.get("Nothing to Load"), JOptionPane.INFORMATION_MESSAGE );
499             return;
500         }
501
502         Object JavaDoc listOb[] = list.toArray();
503
504         CBJComboBox loadCombo = new CBJComboBox(listOb);
505         loadCombo.setRenderer(new CBBasicComboBoxRenderer(listOb));
506         loadCombo.setPreferredSize(new Dimension(140, 20));
507         int response = JOptionPane.showConfirmDialog(this, loadCombo,
508                 CBIntText.get("Select List"), JOptionPane.OK_CANCEL_OPTION);
509
510         if (response != JOptionPane.OK_OPTION)
511             return;
512
513         // Default the check box to NOT checked...
514
includeDNCheckBox.setSelected(false);
515
516         String JavaDoc name = (loadCombo.getSelectedItem()).toString();
517         String JavaDoc loadList = getList(name);
518
519         nameField.setText(name);
520
521         // Get rid of the old attributes that are floating around...
522
arrayList.clear();
523         getListAttrs(loadList, arrayList);
524
525         selectedList.setListData(arrayList.toArray());
526     }
527
528    /**
529     * Recursively extracts the attributes from the saved return attributes list.
530     * @param loadList the list of file names separated by a ';'.
531     * @param list the list to store the file names in.
532     */

533     public void getListAttrs(String JavaDoc loadList, ArrayList list)
534     {
535         if (loadList.indexOf(";") > -1)
536         {
537             String JavaDoc temp = loadList.substring(0, loadList.indexOf(";"));
538
539             // Check if the attribute is the inlude DN flag, if it is just check the check box.
540
// Otherwise add the attribute to the list of selected attributes.
541
if(temp.equalsIgnoreCase(INCLUDE_DN))
542                 includeDNCheckBox.setSelected(true);
543             else
544                 list.add(temp);
545
546             // Move along to the next index and call this method again...
547
getListAttrs(loadList.substring(loadList.indexOf(";")+1), list);
548         }
549     }
550
551    /**
552     * Returns true if the property file (return_attributes.txt) contains the supplied
553     * key name.
554     * @param name the name of the list for example, 'myList'.
555     * @return true if the property file contains the list, false otherwise.
556     */

557     protected boolean exists(String JavaDoc name)
558     {
559         // Check if the list name already exists, if so return true...
560
if(properties.containsKey(name))
561             return true;
562
563         return false;
564     }
565
566    /**
567     * Returns the value from the property file of a given list name.
568     * @param name the key of the value that is being returned (e.g. 'myList').
569     * @return the value of the key i.e. the list.
570     */

571     public String JavaDoc getList(String JavaDoc name)
572     {
573         return properties.getProperty(name);
574     }
575
576    /**
577     * Checks if the name of the list that the user wants to delete is valid, calls the remove method
578     * then clears the text in the name field.
579     */

580     public void delete()
581     {
582         String JavaDoc toDelete = nameField.getText();
583
584         if (toDelete==null || toDelete.trim().length() <= 0 || toDelete.equalsIgnoreCase("Untitled"))
585         {
586             JOptionPane.showMessageDialog(this,
587                     CBIntText.get("Please enter the name of the list that you want to delete."),
588                     CBIntText.get("Nothing to Delete"), JOptionPane.INFORMATION_MESSAGE );
589             return;
590         }
591         else
592         {
593             int response = JOptionPane.showConfirmDialog(this,
594                     CBIntText.get("Are you sure you want to delete the list ''{0}''?", new String JavaDoc[] {toDelete}),
595                     CBIntText.get("Delete List?"), JOptionPane.OK_CANCEL_OPTION);
596
597             if (response != JOptionPane.OK_OPTION)
598                 return;
599         }
600
601         removeList(toDelete);
602
603         nameField.setText("");
604
605         // Get rid of the old attributes that are floating around...
606
arrayList.clear();
607         selectedList.setListData(arrayList.toArray());
608
609         // Default the check box to NOT checked...
610
includeDNCheckBox.setSelected(false);
611
612         // Set the search GUI to null so that it is forced to re-read it's config and pick up new lists...
613
jx.getTree().setSearchGUI(null);
614         jx.getSearchTree().setSearchGUI(null);
615         jx.getSchemaTree().setSearchGUI(null);
616     }
617
618    /**
619     * Removes a list from the properties file return_attributes.txt.
620     * @param name the list name (key) to be removed (deleted).
621     */

622     protected void removeList(String JavaDoc name)
623     {
624         if(!properties.containsKey(name))
625             return;
626
627         properties.remove(name);
628         CBUtility.writePropertyFile(localDir + FILENAME, properties, "");
629         removeFromSearch(name);
630     }
631
632    /**
633     * If a return attribute list is deleted check that the search file doesn't have
634     * a reference to it. If it does delete it.
635     * @param name the name of the return attribute list that is being deleted.
636     */

637     public void removeFromSearch(String JavaDoc name)
638     {
639         SearchModel sm = new SearchModel();
640         sm.removeRetAttrs(name);
641     }
642
643    /**
644     * Returns a list of the values that the user has selected.
645     * @return a list of the values that the user has selected.
646     */

647     public ArrayList getSelectedValues()
648     {
649         if(arrayList.isEmpty())
650             return null;
651         else
652             return arrayList;
653     }
654
655    /**
656     * Overrides the doOK of CBDialog so that a prompt is displayed before the user exits.
657     */

658     public void doOK()
659     {
660         if(!hasSaved)
661         {
662             int response = JOptionPane.showConfirmDialog(this, CBIntText.get("Exit without saving the return attributes list?"),
663                                                             CBIntText.get("Exit Without Saving"), JOptionPane.OK_CANCEL_OPTION);
664
665             if (response == JOptionPane.OK_OPTION)
666                 super.doOK();
667         }
668         else
669         {
670             super.doOK();
671         }
672     }
673 }
Popular Tags