KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > lucane > client > ConnectBox


1 /*
2  * Lucane - a collaborative platform
3  * Copyright (C) 2002 Gautier Ringeisen <gautier_ringeisen@hotmail.com>
4  * Copyright (C) 2004 Vincent Fiack <vfiack@mail15.com>
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19  */

20 package org.lucane.client;
21
22 import org.lucane.client.util.*;
23 import org.lucane.client.widgets.*;
24 import org.lucane.common.*;
25 import org.lucane.common.crypto.KeyTool;
26 import org.lucane.common.crypto.MD5;
27 import org.lucane.common.net.ObjectConnection;
28
29 import java.awt.*;
30 import java.awt.event.*;
31 import java.util.*;
32 import javax.swing.*;
33 import javax.swing.border.EmptyBorder JavaDoc;
34
35 /**
36  * Connection Dialog
37  */

38 class ConnectBox
39 implements KeyListener, ActionListener, WindowListener
40 {
41     private JDialog dialog;
42     
43     private boolean isConnected;
44     
45     private JTextField tbName;
46     private JPasswordField tbPasswd;
47     private JButton btOk;
48     private JButton btCancel;
49     private JProgressBar pbStatus = null;
50     
51     /**
52      * Constructor
53      *
54      * @param serverName the server
55      * @param serverPort the server port
56      */

57     public ConnectBox(String JavaDoc serverName, int serverPort)
58     {
59         this.isConnected = false;
60     }
61     
62     private void initGui()
63     {
64         dialog = new JDialog((Frame)null, Translation.tr("connectBoxTitle"), true);
65         JPanel pnlMain = new JPanel(new BorderLayout());
66         
67         ImageIcon logo = Client.getImageIcon("login_logo.png");
68         
69         JLabel jLblLogo = new JLabel();
70         jLblLogo.setBackground(Color.WHITE);
71         jLblLogo.setIcon(logo);
72         
73         pnlMain.add(jLblLogo, BorderLayout.CENTER);
74         
75         FocusListener fl = new FocusListener() {
76             public void focusGained(FocusEvent fe) {
77                 JTextField jtf = (JTextField)fe.getComponent();
78                 jtf.setSelectionStart(0);
79                 jtf.setSelectionEnd(jtf.getText().length());
80             }
81             public void focusLost(FocusEvent fe) {}
82         };
83         
84         this.tbName = new JTextField();
85         tbName.addFocusListener(fl);
86         this.tbPasswd = new JPasswordField();
87         tbPasswd.addFocusListener(fl);
88         
89         this.btOk = new JButton(Translation.tr("connectBoxConnect"));
90         this.btCancel = new JButton(Translation.tr("connectBoxCancel"));
91         this.btOk.setIcon(Client.getImageIcon("ok.png"));
92         this.btCancel.setIcon(Client.getImageIcon("cancel.png"));
93         
94         this.pbStatus = new JProgressBar(0, 100);
95         this.pbStatus.setValue(0);
96         this.pbStatus.setFont(this.pbStatus.getFont().deriveFont(9f));
97         this.pbStatus.setString("");
98         this.pbStatus.setStringPainted(true);
99         
100         JPanel pnlInput = new JPanel(new GridLayout(2, 2, 2, 2));
101         pnlInput.add(new JLabel(Translation.tr("connectBoxLogin")));
102         pnlInput.add(tbName);
103         pnlInput.add(new JLabel(Translation.tr("connectBoxPasswd")));
104         pnlInput.add(tbPasswd);
105         
106         JPanel pnlButtons = new JPanel(new FlowLayout(FlowLayout.CENTER, 4, 2));
107         pnlButtons.add(btOk);
108         pnlButtons.add(btCancel);
109         
110         JPanel pnlLogin = new JPanel(new BorderLayout(4, 4));
111         pnlLogin.setBorder(new EmptyBorder JavaDoc(4, 4, 0, 4));
112         pnlLogin.add(pnlInput, BorderLayout.CENTER);
113         pnlLogin.add(pnlButtons, BorderLayout.SOUTH);
114         
115         pnlMain.add(pnlLogin, BorderLayout.SOUTH);
116         
117         dialog.addWindowListener(this);
118         
119         btOk.addActionListener(this);
120         btCancel.addActionListener(this);
121         btOk.addKeyListener(this);
122         btCancel.addKeyListener(this);
123         tbPasswd.addKeyListener(this);
124         tbName.addKeyListener(this);
125         
126         dialog.getContentPane().setLayout(new BorderLayout(4, 4));
127         dialog.getContentPane().add(pnlMain, BorderLayout.CENTER);
128         dialog.getContentPane().add(pbStatus, BorderLayout.SOUTH);
129         
130         dialog.pack();
131         dialog.setResizable(false);
132     }
133     
134     /**
135      * Show the modal dialog
136      *
137      * @param defaultLogin the login to display
138      * @param passwd if non null, autoconnect
139      */

140     public void showModalDialog(String JavaDoc defaultLogin)
141     {
142         initGui();
143         
144         //center dialog
145
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
146         dialog.setLocation((d.width-dialog.getWidth())/2, (d.height-dialog.getHeight())/2);
147         
148         tbName.setText(defaultLogin);
149         
150         dialog.show();
151     }
152     
153     /**
154      * Is the connection accepted ?
155      *
156      * @return true if the connection is accepted
157      */

158     public boolean connectionAccepted()
159     {
160         return isConnected;
161     }
162     
163     /**
164      * Set the value of the progressbar
165      *
166      * @param v the new value
167      * @param str the message
168      */

169     public void setProgressValue(int v, String JavaDoc str)
170     {
171         if(pbStatus == null)
172             return;
173         
174         pbStatus.setValue(v);
175         pbStatus.setString(str);
176     }
177     
178     /**
179      * Set the maximum value of the progressbar
180      *
181      * @param m the maximum value
182      */

183     public void setProgressMax(int m)
184     {
185         if(pbStatus == null)
186             return;
187         
188         pbStatus.setMaximum(m + 1);
189         pbStatus.setIndeterminate(false);
190         pbStatus.setValue(1);
191     }
192     
193     /**
194      * Close the box
195      */

196     public void closeDialog()
197     {
198         dialog.setVisible(false);
199         dialog.dispose();
200     }
201     
202     /**
203      * Key listener.
204      * Push the OK button
205      */

206     public void keyTyped(KeyEvent ev)
207     {
208         if (ev.getKeyChar() == KeyEvent.VK_ENTER)
209         {
210             if (ev.getSource() == btCancel)
211                 btCancel.doClick();
212             else
213                 btOk.doClick();
214         }
215     }
216     public void keyPressed(KeyEvent ev) {}
217     public void keyReleased(KeyEvent ev) {}
218     
219     /**
220      * Action Listener
221      */

222     public void actionPerformed(ActionEvent ev)
223     {
224         if ((JButton) ev.getSource() == btOk)
225         {
226             new Thread JavaDoc() {
227                 public void run() {
228                     tryToConnect(Client.getInstance(), tbName.getText(),
229                             new String JavaDoc(tbPasswd.getPassword()), true);
230                 }
231             }.start();
232         }
233         else if ((JButton) ev.getSource() == btCancel) {
234             closeDialog();
235             System.exit(0);
236         }
237     }
238     
239     /**
240      * Connect to the server and authenticate
241      */

242     protected void tryToConnect(Client parent, String JavaDoc user, String JavaDoc passwd, boolean gui)
243     {
244         String JavaDoc msg;
245         
246         if(gui)
247             pbStatus.setIndeterminate(true);
248
249         try
250         {
251             Logging.getLogger().info("Creating new communicator");
252             parent.createNewCommunicator();
253
254             if(Communicator.getInstance().useSSL())
255             {
256                 if(gui)
257                     pbStatus.setString(Translation.tr("msg.generatingKeyPair"));
258                 Logging.getLogger().info("Generating keypair");
259                 
260                 String JavaDoc privateKey = KeyTool.createPrivateStore(user, passwd);
261                 String JavaDoc publicKey = KeyTool.createPublicStore(privateKey, user);
262                 Client.getInstance().setKeys(privateKey, publicKey);
263                 
264                 if(gui)
265                     pbStatus.setString("");
266             }
267                 
268             Logging.getLogger().info("Creating new listener");
269             Listener lstnr = parent.createNewListener(user, passwd);
270             parent.setMyInfos(user, lstnr.getPort());
271
272             
273             Logging.getLogger().info("Request for connection");
274             msg = requestForConnection(parent, passwd);
275             
276             if (msg.startsWith("AUTH_ACCEPTED"))
277             {
278                 isConnected = true;
279                 Client.getInstance().init();
280                 if(gui)
281                     closeDialog();
282             }
283             else
284             {
285                 if(gui)
286                 {
287                     pbStatus.setIndeterminate(false);
288                     pbStatus.setValue(0);
289                     DialogBox.error(getErrorMsg(msg));
290                 }
291                 Logging.getLogger().severe(getErrorMsg(msg));
292             }
293         }
294         catch (Exception JavaDoc e)
295         {
296             if(gui)
297             {
298                 pbStatus.setIndeterminate(false);
299                 pbStatus.setValue(0);
300                 pbStatus.setString("");
301                 DialogBox.error(Translation.tr("connectBoxBadDataError"));
302             }
303             
304             Logging.getLogger().severe(Translation.tr("connectBoxBadDataError"));
305             e.printStackTrace();
306         }
307     }
308         
309     
310     private String JavaDoc requestForConnection(Client parent)
311     {
312         return this.requestForConnection(parent, new String JavaDoc(tbPasswd.getPassword()));
313     }
314     
315     
316     /**
317      * Ask the server to authenticate the client
318      *
319      * @return the server's answer
320      */

321     private String JavaDoc requestForConnection(Client parent, String JavaDoc passwd)
322     {
323         StringTokenizer stk;
324         String JavaDoc msg;
325         msg = "AUTH "
326             + MD5.encode(passwd);
327         
328         try
329         {
330             ConnectInfo serverInfos = new ConnectInfo("Server", parent.getConfig().getServerHost(),
331                     parent.getConfig().getServerPort(), "nokey", "Server");
332             Communicator.getInstance().setProxyInfo();
333             Logging.getLogger().finer("ConnectBox::requestForConnection(): CALL TO COMMUNICATOR");
334             
335             ObjectConnection oc = Communicator.getInstance().sendMessageTo(serverInfos, "Server", msg);
336             msg = oc.readString();
337             oc.close();
338             Logging.getLogger().finer("ConnectBox::requestForConnection(): MSG '" + msg + "'");
339             
340             if ((msg == null) || (msg.equals("")))
341                 msg = "BAD_MESSAGE";
342         }
343         catch (Exception JavaDoc ex)
344         {
345             Logging.getLogger().severe(ex.getMessage());
346             ex.printStackTrace();
347             msg = "NO_CONNECTION";
348         }
349         
350         return msg;
351     }
352     
353     /**
354      * Translate the server response to an understable message
355      *
356      * @param msg the server's message
357      * @return the userfriendly message
358      */

359     private String JavaDoc getErrorMsg(String JavaDoc msg)
360     {
361         if (msg.equals("BAD_MESSAGE"))
362             return Translation.tr("connectBoxBadMessage1") + "\n" + Translation.tr("connectBoxBadMessage2");
363         else if (msg.equals("NO_CONNECTION"))
364             return Translation.tr("connectBoxNoConnection1") + "\n" + Translation.tr("connectBoxNoConnection2");
365         else if (msg.equals("NOT_VALID_USER"))
366             return Translation.tr("connectBoxNotValidUser1") + "\n" + Translation.tr("connectBoxNotValidUser2");
367         else if (msg.equals("NOT_VALID_SERVER"))
368             return Translation.tr("connectBoxNotValidServer1") + "\n" + Translation.tr("connectBoxNotValidServer2");
369         else if (msg.equals("ACCESS_DENIED"))
370             return Translation.tr("connectBoxAccessDenied1") + "\n" + Translation.tr("connectBoxAccessDenied2");
371         else if (msg.equals("ALREADY_CONNECTED"))
372             return Translation.tr("connectBoxAlreadyConnected1") + "\n" + Translation.tr("connectBoxAlreadyConnected2");
373         else
374             return Translation.tr("connectBoxBadMessage1") + "\n" + Translation.tr("connectBoxBadMessage2");
375     }
376     
377     public void windowOpened(WindowEvent we) {}
378     public void windowClosed(WindowEvent we) {}
379     public void windowIconified(WindowEvent we) {}
380     public void windowDeiconified(WindowEvent we) {}
381     public void windowActivated(WindowEvent we) {}
382     public void windowDeactivated(WindowEvent we) {}
383     public void windowClosing(WindowEvent we)
384     {
385         closeDialog();
386         System.exit(0);
387     }
388 }
389
Popular Tags