JXLoginPanel.java
上传用户:zhengdagz
上传日期:2014-03-06
资源大小:1956k
文件大小:16k
源码类别:

xml/soap/webservice

开发平台:

Java

  1. /*
  2.  * $Id: JXLoginPanel.java,v 1.3 2005/06/27 08:26:58 kleopatra Exp $
  3.  *
  4.  * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle,
  5.  * Santa Clara, California 95054, U.S.A. All rights reserved.
  6.  */
  7. package org.jdesktop.swingx;
  8. import java.awt.BorderLayout;
  9. import java.awt.Cursor;
  10. import java.awt.GridBagConstraints;
  11. import java.awt.GridBagLayout;
  12. import java.awt.Insets;
  13. import java.io.IOException;
  14. import java.util.Enumeration;
  15. import java.util.ResourceBundle;
  16. import javax.swing.ComboBoxModel;
  17. import javax.swing.JCheckBox;
  18. import javax.swing.JComboBox;
  19. import javax.swing.JLabel;
  20. import javax.swing.JPasswordField;
  21. import javax.swing.JTextField;
  22. import javax.swing.UIManager;
  23. import org.jdesktop.swingx.auth.*;
  24. /**
  25.  *  <p>JXLoginPanel is a JPanel that implements a Login dialog with
  26.  *  support for saving passwords supplied for future use in a secure
  27.  *  manner. It is intended to work with <strong>LoginService</strong>
  28.  *  and <strong>PasswordStore</strong> to implement the
  29.  *  authentication.</p>
  30.  *
  31.  *  <p> In order to perform the authentication, <strong>JXLoginPanel</strong>
  32.  *  calls the <code>authenticate</code> method of the <strong>LoginService
  33.  *  </strong>. In order to perform the persistence of the password,
  34.  *  <strong>JXLoginPanel</strong> calls the put method of the
  35.  *  <strong>PasswordStore</strong> object that is supplied. If
  36.  *  the <strong>PasswordStore</strong> is <code>null</code>, then the password
  37.  *  is not saved. Similarly, if a <strong>PasswordStore</strong> is
  38.  *  supplied and the password is null, then the <strong>PasswordStore</strong>
  39.  *  will be queried for the password using the <code>get</code> method.
  40.  *
  41.  * Changes by Shai:
  42.  * Clarified the save mode a little bit including hiding the save checkbox when there
  43.  * is no password store.
  44.  * Changed the class to derive from JXImagePanel to make customization easier (need to
  45.  * check my ImagePanel which has some technical advantages).
  46.  * Removed the static keyword from the ok/cancel buttons since this can cause an issue
  47.  * with more than one login dialogs (yes its an unlikely situation but documenting this
  48.  * sort of behavior or dealing with one bug resulting from this can be a real pain!).
  49.  * Allowed the name field to be represented as a text field when there is no password store.
  50.  * Rewrote the layout code to mostly work with a single container.
  51.  * Removed additional dialogs for progress and error messages and incorporated their 
  52.  * functionality into the main dialog.
  53.  * Allowed for an IOException with a message to be thrown by the login code. This message
  54.  * is displayed to the user when the login is stopped.
  55.  * Removed repetetive code and moved it to a static block.
  56.  * i18n converted some of the strings that were not localized.
  57.  *
  58.  * @author Bino George
  59.  * @author Shai Almog
  60.  * @author rbair
  61.  */
  62. public class JXLoginPanel extends JXImagePanel {
  63. /**
  64.  * Comment for <code>serialVersionUID</code>
  65.  */
  66. private static final long serialVersionUID = 3544949969896288564L;
  67.     /**
  68.      * The JXLoginPanel can attempt to save certain user information such as
  69.      * the username, password, or both to their respective stores.
  70.      * This type specifies what type of save should be performed.
  71.      */
  72.     public static enum SaveMode { NONE, USER_NAME, PASSWORD, BOTH};
  73.     /**
  74.      * Used as a prefix when pulling data out of UIManager for i18n
  75.      */
  76.     private static String CLASS_NAME;
  77.     /**
  78.      * This is the area in which the name field is placed. That way it can toggle on the fly 
  79.      * between text field and a combo box depending on the situation.
  80.      */
  81.     private JXPanel namePanel;
  82.     /**
  83.  * If a UserNameStore is used, then this combo box is presented allowing the user
  84.  * to select a previous login name, or type in a new login name
  85.  */
  86. private JComboBox nameCombo;
  87.     /**
  88.  * If a UserNameStore is not used, then this text field is presented allowing the user
  89.  * to simply enter their user name
  90.  */
  91. private JTextField nameField;
  92.     /**
  93.      * The password field presented allowing the user to enter their password
  94.      */
  95. private JPasswordField passwordField;
  96.     /**
  97.      * Check box presented if a PasswordStore is used, allowing the user to decide whether to
  98.      * save their password
  99.      */
  100. private JCheckBox saveCB;
  101.     /**
  102.      * The LoginService to use. This must be specified for the login dialog to operate.
  103.      * If no LoginService is defined, a default login service is used that simply
  104.      * allows all users access. This is useful for demos or prototypes where a proper login
  105.      * server is not available.
  106.      */
  107. private LoginService loginService;
  108.     /**
  109.      * Optional: a PasswordStore to use for storing and retrieving passwords for a specific
  110.      * user.
  111.      */
  112. private PasswordStore passwordStore;
  113.     /**
  114.  * Optional: a UserNameStore to use for storing user names and retrieving them
  115.  */
  116. private UserNameStore userNameStore;
  117. /**
  118.  *  Whether to save password or username or both
  119.  */
  120. private SaveMode saveMode;
  121.     /**
  122.      * Listens to save events
  123.      */
  124.     private SaveListener saveListener;
  125.     /**
  126.      * Tracks the cursor at the time that authentication was started, and restores to that
  127.      * cursor after authentication ends, or is cancelled;
  128.      */
  129.     private Cursor oldCursor;
  130.     
  131. /**
  132.  * Creates a default JXLoginPanel instance
  133.  */
  134. static {
  135. // Popuplate UIDefaults with the localizable Strings we will use
  136. // in the Login panel.
  137. CLASS_NAME = JXLoginPanel.class.getCanonicalName();
  138. String lookup;
  139.         ResourceBundle res = ResourceBundle.getBundle("org.jdesktop.swingx.auth.resources.resources");
  140.         Enumeration<String> keys = res.getKeys();
  141.         while (keys.hasMoreElements()) {
  142.             String key = keys.nextElement();
  143. lookup = CLASS_NAME + "." + key;
  144. if (UIManager.getString(lookup) == null) {
  145. UIManager.put(lookup, res.getString(key));
  146. }
  147.         }
  148. }
  149. public JXLoginPanel() {
  150.         this(null);
  151. }
  152.     
  153.     public JXLoginPanel(LoginService service) {
  154.         this(service, null, null);
  155.     }
  156.     
  157.     public JXLoginPanel(LoginService service, PasswordStore passwordStore, UserNameStore userStore) {
  158. this.loginService = service == null ? new NullLoginService() : service;
  159. this.passwordStore = passwordStore == null ? new NullPasswordStore() : passwordStore;
  160.         this.userNameStore = userStore == null ? new DefaultUserNameStore() : userStore;
  161.         
  162.         //initialize the save mode
  163.         if (passwordStore != null && userStore != null) {
  164.             saveMode = SaveMode.BOTH;
  165.         } else if (passwordStore != null) {
  166.             saveMode = SaveMode.PASSWORD;
  167.         } else if (userStore != null) {
  168.             saveMode = SaveMode.USER_NAME;
  169.         } else {
  170.             saveMode = SaveMode.NONE;
  171.         }
  172.         
  173.         saveListener = new SaveListener();
  174. this.loginService.addLoginListener(saveListener);
  175. setLayout(new BorderLayout());
  176. add(createLoginPanel(), BorderLayout.CENTER);
  177.     }
  178.     
  179. // if (username != null) {
  180. // userNameStore.addUsername(username);
  181. // }
  182.     
  183.     private JXPanel createNamePanel() {
  184.         JXPanel namePanel = new JXPanel(new BorderLayout());
  185.         nameField = new JTextField("", 15);
  186.         nameField.setEditable(true);
  187.         nameCombo = new JComboBox(new ComboBoxModel() {
  188.             private Object selectedItem;
  189.             public void setSelectedItem(Object anItem) {
  190.                 selectedItem = anItem;
  191.             }
  192.             public Object getSelectedItem() {
  193.                 return selectedItem;
  194.             }
  195.             public Object getElementAt(int index) {
  196.                 return userNameStore.getUserNames()[index];
  197.             }
  198.             public int getSize() {
  199.                 return userNameStore.getUserNames().length;
  200.             }
  201.             public void removeListDataListener(javax.swing.event.ListDataListener l) {
  202.                 //TODO
  203.             }
  204.             public void addListDataListener(javax.swing.event.ListDataListener l) {
  205.                 //TODO
  206.             }
  207.         });
  208.         nameCombo.setEditable(true);
  209.         if (saveMode == SaveMode.NONE) {
  210.             namePanel.add(nameField, BorderLayout.CENTER);
  211.         } else {
  212.             namePanel.add(nameCombo, BorderLayout.CENTER);
  213.         }
  214.         return namePanel;
  215.     }
  216.     
  217. private JXPanel createLoginPanel() {
  218.         JXPanel loginPanel = new JXPanel();
  219.         JLabel nameLabel = new JLabel(UIManager.getString(CLASS_NAME + ".nameString"));
  220.         namePanel = createNamePanel();
  221.         JLabel passwordLabel = new JLabel(UIManager.getString(CLASS_NAME + ".passwordString"));
  222. passwordField = new JPasswordField("", 15);
  223.         saveCB = new JCheckBox(UIManager.getString(CLASS_NAME + ".rememberPasswordString"));
  224.         saveCB.setVisible(saveMode == SaveMode.PASSWORD || saveMode == SaveMode.BOTH);
  225.         
  226.         loginPanel.setLayout(new GridBagLayout());
  227.         GridBagConstraints gridBagConstraints = new GridBagConstraints();
  228.         gridBagConstraints.gridx = 0;
  229.         gridBagConstraints.gridy = 0;
  230.         gridBagConstraints.anchor = GridBagConstraints.WEST;
  231.         gridBagConstraints.insets = new Insets(0, 0, 5, 11);
  232.         loginPanel.add(nameLabel, gridBagConstraints);
  233.         gridBagConstraints = new GridBagConstraints();
  234.         gridBagConstraints.gridx = 1;
  235.         gridBagConstraints.gridy = 0;
  236.         gridBagConstraints.gridwidth = 1;
  237.         gridBagConstraints.anchor = GridBagConstraints.WEST;
  238.         gridBagConstraints.fill = GridBagConstraints.HORIZONTAL;
  239.         gridBagConstraints.weightx = 1.0;
  240.         gridBagConstraints.insets = new Insets(0, 0, 5, 0);
  241.         loginPanel.add(namePanel, gridBagConstraints);
  242.         gridBagConstraints = new GridBagConstraints();
  243.         gridBagConstraints.gridx = 0;
  244.         gridBagConstraints.gridy = 1;
  245.         gridBagConstraints.anchor = GridBagConstraints.WEST;
  246.         gridBagConstraints.insets = new Insets(0, 0, 11, 11);
  247.         loginPanel.add(passwordLabel, gridBagConstraints);
  248.         gridBagConstraints = new GridBagConstraints();
  249.         gridBagConstraints.gridx = 1;
  250.         gridBagConstraints.gridy = 1;
  251.         gridBagConstraints.gridwidth = 1;
  252.         gridBagConstraints.anchor = GridBagConstraints.WEST;
  253.         gridBagConstraints.fill = GridBagConstraints.HORIZONTAL;
  254.         gridBagConstraints.weightx = 1.0;
  255.         gridBagConstraints.insets = new Insets(0, 0, 11, 0);
  256.         loginPanel.add(passwordField, gridBagConstraints);
  257.         gridBagConstraints = new GridBagConstraints();
  258.         gridBagConstraints.gridx = 0;
  259.         gridBagConstraints.gridy = 2;
  260.         gridBagConstraints.gridwidth = 2;
  261.         gridBagConstraints.fill = GridBagConstraints.HORIZONTAL;
  262.         gridBagConstraints.anchor = GridBagConstraints.WEST;
  263.         gridBagConstraints.weightx = 1.0;
  264.         gridBagConstraints.insets = new Insets(0, 0, 0, 0);
  265.         loginPanel.add(saveCB, gridBagConstraints);
  266.         return loginPanel;
  267.     }
  268.     
  269. /**
  270.  * Listener class to implement saving of passwords and usernames.
  271.  * 
  272.  * 
  273.  */
  274. class SaveListener implements LoginListener {
  275. public void loginFailed(LoginEvent source) {
  276. }
  277. public void loginSucceeded(LoginEvent source) {
  278. if (getSaveMode() == SaveMode.PASSWORD || getSaveMode() == SaveMode.BOTH) {
  279. savePassword();
  280. } else if (getSaveMode() == SaveMode.USER_NAME) {
  281. userNameStore.addUserName(nameField.getText());
  282. userNameStore.saveUserNames();
  283. }
  284. }
  285. public void loginStarted(LoginEvent source) {
  286. }
  287. public void loginCanceled(LoginEvent source) {
  288. }
  289. }
  290. void savePassword() {
  291. if (passwordStore != null) {
  292. passwordStore.set(getUserName(),getLoginService().getServer(),getPassword());
  293. }
  294. }
  295. /**
  296.  * @return Returns the saveMode.
  297.  */
  298. public SaveMode getSaveMode() {
  299. return saveMode;
  300. }
  301.     
  302.     /**
  303.      * The save mode indicates whether the "save" password is checked by default. This method
  304.      * makes no difference if the passwordStore is null.
  305.      *
  306.  * @param saveMode The saveMode to set either SAVE_NONE, SAVE_PASSWORD or SAVE_USERNAME
  307.  */
  308. public void setSaveMode(SaveMode saveMode) {
  309.         namePanel.removeAll();
  310. this.saveMode = saveMode;
  311.         switch (saveMode) {
  312.             case USER_NAME:
  313.             case PASSWORD:
  314.             case BOTH:
  315.                 namePanel.add(nameCombo, BorderLayout.CENTER);
  316.                 saveCB.setVisible(!(passwordStore instanceof NullPasswordStore));
  317.                 revalidate();
  318.                 break;
  319.             default:
  320.                 namePanel.add(nameField, BorderLayout.CENTER);
  321.                 saveCB.setSelected(false);
  322.                 saveCB.setVisible(false);
  323.                 revalidate();
  324.         }
  325. }
  326. /**
  327.  * Sets the <strong>LoginService</strong> for this panel.
  328.  *
  329.  * @param service service
  330.  */
  331. public void setLoginService(LoginService service) {
  332. loginService = service;
  333. }
  334. /**
  335.  * Gets the <strong>LoginService</strong> for this panel.
  336.  *
  337.  * @return service service
  338.  */
  339. public LoginService getLoginService() {
  340. return loginService;
  341. }
  342. /**
  343.  * Sets the <strong>PasswordStore</strong> for this panel.
  344.  *
  345.  * @param store PasswordStore
  346.  */
  347. public void setPasswordStore(PasswordStore store) {
  348. passwordStore = store;
  349. }
  350. /**
  351.  * Gets the <strong>PasswordStore</strong> for this panel.
  352.  *
  353.  * @return store PasswordStore
  354.  */
  355. public PasswordStore getPasswordStore() {
  356. return passwordStore;
  357. }
  358. /**
  359.  * Sets the <strong>User name</strong> for this panel.
  360.  *
  361.  * @param username User name
  362.  */
  363. public void setUserName(String username) {
  364.         if(saveMode == SaveMode.NONE) {
  365.             nameField.setText(username);
  366.         } else {
  367.             nameCombo.setSelectedItem(username);
  368.         }
  369. }
  370. /**
  371.  * Gets the <strong>User name</strong> for this panel.
  372.  * @return the user name
  373.  */
  374. public String getUserName() {
  375.         if(saveMode != SaveMode.NONE) {
  376.             return (String)nameCombo.getSelectedItem();
  377.         } else {
  378.             return nameField.getText();
  379.         }
  380. }
  381. /**
  382.  * Sets the <strong>Password</strong> for this panel.
  383.  *
  384.  * @param password Password
  385.  */
  386. public void setPassword(char[] password) {
  387. passwordField.setText(new String(password));
  388. }
  389. /**
  390.  * Gets the <strong>Password</strong> for this panel.
  391.  *
  392.  * @return password Password
  393.  */
  394. public char[] getPassword() {
  395. return passwordField.getPassword();
  396. }
  397.     /**
  398.      *
  399.      */
  400.     public void startLogin() {
  401.         oldCursor = getCursor();
  402.         try {
  403. //            loginPanel.progressIndicator.setIndeterminate(true);
  404. //            loginPanel.cancelLogin.setEnabled(true);
  405.             setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
  406.             String name = getUserName();
  407.             char[] password = getPassword();
  408.             loginService.startAuthentication(name, password, null);
  409.             if (saveMode != SaveMode.NONE && !userNameStore.containsUserName(name)) {
  410.                 userNameStore.addUserName(name);
  411.                 userNameStore.saveUserNames();
  412.             }
  413.             if (saveCB.isSelected() && (saveMode == SaveMode.BOTH || saveMode == SaveMode.PASSWORD)) {
  414.                 passwordStore.set(name, loginService.getServer(), password);
  415.             }
  416. //            UserPermissions.getInstance().setRoles(service.getUserRoles());
  417.         } catch(IOException ioerr) {
  418. //            loginPanel.loginProgress.setText(ioerr.getMessage());
  419. //            finishedLogin(false);
  420.         } finally {
  421.             setCursor(oldCursor);
  422.         }
  423.     }
  424.     
  425.     public void cancelLogin() {
  426.         loginService.cancelAuthentication();
  427.         setCursor(oldCursor);
  428.     }
  429.     
  430.     /**
  431.      * Simple login service that allows everybody to login. This is useful in demos and allows
  432.      * us to avoid having to check for LoginService being null
  433.      */
  434.     private static final class NullLoginService extends LoginService {
  435.         public boolean authenticate(String name, char[] password, String server) throws IOException {
  436.             return true;
  437.         }
  438.     }
  439.     
  440.     /**
  441.      * Simple PasswordStore that does not remember passwords
  442.      */
  443.     private static final class NullPasswordStore extends PasswordStore {
  444.         private static final char[] EMPTY = new char[0];
  445.         public boolean set(String username, String server, char[] password) {
  446.             //null op
  447.             return false;
  448.         }
  449.         public char[] get(String username, String server) {
  450.             return EMPTY;
  451.         }
  452.     }
  453. }