Add Registration functionality and tidy up
[WeStealzYourDataz.git] / src / uk / ac / ntu / n0521366 / wsyd / client / ClientGUI.java
1 /*
2  * The MIT License
3  *
4  * Copyright 2015 Eddie Berrisford-Lynch <dev@fun2be.me>.
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to deal
8  * in the Software without restriction, including without limitation the rights
9  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10  * copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22  * THE SOFTWARE.
23  */
24 package uk.ac.ntu.n0521366.wsyd.client;
25
26 import java.awt.event.ActionEvent;
27 import java.awt.event.ActionListener;
28 import java.io.IOException;
29 import java.net.InetSocketAddress;
30 import java.net.Socket;
31 import java.text.MessageFormat;
32 import java.text.SimpleDateFormat;
33 import java.util.ArrayList;
34 import java.util.SortedMap;
35 import javax.swing.JDialog;
36 import javax.swing.JFrame;
37 import javax.swing.JTextField;
38 import java.util.TreeSet;
39 import java.util.logging.Level;
40 import java.util.logging.Logger;
41 import javax.swing.JProgressBar;
42 import javax.swing.ProgressMonitor;
43 import javax.swing.Timer;
44 import uk.ac.ntu.n0521366.wsyd.libs.WSYD_Member;
45 import uk.ac.ntu.n0521366.wsyd.libs.message.MessageLogin;
46 import uk.ac.ntu.n0521366.wsyd.libs.message.MessageMember;
47 import uk.ac.ntu.n0521366.wsyd.libs.net.Network;
48 import uk.ac.ntu.n0521366.wsyd.libs.net.NetworkMessage;
49 import uk.ac.ntu.n0521366.wsyd.libs.net.NetworkMessageEvent;
50 import uk.ac.ntu.n0521366.wsyd.libs.net.NetworkMessageEventListener;
51 import uk.ac.ntu.n0521366.wsyd.libs.net.NetworkServerTCP;
52 import uk.ac.ntu.n0521366.wsyd.libs.net.NetworkServerUDP;
53 import uk.ac.ntu.n0521366.wsyd.libs.net.NetworkServerUDPMulticast;
54 import uk.ac.ntu.n0521366.wsyd.libs.net.NetworkStream;
55 import uk.ac.ntu.n0521366.wsyd.libs.net.NetworkStreamManager;
56 import uk.ac.ntu.n0521366.wsyd.libs.net.ServiceAddressMap;
57 import uk.ac.ntu.n0521366.wsyd.libs.net.WSYD_SocketAddress;
58
59 /**
60  *
61  * @author Eddie Berrisford-Lynch
62  */
63 public class ClientGUI extends javax.swing.JFrame implements NetworkMessageEventListener {
64     
65     private boolean loginSuccessful = false;
66     
67     private boolean registrationSuccessful = false;
68     
69     private final Login loginDialog = new Login(this, true);
70     private final EditProfile registrationDialog = new EditProfile(this, true);
71     
72     /**
73      * Member record for this client's user.
74      */
75     private WSYD_Member myMember;
76     
77     Socket socialSocket;
78     
79     /**
80      * Readable/displayable name of this application
81      * 
82      * TODO: title should be assigned userID when SocialServer connection established
83      */
84     private  String _title = null;
85     
86     /**
87      * Network services to address map.
88      */
89     ServiceAddressMap _serviceToAddressMap;
90     
91     /**
92      * Handles display and sending of log messages.
93      */
94     @SuppressWarnings("NonConstantLogger")
95     private static Logger LOGGER;
96     
97     /**
98      * SortedMap wraps a TreeMap that has been made thread-safe by
99      * Collections.synchronizedSortedMap() in readMembers().
100      *
101      * Long key, the userID
102      * WSYD_Member member record
103      */
104     SortedMap<Long, WSYD_Member> _members;
105     
106     /**
107      * userIDs of members currently logged in
108      */
109     ArrayList<Long> _membersOnline;
110     
111     Timer _regularTasks;
112     
113     WSYD_SocketAddress _multicastAdvertiserSA;
114     
115     NetworkServerUDPMulticast _multicastService;
116     
117     WSYD_SocketAddress _udpNotificationServiceSA;
118     
119     NetworkServerUDP _udpNotificationService;
120     
121     WSYD_SocketAddress _tcpChatServiceSA;
122     
123     NetworkServerTCP _tcpChatService;
124     
125     NetworkStreamManager _tcpStreamManager;
126     
127     /**
128      * Creates new form ClientGUI
129      */
130     public ClientGUI() {
131         initComponents();
132         _serviceToAddressMap = new ServiceAddressMap(_title, LOGGER);
133         _tcpStreamManager = new NetworkStreamManager();
134     }
135
136     /**
137      * This method is called from within the constructor to initialize the form.
138      * WARNING: Do NOT modify this code. The content of this method is always
139      * regenerated by the Form Editor.
140      */
141     @SuppressWarnings("unchecked")
142     // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
143     private void initComponents() {
144
145         gSplitPane1 = new javax.swing.JSplitPane();
146         gDetails = new javax.swing.JTabbedPane();
147         gPersonalProfile = new javax.swing.JPanel();
148         gPersonalName = new javax.swing.JLabel();
149         gPersonalStatus = new javax.swing.JTextField();
150         gScrollPane1 = new javax.swing.JScrollPane();
151         gPersonalNewsFeed = new javax.swing.JList();
152         gFriendProfile = new javax.swing.JPanel();
153         gLabelFriendName = new javax.swing.JLabel();
154         jScrollPane1 = new javax.swing.JScrollPane();
155         gTAreaFriendBio = new javax.swing.JTextArea();
156         jScrollPane2 = new javax.swing.JScrollPane();
157         gListFriendInterests = new javax.swing.JList();
158         gLabelFriendBirthplace = new javax.swing.JLabel();
159         gLabelFriendBirthplaceData = new javax.swing.JLabel();
160         gLabelFriendLocation = new javax.swing.JLabel();
161         gLabelFriendLocationData = new javax.swing.JLabel();
162         jScrollPane3 = new javax.swing.JScrollPane();
163         gTAreaFriendStatuses = new javax.swing.JTextArea();
164         gLabelFriendInterests = new javax.swing.JLabel();
165         gButtonAddFriendChat = new javax.swing.JButton();
166         gOnlineList = new javax.swing.JScrollPane();
167         jList1 = new javax.swing.JList();
168         gStatusPanel = new javax.swing.JPanel();
169         gLabelFriendsOnlineQty = new javax.swing.JLabel();
170         gLabelFriendRequestsQty = new javax.swing.JLabel();
171         gLabelOnlineQty = new javax.swing.JLabel();
172
173         setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
174         setTitle("We Stealz Your Dataz");
175         addWindowListener(new java.awt.event.WindowAdapter() {
176             public void windowActivated(java.awt.event.WindowEvent evt) {
177                 formWindowActivated(evt);
178             }
179         });
180
181         gSplitPane1.setDividerLocation(this.getWidth() - 200);
182         gSplitPane1.setResizeWeight(0.5);
183         gSplitPane1.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
184             public void propertyChange(java.beans.PropertyChangeEvent evt) {
185                 gSplitPane1PropertyChange(evt);
186             }
187         });
188
189         gPersonalName.setText("Your Name");
190         gPersonalName.setToolTipText("Click to edit your profile");
191         gPersonalName.setMinimumSize(new java.awt.Dimension(64, 15));
192
193         gPersonalStatus.setText("My current status");
194         gPersonalStatus.addActionListener(new java.awt.event.ActionListener() {
195             public void actionPerformed(java.awt.event.ActionEvent evt) {
196                 gPersonalStatusActionPerformed(evt);
197             }
198         });
199
200         gPersonalNewsFeed.setModel(new javax.swing.AbstractListModel() {
201             String[] strings = { "Server uptime: 1 hour" };
202             public int getSize() { return strings.length; }
203             public Object getElementAt(int i) { return strings[i]; }
204         });
205         gPersonalNewsFeed.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
206         gPersonalNewsFeed.setToolTipText("WSYD News Feed");
207         gPersonalNewsFeed.setMinimumSize(new java.awt.Dimension(64, 17));
208         gPersonalNewsFeed.setNextFocusableComponent(gPersonalName);
209         gScrollPane1.setViewportView(gPersonalNewsFeed);
210
211         javax.swing.GroupLayout gPersonalProfileLayout = new javax.swing.GroupLayout(gPersonalProfile);
212         gPersonalProfile.setLayout(gPersonalProfileLayout);
213         gPersonalProfileLayout.setHorizontalGroup(
214             gPersonalProfileLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
215             .addGroup(gPersonalProfileLayout.createSequentialGroup()
216                 .addGap(30, 30, 30)
217                 .addGroup(gPersonalProfileLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
218                     .addComponent(gScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 460, Short.MAX_VALUE)
219                     .addComponent(gPersonalName, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
220                     .addComponent(gPersonalStatus))
221                 .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
222         );
223         gPersonalProfileLayout.setVerticalGroup(
224             gPersonalProfileLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
225             .addGroup(gPersonalProfileLayout.createSequentialGroup()
226                 .addContainerGap()
227                 .addComponent(gPersonalName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
228                 .addGap(18, 18, 18)
229                 .addComponent(gPersonalStatus, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
230                 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
231                 .addComponent(gScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 248, javax.swing.GroupLayout.PREFERRED_SIZE)
232                 .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
233         );
234
235         gDetails.addTab("News and Status", gPersonalProfile);
236
237         gLabelFriendName.setText("Friend's Name");
238
239         gTAreaFriendBio.setEditable(false);
240         gTAreaFriendBio.setColumns(35);
241         gTAreaFriendBio.setLineWrap(true);
242         gTAreaFriendBio.setRows(12);
243         gTAreaFriendBio.setTabSize(4);
244         gTAreaFriendBio.setText("Friend's Bio");
245         gTAreaFriendBio.setMinimumSize(new java.awt.Dimension(100, 50));
246         gTAreaFriendBio.setPreferredSize(new java.awt.Dimension(350, 156));
247         jScrollPane1.setViewportView(gTAreaFriendBio);
248
249         gListFriendInterests.setFont(new java.awt.Font("Dialog", 0, 12)); // NOI18N
250         gListFriendInterests.setModel(new javax.swing.AbstractListModel() {
251             String[] strings = { "Interest1", "Interest2", "Interest3", "..." };
252             public int getSize() { return strings.length; }
253             public Object getElementAt(int i) { return strings[i]; }
254         });
255         gListFriendInterests.setMinimumSize(new java.awt.Dimension(85, 85));
256         gListFriendInterests.setPreferredSize(new java.awt.Dimension(100, 85));
257         jScrollPane2.setViewportView(gListFriendInterests);
258
259         gLabelFriendBirthplace.setText("Birthplace:");
260
261         gLabelFriendBirthplaceData.setFont(new java.awt.Font("Dialog", 0, 12)); // NOI18N
262         gLabelFriendBirthplaceData.setText("Their Birthplace");
263
264         gLabelFriendLocation.setText("Current City/Town:");
265
266         gLabelFriendLocationData.setFont(new java.awt.Font("Dialog", 0, 12)); // NOI18N
267         gLabelFriendLocationData.setText("Their City/Town");
268
269         gTAreaFriendStatuses.setEditable(false);
270         gTAreaFriendStatuses.setColumns(20);
271         gTAreaFriendStatuses.setRows(5);
272         gTAreaFriendStatuses.setText("Friend's Three statuses");
273         jScrollPane3.setViewportView(gTAreaFriendStatuses);
274
275         gLabelFriendInterests.setText("Interests:");
276
277         gButtonAddFriendChat.setText("Add");
278
279         javax.swing.GroupLayout gFriendProfileLayout = new javax.swing.GroupLayout(gFriendProfile);
280         gFriendProfile.setLayout(gFriendProfileLayout);
281         gFriendProfileLayout.setHorizontalGroup(
282             gFriendProfileLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
283             .addGroup(gFriendProfileLayout.createSequentialGroup()
284                 .addGroup(gFriendProfileLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
285                     .addGroup(gFriendProfileLayout.createSequentialGroup()
286                         .addGap(24, 24, 24)
287                         .addComponent(gLabelFriendLocation))
288                     .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, gFriendProfileLayout.createSequentialGroup()
289                         .addContainerGap()
290                         .addGroup(gFriendProfileLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
291                             .addComponent(gLabelFriendInterests, javax.swing.GroupLayout.Alignment.TRAILING)
292                             .addComponent(gLabelFriendName, javax.swing.GroupLayout.Alignment.TRAILING)
293                             .addComponent(gLabelFriendBirthplace, javax.swing.GroupLayout.Alignment.TRAILING))))
294                 .addGap(32, 32, 32)
295                 .addGroup(gFriendProfileLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
296                     .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
297                     .addComponent(gLabelFriendLocationData)
298                     .addGroup(gFriendProfileLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
299                         .addComponent(gButtonAddFriendChat)
300                         .addComponent(gLabelFriendBirthplaceData)))
301                 .addGap(90, 90, 90)
302                 .addGroup(gFriendProfileLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
303                     .addComponent(jScrollPane1)
304                     .addComponent(jScrollPane3))
305                 .addGap(21, 21, 21))
306         );
307         gFriendProfileLayout.setVerticalGroup(
308             gFriendProfileLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
309             .addGroup(gFriendProfileLayout.createSequentialGroup()
310                 .addContainerGap()
311                 .addGroup(gFriendProfileLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
312                     .addGroup(gFriendProfileLayout.createSequentialGroup()
313                         .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
314                         .addGap(18, 18, 18)
315                         .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 111, Short.MAX_VALUE))
316                     .addGroup(gFriendProfileLayout.createSequentialGroup()
317                         .addComponent(gLabelFriendName)
318                         .addGap(39, 39, 39)
319                         .addGroup(gFriendProfileLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
320                             .addComponent(gLabelFriendBirthplaceData)
321                             .addComponent(gLabelFriendBirthplace))
322                         .addGap(38, 38, 38)
323                         .addGroup(gFriendProfileLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
324                             .addComponent(gLabelFriendLocation)
325                             .addComponent(gLabelFriendLocationData))
326                         .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
327                         .addGroup(gFriendProfileLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
328                             .addComponent(gLabelFriendInterests)
329                             .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
330                     .addGroup(gFriendProfileLayout.createSequentialGroup()
331                         .addComponent(gButtonAddFriendChat)
332                         .addGap(0, 0, Short.MAX_VALUE)))
333                 .addContainerGap())
334         );
335
336         gDetails.addTab("Friend Profile", gFriendProfile);
337
338         gSplitPane1.setLeftComponent(gDetails);
339
340         jList1.setModel(new javax.swing.AbstractListModel() {
341             String[] strings = { "Eddie Berrisford-Lynch", "Tom Thumb", "Peter Pan", "Freddy Mercury", "Sam Smith" };
342             public int getSize() { return strings.length; }
343             public Object getElementAt(int i) { return strings[i]; }
344         });
345         jList1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
346         jList1.setMaximumSize(new java.awt.Dimension(200, 119));
347         jList1.setMinimumSize(new java.awt.Dimension(100, 119));
348         jList1.setVisibleRowCount(30);
349         gOnlineList.setViewportView(jList1);
350
351         gSplitPane1.setRightComponent(gOnlineList);
352
353         getContentPane().add(gSplitPane1, java.awt.BorderLayout.CENTER);
354
355         gLabelFriendsOnlineQty.setText("Friends: 000");
356
357         gLabelFriendRequestsQty.setText("Requests Pending: 000");
358
359         gLabelOnlineQty.setText("Online: 000");
360
361         javax.swing.GroupLayout gStatusPanelLayout = new javax.swing.GroupLayout(gStatusPanel);
362         gStatusPanel.setLayout(gStatusPanelLayout);
363         gStatusPanelLayout.setHorizontalGroup(
364             gStatusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
365             .addGroup(gStatusPanelLayout.createSequentialGroup()
366                 .addComponent(gLabelOnlineQty)
367                 .addGap(18, 18, 18)
368                 .addComponent(gLabelFriendsOnlineQty)
369                 .addGap(18, 18, 18)
370                 .addComponent(gLabelFriendRequestsQty)
371                 .addContainerGap(651, Short.MAX_VALUE))
372         );
373         gStatusPanelLayout.setVerticalGroup(
374             gStatusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
375             .addGroup(gStatusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
376                 .addComponent(gLabelFriendsOnlineQty)
377                 .addComponent(gLabelFriendRequestsQty)
378                 .addComponent(gLabelOnlineQty))
379         );
380
381         getContentPane().add(gStatusPanel, java.awt.BorderLayout.SOUTH);
382
383         pack();
384     }// </editor-fold>//GEN-END:initComponents
385
386     private void gPersonalStatusActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_gPersonalStatusActionPerformed
387         // TODO add your handling code here:
388     }//GEN-LAST:event_gPersonalStatusActionPerformed
389
390     private void gSplitPane1PropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_gSplitPane1PropertyChange
391         // TODO add your handling code here:
392     }//GEN-LAST:event_gSplitPane1PropertyChange
393
394     private void formWindowActivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowActivated
395         // TODO add your handling code here:
396     }//GEN-LAST:event_formWindowActivated
397
398     private ClientGUI initNeighbourListener() {
399         _multicastAdvertiserSA = new WSYD_SocketAddress(Network.MULTICAST_IP, Network.PORTS_MULTICAST_DISCOVERY, WSYD_SocketAddress.Protocol.UDP);
400         _multicastService = new NetworkServerUDPMulticast(_multicastAdvertiserSA, _title + "MC", _serviceToAddressMap, LOGGER);
401         _multicastService.getEventManager().addNetworkMessageEventListener(this, "Neighbour");
402         _multicastService.execute();
403         _serviceToAddressMap.put("all", new ServiceAddressMap.LastSeenHost(new InetSocketAddress(Network.MULTICAST_IP, Network.PORTS_MULTICAST_DISCOVERY), ServiceAddressMap.LastSeenHost.STATE.STATIC));
404                
405         return this;
406     }
407     
408     private void initListeners() {
409         
410         _udpNotificationServiceSA = new WSYD_SocketAddress(Network.IPv4_WILDCARD, Network.PORTS_EPHEMERAL, WSYD_SocketAddress.Protocol.UDP);
411         _udpNotificationService = new NetworkServerUDP(_udpNotificationServiceSA, _title + "_Notifier", _serviceToAddressMap, LOGGER);
412         _udpNotificationService.getEventManager().addNetworkMessageEventListener(this, "Notification");
413         _udpNotificationService.execute();
414         
415         _tcpChatServiceSA = new WSYD_SocketAddress(Network.IPv4_WILDCARD, Network.PORTS_EPHEMERAL, WSYD_SocketAddress.Protocol.TCP);
416         _tcpChatService = new NetworkServerTCP(_tcpChatServiceSA, _title + "_Chat", _serviceToAddressMap, _tcpStreamManager, LOGGER);
417         _tcpChatService.getEventManager().addNetworkMessageEventListener(this, "ChatRequest");
418         _tcpChatService.execute();
419         
420         ActionListener servicesAnnounceActionListener = new ActionListener() {
421             /**
422              * Perform regular house-keeping tasks.
423              * @param e 
424              */
425             @Override
426             public void actionPerformed(ActionEvent e) {   
427                 // clean up the known hosts map
428                 ArrayList<String> servicesRemoved = _serviceToAddressMap.cleanServiceAddressMap(5000);
429                 for (String service: servicesRemoved) {
430                     // FIXME: does the process care if hosts have been removed? if not, remove this array iteration
431                     switch (service) {
432                     }
433                 }
434                 
435                 // TODO: PING server
436
437             }
438         };
439         
440         _regularTasks = new Timer(1000, servicesAnnounceActionListener);
441         _regularTasks.setInitialDelay(100);
442         _regularTasks.start();
443         
444     }
445     
446     private void connectionDialog() {
447         /* FIXME: progress monitor
448         ProgressMonitor pm = new ProgressMonitor(this, "Waiting for the Server...", "", 0, 10);
449         pm.setMillisToPopup(100);
450         pm.setProgress(1);
451         */
452         while (!_serviceToAddressMap.containsService("ServerSocialMC"));
453
454         // pm.setProgress(10);
455         
456         try {
457             socialSocket = new Socket(_serviceToAddressMap.getServiceAddress("ServerSocialMC").getAddress(), Network.PORTS_SERVER_SOCIAL);
458             NetworkStream newStream = new NetworkStream(socialSocket, _tcpStreamManager);
459             _tcpStreamManager.addStream(NetworkStreamManager.SERVERSOCIAL, newStream);
460             newStream.getEventManager().addNetworkMessageEventListener(this);
461         } catch (IOException ex) {
462             //Logger.getLogger(ClientGUI.class.getName()).log(Level.SEVERE, null, ex);
463             System.err.println("IOException in connectionDialog()");
464         }
465         loginDialog();
466     }
467     
468     private void loginDialog()
469     {
470         //WSYD_Login loginDialog = new Login(this, true);
471         loginDialog.setLocationRelativeTo(null);
472         loginDialog.setVisible(true);
473         if (loginSuccessful)
474         {
475             this.setLocationRelativeTo(null);
476             this.setVisible(true);
477         }
478     }
479     
480     public void loginAbort()
481     {
482         this.dispose();
483     }
484     
485     public boolean validateLogin(String uName, String pWord)
486     {
487         boolean result = false;
488         System.out.println(uName + pWord + "<");
489         
490         if (uName.equals("admin") && pWord.equals("admin"))
491         {
492             System.out.println("True");
493             loginSuccessful = true;
494             result = true;
495         }
496         else {
497             NetworkMessage message = new NetworkMessage("Login", null, new MessageLogin(uName, pWord));
498             NetworkStream ns = _tcpStreamManager._tcpStreams.get(NetworkStreamManager.SERVERSOCIAL);
499             if (ns != null) {
500                 ns.write(message);                
501                 result = true;
502             }
503             else
504                 System.err.println(" validateLogin(): do not know where ServerSocial is");
505         }
506         return result;
507     }
508     
509     public void registrationProfileDialog()
510     {
511         registrationDialog.setLocationRelativeTo(null);
512         registrationDialog.setVisible(true);
513     }
514     
515     public void confirmRegistration(WSYD_Member registrationData)
516     {
517         // TODO: confirmRegistration(): submit registrationDialog data to SocialServer
518         if (registrationData != null) {
519             NetworkMessage message = new NetworkMessage("Register", null, new MessageMember(registrationData));
520             NetworkStream ns = this._tcpStreamManager._tcpStreams.get(NetworkStreamManager.SERVERSOCIAL);
521             if (ns != null) {
522                 ns.write(message);
523             }
524             else
525                 System.err.println("confirmRegistration(): do not know where SocialServer is");
526         }
527     }
528     
529     
530     /**
531      * @param args the command line arguments
532      */
533     public static void main(String args[]) {
534         /* Set the Nimbus look and feel */
535         //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
536         /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
537          * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
538          */
539         try {
540             for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
541                 if ("Nimbus".equals(info.getName())) {
542                     javax.swing.UIManager.setLookAndFeel(info.getClassName());
543                     break;
544                 }
545             }
546         } catch (ClassNotFoundException ex) {
547             java.util.logging.Logger.getLogger(ClientGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
548         } catch (InstantiationException ex) {
549             java.util.logging.Logger.getLogger(ClientGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
550         } catch (IllegalAccessException ex) {
551             java.util.logging.Logger.getLogger(ClientGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
552         } catch (javax.swing.UnsupportedLookAndFeelException ex) {
553             java.util.logging.Logger.getLogger(ClientGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
554         }
555         //</editor-fold>
556         //</editor-fold>
557         //</editor-fold>
558         //</editor-fold>
559
560         /* Create and display the form */
561         java.awt.EventQueue.invokeLater(new Runnable() {
562             public void run() {
563                 new ClientGUI().initNeighbourListener().connectionDialog();
564             }
565         });
566     }
567
568     // Variables declaration - do not modify//GEN-BEGIN:variables
569     private javax.swing.JButton gButtonAddFriendChat;
570     private javax.swing.JTabbedPane gDetails;
571     private javax.swing.JPanel gFriendProfile;
572     private javax.swing.JLabel gLabelFriendBirthplace;
573     private javax.swing.JLabel gLabelFriendBirthplaceData;
574     private javax.swing.JLabel gLabelFriendInterests;
575     private javax.swing.JLabel gLabelFriendLocation;
576     private javax.swing.JLabel gLabelFriendLocationData;
577     private javax.swing.JLabel gLabelFriendName;
578     private javax.swing.JLabel gLabelFriendRequestsQty;
579     private javax.swing.JLabel gLabelFriendsOnlineQty;
580     private javax.swing.JLabel gLabelOnlineQty;
581     private javax.swing.JList gListFriendInterests;
582     private javax.swing.JScrollPane gOnlineList;
583     private javax.swing.JLabel gPersonalName;
584     private javax.swing.JList gPersonalNewsFeed;
585     private javax.swing.JPanel gPersonalProfile;
586     private javax.swing.JTextField gPersonalStatus;
587     private javax.swing.JScrollPane gScrollPane1;
588     private javax.swing.JSplitPane gSplitPane1;
589     private javax.swing.JPanel gStatusPanel;
590     private javax.swing.JTextArea gTAreaFriendBio;
591     private javax.swing.JTextArea gTAreaFriendStatuses;
592     private javax.swing.JList jList1;
593     private javax.swing.JScrollPane jScrollPane1;
594     private javax.swing.JScrollPane jScrollPane2;
595     private javax.swing.JScrollPane jScrollPane3;
596     // End of variables declaration//GEN-END:variables
597
598     @Override
599     public void NetworkMessageReceived(NetworkMessageEvent event) {
600         NetworkMessage nm = event.getNetworkMessage();
601         if (nm == null)
602             return;
603         System.err.println(MessageFormat.format("Network Message received with intent {0} from sender {1}", nm.getIntent(), nm.getSender()));
604         switch (nm.getIntent()) {
605             case "Login":
606                 MessageLogin ml = (MessageLogin) nm.getMessage();
607                 if (ml != null) {
608                     this.loginSuccessful = ml._loggedIn;
609                     if (ml._loggedIn)
610                         this.loginDialog.dispose();
611                     else
612                         loginDialog.setUserName("Invalid Login: retry");
613                 }
614                 break;
615             case "Register":
616                 MessageMember mm = (MessageMember) nm.getMessage();
617                 if (mm != null) {
618                     if (mm.getRegistered() == MessageMember.STATE.REGISTERED) {
619                         this.myMember = mm.getMember();
620                         this.registrationSuccessful = true;
621                         // dismiss the dialogs and show client's main window
622                         registrationDialog.dispose();
623                         loginDialog.dispose();
624                         this.setTitle("WSYD logged in as " + this.myMember._userName);
625                         this.setLocationRelativeTo(null);
626                         this.setVisible(true);
627                     } else
628                         javax.swing.JOptionPane.showMessageDialog(registrationDialog, mm.getStatus(), "Registration failed", javax.swing.JOptionPane.ERROR_MESSAGE);
629                 }
630                 break;
631             default:
632                 System.err.println(MessageFormat.format("Unhandled NetworkMessage received with intent {0} from sender {1}", nm.getIntent(), nm.getSender()));
633                 
634         }
635     }
636 }