1 38 44 45 import javax.mail.*; 46 import java.net.InetAddress ; 47 import java.awt.*; 48 import javax.swing.*; 49 50 57 58 public class SimpleAuthenticator extends Authenticator { 59 60 Frame frame; 61 String username; 62 String password; 63 64 public SimpleAuthenticator(Frame f) { 65 this.frame = f; 66 } 67 68 protected PasswordAuthentication getPasswordAuthentication() { 69 70 String prompt = getRequestingPrompt(); 72 if (prompt == null) 73 prompt = "Please login..."; 74 75 String protocol = getRequestingProtocol(); 77 if (protocol == null) 78 protocol = "Unknown protocol"; 79 80 String host = null; 82 InetAddress inet = getRequestingSite(); 83 if (inet != null) 84 host = inet.getHostName(); 85 if (host == null) 86 host = "Unknown host"; 87 88 String port = ""; 90 int portnum = getRequestingPort(); 91 if (portnum != -1) 92 port = ", port " + portnum + " "; 93 94 String info = "Connecting to " + protocol + " mail service on host " + 96 host + port; 97 98 JComponent d = new JComponent() { }; 103 104 GridBagLayout gb = new GridBagLayout(); 105 GridBagConstraints c = new GridBagConstraints(); 106 d.setLayout(gb); 107 c.insets = new Insets(2, 2, 2, 2); 108 109 c.anchor = GridBagConstraints.WEST; 110 c.gridwidth = GridBagConstraints.REMAINDER; 111 c.weightx = 0.0; 112 d.add(constrain(new JLabel(info), gb, c)); 113 d.add(constrain(new JLabel(prompt), gb, c)); 114 115 c.gridwidth = 1; 116 c.anchor = GridBagConstraints.EAST; 117 c.fill = GridBagConstraints.NONE; 118 c.weightx = 0.0; 119 d.add(constrain(new JLabel("Username:"), gb, c)); 120 121 c.anchor = GridBagConstraints.EAST; 122 c.fill = GridBagConstraints.HORIZONTAL; 123 c.gridwidth = GridBagConstraints.REMAINDER; 124 c.weightx = 1.0; 125 String user = getDefaultUserName(); 126 JTextField username = new JTextField(user, 20); 127 d.add(constrain(username, gb, c)); 128 129 c.gridwidth = 1; 130 c.fill = GridBagConstraints.NONE; 131 c.anchor = GridBagConstraints.EAST; 132 c.weightx = 0.0; 133 d.add(constrain(new JLabel("Password:"), gb, c)); 134 135 c.anchor = GridBagConstraints.EAST; 136 c.fill = GridBagConstraints.HORIZONTAL; 137 c.gridwidth = GridBagConstraints.REMAINDER; 138 c.weightx = 1.0; 139 JPasswordField password = new JPasswordField("", 20); 140 d.add(constrain(password, gb, c)); 141 if (user != null && user.length() > 0) 143 password.requestFocus(); 144 else 145 username.requestFocus(); 146 147 int result = JOptionPane.showConfirmDialog(frame, d, "Login", 148 JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); 149 150 if (result == JOptionPane.OK_OPTION) 151 return new PasswordAuthentication(username.getText(), 152 password.getText()); 153 else 154 return null; 155 } 156 157 private Component constrain(Component cmp, 158 GridBagLayout gb, GridBagConstraints c) { 159 gb.setConstraints(cmp, c); 160 return (cmp); 161 } 162 } 163 | Popular Tags |