KickJava   Java API By Example, From Geeks To Geeks.

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


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

19 package org.lucane.client;
20
21 import org.lucane.client.util.*;
22 import org.lucane.client.widgets.*;
23 import org.lucane.common.*;
24 import org.lucane.common.net.ObjectConnection;
25
26 import java.net.*;
27 import java.awt.Font JavaDoc;
28 import java.awt.Graphics JavaDoc;
29 import java.awt.image.BufferedImage JavaDoc;
30 import java.io.*;
31 import java.util.*;
32
33 import javax.swing.Icon JavaDoc;
34 import javax.swing.ImageIcon JavaDoc;
35 import javax.swing.JLabel JavaDoc;
36 import javax.swing.LookAndFeel JavaDoc;
37 import javax.swing.UIManager JavaDoc;
38 import javax.swing.plaf.IconUIResource JavaDoc;
39
40
41 /**
42  * The client main class.
43  * It's a singleton containing the different client parts :
44  * Listener, Communicator, PluginManager, ...
45  * It is used as a glue between the different components
46  */

47 public class Client
48 {
49     private static final String JavaDoc CONFIG_FILE = "etc/client-config.xml";
50     private static final String JavaDoc LOG_FILE = "logs/lucane.log";
51     public static final String JavaDoc APPLICATIONS_DIRECTORY = "applications/";
52     public static final String JavaDoc VERSION = "0.7.5";
53     
54     private ConnectInfo myinfos; //can be masked by the proxy
55
private ConnectInfo realinfos; //has the real infos
56
private ConnectInfo serverInfos;
57     
58     private String JavaDoc privateKey;
59     private String JavaDoc publicKey;
60     
61     private PluginManager pluginloader;
62     private Listener listener;
63     private Communicator communicator;
64     
65     private ConnectBox connectbox;
66     
67     private boolean isConnected;
68     
69     private ArrayList userListListeners;
70     private ArrayList users;
71
72     private ClientConfig config;
73     
74     //the current startup plugin
75
private String JavaDoc startupPlugin;
76     
77     //the window manager
78
private WindowManager windowManager;
79     
80     
81     private static Client instance = null;
82     
83     /**
84      * Client is a Singleton
85      *
86      * @return the unique client instance
87      */

88     public static Client getInstance()
89     {
90         if(instance == null)
91             instance = new Client();
92         
93         return instance;
94     }
95     
96     /**
97      * Creates a new client
98      */

99     private Client()
100     {
101         this.isConnected = false;
102         this.myinfos = null;
103         this.realinfos = null;
104         this.pluginloader = null;
105         this.listener = null;
106         this.communicator = null;
107         this.users = new ArrayList();
108         this.userListListeners = new ArrayList();
109         this.config = null;
110         
111         this.windowManager = new DefaultWindowManager();
112         
113         //create application directory structure
114
String JavaDoc appPath = System.getProperty("user.dir") + '/' + APPLICATIONS_DIRECTORY;
115         new File(appPath).mkdirs();
116     }
117     
118     /**
119      * Shows the connection box
120      *
121      * @param defaultLogin the default login
122      * @param passwd the password to use automatically or null
123      * @param serverName the server to use for the connection
124      * @param serverPort the server to use for the connection
125      */

126     protected void showConnectBox(String JavaDoc defaultLogin, String JavaDoc passwd, String JavaDoc serverName, int serverPort)
127     {
128         this.connectbox = new ConnectBox(serverName, serverPort);
129         if(passwd == null)
130             connectbox.showModalDialog(defaultLogin);
131         else
132             connectbox.tryToConnect(this, defaultLogin, passwd, false);
133     }
134     
135     /**
136      * Initialize the client and launch the startup plugin
137      */

138     protected void init()
139     {
140         //create localconfig structure
141
String JavaDoc configPath = System.getProperty("user.dir") + '/' + LocalConfig.CONFIG_DIRECTORY
142         + this.getMyInfos().getName();
143         new File(configPath).mkdirs();
144         
145         this.listener.listen();
146         this.pluginloader = PluginManager.getInstance();
147         this.communicator.updatePlugins();
148         
149         
150         this.serverInfos = new ConnectInfo("Server", config.getServerHost(),
151                 config.getServerPort(), "nokey", "Server");
152         
153         try
154         {
155             ObjectConnection oc = this.communicator.sendMessageTo(serverInfos, "Server",
156             "STARTUP_PLUGINS");
157             
158             this.startupPlugin = oc.readString();
159             oc.close();
160         }
161         catch(Exception JavaDoc e)
162         {
163             Logging.getLogger().warning(e.toString());
164         }
165     }
166     
167     protected void startMainPlugin()
168     {
169         if(this.pluginloader.isAvailable(startupPlugin))
170             this.pluginloader.run(startupPlugin, new ConnectInfo[0]);
171         else
172         {
173             DialogBox.error(startupPlugin + " : " + Translation.tr("clientUnknownPlugin"));
174             this.cleanExit();
175         }
176     }
177     
178     /**
179      * Creates a new Listener object
180      *
181      * @return the new listener
182      */

183     protected Listener createNewListener(String JavaDoc userName, String JavaDoc passwd)
184     {
185         if(this.listener != null)
186             this.listener.pleaseStop();
187         
188         this.listener = new Listener(privateKey, userName, passwd);
189         
190         return this.listener;
191     }
192     
193     /**
194      * Creates a new ConnectInfo object
195      *
196      * @param userName the user's login
197      * @param listenPort the listening port
198      */

199     protected void setMyInfos(String JavaDoc userName, int listenPort)
200     throws Exception JavaDoc
201     {
202         String JavaDoc publicKey = this.publicKey;
203         if(! Communicator.getInstance().useSSL())
204             publicKey = "nokey";
205         
206         try
207         {
208             if(config.getPublicIpAddress() != null)
209             {
210                 this.realinfos = new ConnectInfo(userName, config.getPublicIpAddress(),
211                         listenPort, publicKey, "client");
212             }
213             else if(config.getPublicIpInterface() != null)
214             {
215                 NetworkInterface ni = NetworkInterface.getByName(config.getPublicIpInterface());
216                 Enumeration e = ni.getInetAddresses();
217                 InetAddress addr = null;
218                 while(e.hasMoreElements())
219                 {
220                     addr = (InetAddress)e.nextElement();
221                     if(addr instanceof Inet4Address)
222                         break;
223                 }
224
225                 this.realinfos = new ConnectInfo(userName,
226                         addr.getHostAddress(),
227                         listenPort, publicKey, "client");
228             }
229             else
230             {
231                 this.realinfos = new ConnectInfo(userName,
232                         InetAddress.getLocalHost().getHostAddress(),
233                         listenPort, publicKey, "client");
234             }
235             
236             if(config.getProxyHost() != null)
237             {
238                 this.myinfos = new ConnectInfo(userName, config.getProxyHost(),
239                         config.getProxyPort(), publicKey, "client");
240             }
241             else
242                 this.myinfos = realinfos;
243         }
244         catch(UnknownHostException ex)
245         {
246             this.myinfos = new ConnectInfo("", "", 0, "nokey", "");
247         }
248     }
249     
250     /**
251      * Set private & public keys for SSL
252      *
253      * @param privateKey
254      * @param publicKey
255      */

256     protected void setKeys(String JavaDoc privateKey, String JavaDoc publicKey)
257     {
258         this.privateKey = privateKey;
259         this.publicKey = publicKey;
260     }
261     
262     /**
263      * Get the connection informations
264      *
265      * @return the connection informations
266      */

267     public ConnectInfo getMyInfos()
268     {
269         return getMyInfos(false);
270     }
271     
272     /**
273      * Get the connection information
274      *
275      * @param noproxy allows to get the real infos and bypass the proxy
276      * @return the connection informations
277      */

278     public ConnectInfo getMyInfos(boolean noproxy)
279     {
280         ConnectInfo my = noproxy ? this.realinfos : this.myinfos;
281         if(my != null)
282             return my;
283
284         return new ConnectInfo("", "", 0, "nokey", "client");
285     }
286     
287     /**
288      * Creates a new Communicator object
289      */

290     protected void createNewCommunicator()
291     {
292         this.communicator = new Communicator();
293     }
294     
295     /**
296      * Flags the client as connected
297      */

298     private void setConnected(boolean connected)
299     {
300         this.isConnected = connected;
301     }
302     
303     /**
304      * Disconnected by the server
305      */

306     protected void disconnect()
307     {
308         try {
309             DialogBox.info(Translation.tr("msg.disconnected"));
310         } catch(UnsatisfiedLinkError JavaDoc ule) {
311             //awt isn't available.
312
}
313         cleanExit();
314     }
315     
316     /**
317      * Quits the client properly
318      */

319     protected void cleanExit()
320     {
321         if(isConnected)
322         {
323             try {
324                 ObjectConnection oc = communicator.sendMessageTo(serverInfos, "Server",
325                         "CONNECT_DEL " + myinfos.getName());
326                 oc.close();
327             } catch(Exception JavaDoc e) {
328                 Logging.getLogger().warning("Can't send exit message to server");
329             }
330         }
331         Logging.getLogger().info("Exiting cleanly.");
332         Runtime.getRuntime().halt(0);
333     }
334     
335     /**
336      * Set the connected user list
337      *
338      * @param users the user list
339      */

340     protected void setUserList(ArrayList users)
341     {
342         this.users = users;
343         this.communicator.flushConnectInfosCache();
344         
345         Iterator i = this.userListListeners.iterator();
346         while(i.hasNext())
347             ((UserListListener)i.next()).userListChanged(users);
348     }
349     
350     /**
351      * Get the connect box
352      *
353      * @return the ConnectBox
354      */

355     protected ConnectBox getConnectBox()
356     {
357         return this.connectbox;
358     }
359     
360     /**
361      * Get the current window manager
362      */

363     public WindowManager getWindowManager()
364     {
365         return this.windowManager;
366     }
367     
368     /**
369      * Add a UserListListener. It will be notified at each
370      * change of the connected userlist
371      *
372      * @param ull the UserListListener
373      */

374     public void addUserListListener(UserListListener ull)
375     {
376         this.userListListeners.add(ull);
377     }
378     
379     /**
380      * Remove a UserListListener
381      *
382      * @param ull the UserListListener
383      */

384     public void removeUserListListener(UserListListener ull)
385     {
386         this.userListListeners.remove(ull);
387     }
388     
389     /**
390      * Get the connected users
391      *
392      * @return the user list
393      */

394     public List getUserList()
395     {
396         return users;
397     }
398     
399     /**
400      * Get the startup plugin for the current user
401      */

402     public String JavaDoc getStartupPlugin()
403     {
404         return this.startupPlugin;
405     }
406     
407     /**
408      * Change the flag startup plugin.
409      * You shouldn't use it. It's used by quicklaunch to set MainInterface
410      * if quicklaunch can't be started.
411      *
412      * @param pluginName the plugin name
413      */

414     public void setStartupPlugin(String JavaDoc pluginName)
415     {
416         this.startupPlugin = pluginName;
417     }
418     
419     /**
420      * Set configuration
421      *
422      * @param config the configuration
423      */

424     private void setConfig(ClientConfig config)
425     {
426         this.config = config;
427         Translation.setLocale(config.getLanguage());
428         
429         if(config.getFont() != null)
430         {
431             FontManager.setDefaultFont(new Font JavaDoc(config.getFont(), Font.PLAIN, 12));
432             Logging.getLogger().info("Using font : " + config.getFont());
433         }
434         
435         if(config.getProxyHost() != null)
436         {
437             Logging.getLogger().info("Using a proxy connection : " + config.getProxyHost()
438                     + ":" + config.getProxyPort());
439         }
440
441         if(config.getPublicIpAddress() != null)
442             Logging.getLogger().info("Forced use of the IP address : " + config.getPublicIpAddress());
443         else if(config.getPublicIpInterface() != null)
444             Logging.getLogger().info("Forced use of the network interface : " + config.getPublicIpInterface());
445     }
446     
447     /**
448      * Get the configuration
449      *
450      * @return the client configuration
451      */

452     public ClientConfig getConfig()
453     {
454         return this.config;
455     }
456     
457     /**
458      * Get an icon from its image name
459      *
460      * @param icon the image name
461      * @return an ImageIcon instance
462      */

463     public static ImageIcon JavaDoc getImageIcon(String JavaDoc icon)
464     {
465         URL url=null;
466         try {
467             // create the default url
468
url=new URL("jar:file:///"
469                     + System.getProperty("user.dir").replace('\\', '/')
470                     + "/lib/lucane-client-" + Client.VERSION + ".jar!/images/"
471                     + icon);
472         } catch(MalformedURLException mue) {
473             url = null;
474         }
475         
476         // check icon existence
477
try {
478             if(url != null && url.getContent() == null)
479                 url = null;
480         } catch (IOException e) {
481             url = null;
482         }
483         
484         // if the icon does not exist, show a warning icon instead
485
if(url == null)
486         {
487             Icon JavaDoc ic = (IconUIResource JavaDoc)UIManager.getIcon("OptionPane.warningIcon");
488             BufferedImage JavaDoc image = new BufferedImage JavaDoc(ic.getIconWidth(), ic.getIconHeight(), BufferedImage.TYPE_INT_ARGB);
489             Graphics JavaDoc g = image.getGraphics();
490             ic.paintIcon(new JLabel JavaDoc(), g, 0, 0);
491             return new ImageIcon JavaDoc(image);
492         }
493                 
494         return new ImageIcon JavaDoc(url);
495     }
496     
497     /**
498      * Main
499      *
500      * @param args command line argumens
501      */

502     public static void main(String JavaDoc[] args)
503     {
504         Translation.setLocale("en");
505         
506         //init logging
507
try {
508             new File(System.getProperty("user.dir") + "/logs").mkdirs();
509             Logging.init(LOG_FILE, "ALL");
510         } catch(IOException ioe) {
511             System.err.println("Unable to init logging, exiting.");
512             System.exit(1);
513         }
514
515         String JavaDoc configFile = CONFIG_FILE;
516         if(args.length == 1 || args.length == 3)
517             configFile = args[0];
518
519         //configuration
520
ClientConfig config = null;
521         try {
522             config = new ClientConfig(configFile);
523         } catch(Exception JavaDoc e) {
524             DialogBox.error(Translation.tr("clientNoParamsFile"));
525             System.exit(1);
526         }
527         
528         //look and feel
529
try {
530             Class JavaDoc lnfClass = Class.forName(config.getLooknfeel());
531             LookAndFeel JavaDoc lnf = (LookAndFeel JavaDoc)lnfClass.newInstance();
532             UIManager.setLookAndFeel(lnf);
533         } catch(Throwable JavaDoc t) {
534             t.printStackTrace();
535         }
536         UIManager.getDefaults().put("ClassLoader", Client.class.getClassLoader());
537         
538         
539         //initialization
540
Client client = Client.getInstance();
541         client.setConfig(config);
542         
543         String JavaDoc login = config.getLogin();
544         String JavaDoc passwd = null;
545         if(args.length == 2 || args.length == 3)
546         {
547             int shift = args.length-2;
548             login = args[0+shift];
549             passwd = args[1+shift];
550         }
551         
552         client.showConnectBox(login, passwd, config.getServerHost(), config.getServerPort());
553         if(client.getConnectBox().connectionAccepted())
554         {
555             client.setConnected(true);
556             Runtime.getRuntime().addShutdownHook(new ShutdownHook());
557             client.startMainPlugin();
558         }
559     }
560 }
561
Popular Tags