Browse Source

v1 chat_local

Alexandre Gonzalvez 3 years ago
parent
commit
7bd2f3ecb6

+ 127
- 93
Application/Clavardage/src/controller/Controller.java View File

@@ -28,17 +28,22 @@ import view.Interface;
28 28
 public class Controller {
29 29
 
30 30
 	/*** CONSTANTES ***/
31
-	final static int portUDPlistening_remoteUsr2 = 31002; // TO REMOVE when we use broadcast
32
-    final static int portUDPlistening_remoteUsr3 = 31003; // TO REMOVE when we use broadcast
33
-    
34
-    public Boolean interfaceRunning;
31
+	int NB_SECOND_WAITING_RESPONSE_BROADCAST = 2;
32
+	
33
+	// TO REMOVE when we use broadcast
34
+	final static int portUDPlistening_usr1 = 31001; 
35
+	final static int portUDPlistening_remoteUsr2 = 31002; 
36
+    final static int portUDPlistening_remoteUsr3 = 31003; 
37
+    final static int [] tabBroadcast = {portUDPlistening_usr1,portUDPlistening_remoteUsr2,portUDPlistening_remoteUsr3};
38
+    		
39
+    public Boolean interfaceRunning = false;
35 40
 	/*** ATTRIBUTS ***/
36 41
 	protected LocalUser myUser;
37 42
 	protected Interface view;
38 43
 	private ListeningThreadUDP udp_connect_thread;
39 44
 	private ListeningThreadTCPConnection tcp_connect_thread;
40 45
 	private Historique histoire;
41
-	private Chat activeChat;
46
+	protected Chat activeChat;
42 47
 	
43 48
 	/**
44 49
 	 *  Constructor of Controller
@@ -82,7 +87,8 @@ public class Controller {
82 87
 		
83 88
 		notify_remote_users();
84 89
 		
85
-		
90
+		interfaceRunning =true;
91
+		view=Interface.createAndShowGUI(this);
86 92
 	}
87 93
 	
88 94
 	/**
@@ -110,13 +116,32 @@ public class Controller {
110 116
 		catch(UnknownHostException e) {
111 117
 			JOptionPane.showMessageDialog(null ,"Could not find local address!");
112 118
 		}
119
+		
113 120
 		this.myUser = new LocalUser(pseudo,addIP,portUDPsend,portUDPlistening,portTCP);
121
+		try {
122
+			if(this.validatePseudo(pseudo)) {
123
+				
124
+				
125
+				this.udp_connect_thread = new ListeningThreadUDP("UDP Listening thread",this);
126
+				this.udp_connect_thread.start();
127
+				
128
+				this.tcp_connect_thread = new ListeningThreadTCPConnection("TCP main Listening thread",this);
129
+				this.tcp_connect_thread.start();
130
+				
131
+				interfaceRunning =true;
132
+				view=Interface.createAndShowGUI(this);
133
+			}
134
+			else {
135
+				System.out.println("Unavailable "+pseudo);
136
+			}
137
+		} catch (IOException e) {
138
+			e.printStackTrace();
139
+		}
140
+		
141
+		
142
+		
114 143
 		
115
-		this.udp_connect_thread = new ListeningThreadUDP("UDP Listening thread",this);
116
-		this.udp_connect_thread.start();
117 144
 		
118
-		this.tcp_connect_thread = new ListeningThreadTCPConnection("TCP main Listening thread",this);
119
-		this.tcp_connect_thread.start();
120 145
 		
121 146
 		notify_remote_users();
122 147
 	}
@@ -188,11 +213,11 @@ public class Controller {
188 213
 	public void changePseudo() throws IOException { 
189 214
 	    String oldPseudo = this.myUser.getPseudo(); //Saves the old one for comparison
190 215
 
191
-	    String tmpPseudo = view.PseudotextField.getText();  // Read user input
216
+	    String tmpPseudo = view.ChangePseudotextField.getText();  // Read user input
192 217
 
193 218
 	    if(!(this.validatePseudo(tmpPseudo)) || tmpPseudo.equals(oldPseudo)) {
194 219
 	        view.Pseudolabel.setText("Already exists, enter another nickname. Your current username is: " + oldPseudo);  // Read user input
195
-	        tmpPseudo = view.PseudotextField.getText();  // Read user input
220
+	        tmpPseudo = view.ChangePseudotextField.getText();  // Read user input
196 221
 	    }
197 222
 	    else {
198 223
 		    this.myUser.setPseudo(tmpPseudo);
@@ -221,46 +246,45 @@ public class Controller {
221 246
 		
222 247
 		// Call broadcast 
223 248
 		InetAddress broadcastIP = InetAddress.getLocalHost(); // change to broadcast
224
-		//System.out.println(broadcastIP);
249
+		//System.out.println(this.myUser.getPortUDPsend());
225 250
 		DatagramSocket dgramSocket = new DatagramSocket(this.myUser.getPortUDPsend(),this.myUser.getAddIP());
226 251
 		byte[] buffer = new byte[256];
227 252
 		
228 253
 		// Création du message à envoyer
229
-		String toSend = this.myUser.getAddIP()+":"+this.myUser.getPortUDPsend()+":test";
230
-		
231
-		// Send to remote user 1
232
-		DatagramPacket outPacket= new DatagramPacket(toSend.getBytes(), toSend.length(),broadcastIP, portUDPlistening_remoteUsr2);
233
-		dgramSocket.send(outPacket);
234
-		
235
-		// Send to remote user 2
236
-		outPacket= new DatagramPacket(toSend.getBytes(), toSend.length(),broadcastIP, portUDPlistening_remoteUsr3);
237
-		dgramSocket.send(outPacket);
238
-		
239
-		// Initialisation des variables de la boucle
240
-		Boolean valid = true;
254
+		String toSend = this.myUser.getAddIP()+":"+this.myUser.getPortUDPsend()+":info";
255
+		
256
+		// Send to other active user (simulation of broadcast)
257
+		DatagramPacket outPacket = null;
258
+		int tabBroadcastSize = tabBroadcast.length;
259
+		for(int i=0;i<tabBroadcastSize;i++) {
260
+			if(tabBroadcast[i]!=myUser.getPortUDPlistening()) {
261
+				outPacket= new DatagramPacket(toSend.getBytes(), toSend.length(),broadcastIP, tabBroadcast[i]);
262
+				dgramSocket.send(outPacket);
263
+			}
264
+		}
241 265
 	
266
+		/*** For 5 seconds wait for answer : validate pseudo & add to userlist ***/
267
+		Boolean valid = true;
242 268
         DatagramPacket inPacket;
243 269
         String response = null;
244 270
         String[] tabresponse= new String [4];
245 271
 		dgramSocket.setSoTimeout(1000);
246 272
 		Boolean arecu;
247
-		
248
-		System.out.print("Wait for pseudo validation ...\n");
249
-
250 273
 		int nbReponse =0;
274
+		System.out.println("("+myUser.getPseudo()+") Waiting for pseudo validation ...");
251 275
 		Date oldDate = new Date();
252 276
         Date newDate = new Date();
253
-		while( (newDate.getTime()-oldDate.getTime()) < 5000 && valid) {
254
-			
277
+        
278
+		while( (newDate.getTime()-oldDate.getTime()) < NB_SECOND_WAITING_RESPONSE_BROADCAST*1000 && valid) {
255 279
 			nbReponse++;
256 280
 			inPacket= new DatagramPacket(buffer, buffer.length);
257
-			
258 281
 			arecu=true;
259 282
 			try{
260 283
 				dgramSocket.receive(inPacket);
261 284
 			}catch (Exception e) {
262 285
 				arecu=false;
263 286
 			} 
287
+			
264 288
 			buffer = inPacket.getData();
265 289
 			response = new String(buffer);
266 290
 			
@@ -268,9 +292,6 @@ public class Controller {
268 292
 				// On découpe la réponse en tableau de string ([adresseIP,tcpPort,nickname])
269 293
 				tabresponse = response.split(":");
270 294
 				
271
-				// Affichage de la réponse
272
-				//System.out.println("Remote user n°"+nbReponse+"\nIP : "+tabresponse[0]+"\nn°Port : "+tabresponse[1]+"\npseudo : "+tabresponse[2]);
273
-				
274 295
 				// Si reception on ajoute l'utilisateur à notre liste d'utilisateur distant
275 296
 				this.myUser.addRemoteUser(InetAddress.getByName(tabresponse[0].split("/")[1]),Integer.parseInt(tabresponse[1]),tabresponse[2]);
276 297
 				valid= (tmpPseudo.compareTo(tabresponse[2])!=0); // On regarde la différence entre notre pseudo et le pseudo reçu
@@ -287,46 +308,35 @@ public class Controller {
287 308
 		
288 309
 		return valid;
289 310
 	}
311
+	
290 312
 	/** notify_remote_users
291 313
 	 * <p>
292 314
 	 * 		En utilisant le port UDP d'envoi, on envoie en broadcast les informations nous concernant
293 315
 	 * </p>
294 316
 	 */
295 317
 	public void notify_remote_users() {
296
-		// Création du socket d'envoi d'information
297 318
 		DatagramSocket dgramSocket= null;
298 319
         try {
299 320
             dgramSocket= new DatagramSocket(this.myUser.getPortUDPsend(),this.myUser.getAddIP());
300 321
         } catch (IOException e) {
301 322
             e.printStackTrace();
302 323
         }
303
-
304
-        // Construction du message à envoyer
305
-        String toSend = this.myUser.getAddIP().toString()+":"+this.myUser.getPortTCP()+":"+this.myUser.getPseudo()+":test";
306 324
         
325
+		// Send to other active user (simulation of broadcast)
326
+        String toSend = this.myUser.getAddIP().toString()+":"+this.myUser.getPortTCP()+":"+this.myUser.getPseudo()+":notify";
307 327
         DatagramPacket outPacket =null;
308
-        
309
-        // Send information to usr2
310
-        if(this.myUser.getPortUDPlistening()!=portUDPlistening_remoteUsr2) {
311
-        	outPacket = new DatagramPacket(toSend.getBytes(), toSend.length(),this.myUser.getAddIP(), portUDPlistening_remoteUsr2);
312
-            try {
313
-                dgramSocket.send(outPacket);
314
-            } catch (IOException e) {
315
-                e.printStackTrace();
316
-            }
317
-        }
318
-        
319
-        
320
-        // Send information to usr3
321
-        if(this.myUser.getPortUDPlistening()!=portUDPlistening_remoteUsr3) {
322
-
323
-	        outPacket= new DatagramPacket(toSend.getBytes(), toSend.length(),this.myUser.getAddIP(), portUDPlistening_remoteUsr3);
324
-	        try {
325
-	            dgramSocket.send(outPacket);
326
-	        } catch (IOException e) {
327
-	            e.printStackTrace();
328
-	        }
329
-        }
328
+        int tabBroadcastSize = tabBroadcast.length;
329
+		for(int i=0;i<tabBroadcastSize;i++) {
330
+			if(tabBroadcast[i]!=myUser.getPortUDPlistening()) {
331
+				outPacket = new DatagramPacket(toSend.getBytes(), toSend.length(),this.myUser.getAddIP(), tabBroadcast[i]);
332
+	            try {
333
+	                dgramSocket.send(outPacket);
334
+	            } catch (IOException e) {
335
+	                e.printStackTrace();
336
+	            }
337
+			}
338
+			
339
+		}
330 340
         dgramSocket.close();
331 341
 	}
332 342
 
@@ -342,7 +352,7 @@ public class Controller {
342 352
 			link=new Socket(c.getRemoteUser().getAddIP(),c.getRemoteUser().getPortTCP()/*, InetAddress.getLocalHost() ,myUser.getPortTCP()*/);
343 353
 			c.setSocket(link);
344 354
 			// Sending data for identification (TO REMOVE IF != IP)
345
-			sendMessage(new Msg_Text(myUser.getAddIP(),Integer.toString(myUser.getPortTCP())),c);
355
+			sendInfoProcess(Integer.toString(myUser.getPortTCP()), c); // tell rm session STOP
346 356
 		}catch(IOException e) {
347 357
 			System.out.println("Error linking to TCP server of "+ c.getRemoteUser().getPortTCP());
348 358
 		}
@@ -376,9 +386,10 @@ public class Controller {
376 386
 		}
377 387
 		
378 388
 		// Look for history
389
+		
379 390
 		int nbMessage = c.getMessages().size();
380 391
 		for(int i=0;i<nbMessage;i++) {
381
-			history+="\n"+c.getMessages().get(i).getMessage();
392
+			history+="\n("+c.getMessages().get(i).getDate()+")\n"+c.getMessages().get(i).getAutor().getPseudo()+" : "+c.getMessages().get(i).getMessage();
382 393
 		}			
383 394
 		this.activeChat = c;
384 395
 		
@@ -390,13 +401,13 @@ public class Controller {
390 401
 		this.activeChat = null;
391 402
 	}
392 403
 	public void closeSession(Chat c) {
393
-		sendMessage(new Msg_Text(myUser.getAddIP(),"end"), c); // tell rm session STOP
404
+		sendInfoProcess("end", c); // tell rm session STOP
394 405
 		JOptionPane.showMessageDialog(null ,"Close session with "+c.getRemoteUser().getPseudo()); 
395 406
 		this.myUser.closeChat(c);
396 407
 	}
397 408
 	
398 409
 	public void askToSend(String textMessage){
399
-		sendMessage(new Msg_Text(myUser.getAddIP(),textMessage), this.activeChat);
410
+		sendMessage(new Msg_Text(myUser,textMessage), this.activeChat);
400 411
 	}
401 412
 	public void sendMessage(Message msg,Chat c) {
402 413
 		/*** Init send process ***/
@@ -408,29 +419,57 @@ public class Controller {
408 419
 		}
409 420
 		c.addMessage(msg);
410 421
 
411
-		/*** Gestion des différentes instance de Message ***/
412 422
 		// TODO check if instance of Msg_Text or anything else and threat it given a type
413 423
 		String message = (String) msg.getMessage();
414
-
415
-		// Date l'envoie du message
416
-		DateFormat dateFormat = new SimpleDateFormat("yyyy MM dd HH mm ss");
417
-		Date date=new Date();
418 424
 		
419 425
 	    // Sauvegarde dans la base de données
426
+		DateFormat dateFormat = new SimpleDateFormat("yyyy MM dd HH mm ss");
427
+		Date date=new Date();
420 428
 	    //this.getHistory().saveMessage(getMyUser(), c.getRemoteUser(),message ,dateFormat.format(date));
421 429
 	    
422 430
 	    // Send message
423
-		//out.println(dateFormat.format(date));
424 431
 		out.println(message);
425 432
 		
426 433
 	}
427 434
 	
435
+	public void sendInfoProcess(String msg,Chat c) {
436
+		PrintWriter out=null;
437
+		try {
438
+			out = new PrintWriter(c.getUserSocket().getOutputStream(),true);
439
+		} catch (IOException e) {
440
+			e.printStackTrace();
441
+		}
442
+
443
+		out.println(msg);
444
+		
445
+	}
428 446
 	
429 447
 	public String askNewMessage() {
430 448
 		String message = "";
431 449
 		return message;
432 450
 	}
433 451
 	
452
+	public String [] askUpdateActiveUsers() {
453
+		String[] pseudotab = new String[myUser.getRemoteUsersList().size()];
454
+		int size = myUser.getRemoteUsersList().size();
455
+		for(int i=0; i < size; i++) {
456
+			pseudotab[i] = myUser.getRemoteUsersList().get(i).getPseudo();
457
+		}
458
+		return pseudotab;
459
+	}
460
+	
461
+	public void askForClose() {
462
+		interfaceRunning = false;
463
+		close();
464
+	}
465
+	public void close() {
466
+		if(interfaceRunning) {
467
+			myUser.closeAllChat();
468
+			tcp_connect_thread.close();
469
+			udp_connect_thread.close();
470
+		}
471
+		
472
+	}
434 473
 	
435 474
 	public static void main(String[] args) throws IOException, InterruptedException {
436 475
 		
@@ -440,13 +479,16 @@ public class Controller {
440 479
 		
441 480
 		/*************************       INIT          *******************************/
442 481
 		/** Création des utilisateurs **/
482
+		// LOCAL USER
483
+		Controller ctr1 = new Controller(31011,portUDPlistening_usr1,31021,"Theau",histoire); 
484
+		
443 485
 		// REMOTEUSER_1 - MIKE
444
-		Controller ctr2 = new Controller(31012,portUDPlistening_remoteUsr2,31022,"Mike",histoire); 
486
+		Controller ctr2 = new Controller(31012,portUDPlistening_remoteUsr2,31022,"Leonie",histoire);
487
+		
445 488
 		// REMOTEUSER_2 - ALICE
446
-		Controller ctr3 = new Controller(31013,portUDPlistening_remoteUsr3,31023,"Alice",histoire); 
447
-		// LOCAL USER
448
-		Controller ctr1 = new Controller(31011,31001,31021,histoire); 
449
-
489
+		Controller ctr3 = new Controller(31013,portUDPlistening_remoteUsr3,31023,"Alexandre",histoire); 
490
+		
491
+		
450 492
 		
451 493
 		
452 494
 		/*********************** 		TEST AREA  				********************/
@@ -476,17 +518,12 @@ public class Controller {
476 518
 		
477 519
 		/*************************       LOOP          *******************************/
478 520
 
479
-		/** Création de l'interface graphique **/ 
480
-		ctr1.interfaceRunning =true;
481
-		ctr1.view=Interface.createAndShowGUI(ctr1);	
482
-		ctr2.interfaceRunning =true;
483
-		ctr2.view=Interface.createAndShowGUI(ctr2);	
484
-		ctr3.interfaceRunning =true;
485
-		ctr3.view=Interface.createAndShowGUI(ctr3);	
521
+	
486 522
 		
487 523
 		/** loop **/
488
-		while(ctr1.interfaceRunning) {
489
-			//ctr1.view.update(info)
524
+		Boolean running = ctr1.interfaceRunning || ctr2.interfaceRunning || ctr3.interfaceRunning;
525
+		while(running) {
526
+			running = ctr1.interfaceRunning || ctr2.interfaceRunning || ctr3.interfaceRunning;
490 527
 		}
491 528
 		
492 529
 		System.out.println("Fin de la boucle");
@@ -497,17 +534,14 @@ public class Controller {
497 534
 		
498 535
 		/** Close thread and socket **/
499 536
 		// REMOTEUSER_1 - MIKE
500
-		ctr2.myUser.closeAllChat();
501
-		ctr2.tcp_connect_thread.close();
502
-		ctr2.udp_connect_thread.close();
537
+		ctr2.close();
538
+		
503 539
 		// REMOTEUSER_2 - ALICE
504
-		ctr3.myUser.closeAllChat();
505
-		ctr3.tcp_connect_thread.close();
506
-		ctr3.udp_connect_thread.close();
540
+		ctr3.close();
541
+		
507 542
 		// LOCAL USER
508
-		ctr1.myUser.closeAllChat();
509
-		ctr1.tcp_connect_thread.close();
510
-		ctr1.udp_connect_thread.close();
543
+		ctr1.close();
544
+		
511 545
 		// AFFICHAGE
512 546
 		System.out.println("end program");
513 547
 		JOptionPane.showMessageDialog(null ,"END");

+ 1
- 1
Application/Clavardage/src/controller/Historique.java View File

@@ -91,7 +91,7 @@ public class Historique {
91 91
 		int	nb_changed_rows = stat.executeUpdate("USE tp_servlet_003");
92 92
 
93 93
 		try {
94
-		nb_changed_rows = stat.executeUpdate("CREATE TABLE chat ( user_IPcode1 INTEGER, user_IPcode2 INTEGER ,Message VARCHAR(450) ,temps VARCHAR(450) )");
94
+			nb_changed_rows = stat.executeUpdate("CREATE TABLE chat ( user_IPcode1 INTEGER, user_IPcode2 INTEGER ,Message VARCHAR(450) ,temps VARCHAR(450) )");
95 95
 		}catch (Exception e) {
96 96
 			e.printStackTrace();
97 97
 

+ 19
- 21
Application/Clavardage/src/controller/ListeningThreadTCPChat.java View File

@@ -1,18 +1,13 @@
1 1
 package controller;
2 2
 
3 3
 import model.Chat;
4
-import model.LocalUser;
5 4
 import model.Msg_Text;
6 5
 import model.RemoteUser;
7 6
 
8 7
 import java.io.BufferedReader;
9 8
 import java.io.IOException;
10 9
 import java.io.InputStreamReader;
11
-import java.io.PrintWriter;
12
-import java.net.InetAddress;
13 10
 import java.net.Socket;
14
-import java.text.DateFormat;
15
-import java.text.SimpleDateFormat;
16 11
 import java.util.Calendar;
17 12
 import java.util.Date;
18 13
 
@@ -93,28 +88,31 @@ public class ListeningThreadTCPChat extends ListeningThread{
93 88
 		    	else {
94 89
 		    		c=this.controller.openSession(rm);
95 90
 		    	}
91
+		    	
92
+		    	 /*** listening tcp message from rm until session is close ***/
93
+				
94
+				try {
95
+					String msgToprint;
96
+					while (!(input=in.readLine()).equals("end")/* && c.getActive()*/) {
97
+						
98
+						System.out.println("("+this.controller.myUser.getPseudo()+") recoit => "+rm.getPseudo()+" : "+input);
99
+						Msg_Text message = new Msg_Text(rm,input);
100
+						c.addMessage(message);
101
+						if(controller.activeChat==c) {
102
+							controller.view.notifyNewMessage("("+message.getDate()+")\n"+c.getRemoteUser().getPseudo()+" : "+input);
103
+						}
104
+					}
105
+				} catch (IOException e) {
106
+					// TODO Auto-generated catch block
107
+					e.printStackTrace();
108
+				}
96 109
 		    }
97 110
 		    else {
98 111
 		    	System.out.println("("+this.controller.myUser.getPseudo()+") Remote User unidentifiable => CLOSING CONNECTION");
99 112
 		    }
100 113
 		   
101 114
 		    
102
-		    /*** listening tcp message from rm until session is close ***/
103
-			
104
-			try {
105
-				System.out.println("("+this.controller.myUser.getPseudo()+") WAIT FOR NEW MESSAGE FROM "+rm.getPseudo());
106
-
107
-				while (!(input=in.readLine()).equals("end")/* && c.getActive()*/) {
108
-					System.out.println("("+this.controller.myUser.getPseudo()+") recoit => "+rm.getPseudo()+" : "+input);
109
-					c.addMessage(new Msg_Text(rm.getAddIP(),input));
110
-					// TODO Prévenir l'interface de la réception d'un nouveau message
111
-					controller.view.notifyNewMessage();
112
-
113
-				}
114
-			} catch (IOException e) {
115
-				// TODO Auto-generated catch block
116
-				e.printStackTrace();
117
-			}
115
+		   
118 116
 
119 117
 			
120 118
 

+ 1
- 4
Application/Clavardage/src/controller/ListeningThreadTCPConnection.java View File

@@ -1,7 +1,5 @@
1 1
 package controller;
2 2
 
3
-import model.LocalUser;
4
-
5 3
 import java.io.IOException;
6 4
 import java.net.ServerSocket;
7 5
 import java.net.Socket;
@@ -51,9 +49,8 @@ public class ListeningThreadTCPConnection extends ListeningThread{
51 49
 			System.out.println("("+this.controller.myUser.getPseudo()+") Server is not listening on port "+this.controller.myUser.getPortTCP());
52 50
 			e.printStackTrace();
53 51
 		}
54
-		// TODO changer le true
55 52
 		while(true) {
56
-			System.out.println("("+this.controller.myUser.getPseudo()+") WAITING FOR NEW CONNECTION");
53
+			System.out.println("("+this.controller.myUser.getPseudo()+") TCP Server waiting for new connection ...");
57 54
 
58 55
 			try {
59 56
 				this.accept(servSocket);

+ 4
- 1
Application/Clavardage/src/controller/ListeningThreadUDP.java View File

@@ -86,7 +86,7 @@ public class ListeningThreadUDP extends ListeningThread{
86 86
 			else { 
87 87
 				try {
88 88
 					// On récupère l'adresse IP et le port TCP de l'utilisateur distant et ajout à la liste de l'utilisateur utilisant ce thread 
89
-					this.controller.myUser.addRemoteUser(InetAddress.getByName(tabMsg[0].split("/")[1]),Integer.parseInt(tabMsg[1]),tabMsg[2]);
89
+					controller.myUser.addRemoteUser(InetAddress.getByName(tabMsg[0].split("/")[1]),Integer.parseInt(tabMsg[1]),tabMsg[2]);
90 90
 				} catch (NumberFormatException e) {
91 91
 					// TODO Auto-generated catch block
92 92
 					e.printStackTrace();
@@ -94,6 +94,9 @@ public class ListeningThreadUDP extends ListeningThread{
94 94
 					// TODO Auto-generated catch block
95 95
 					e.printStackTrace();
96 96
 				}
97
+				if(controller.interfaceRunning) {
98
+					controller.view.updateActiveUsers();
99
+				}
97 100
 			}
98 101
 			
99 102
 			

+ 2
- 2
Application/Clavardage/src/model/LocalUser.java View File

@@ -69,11 +69,11 @@ public class LocalUser extends User{
69 69
 		RemoteUser tmpRemoteUser = new RemoteUser(remoteUserPseudo,remoteUserIP,remoteUserPortTCP);
70 70
 		int index = this.remoteUsersList.indexOf(tmpRemoteUser);
71 71
 		if(index!=-1) {
72
-			System.out.println("("+this.pseudo+") - "+"MAJ, IP(port) of user : "+remoteUserPseudo+" => "+remoteUserIP+"("+remoteUserPortTCP+")");
72
+			System.out.println("("+this.pseudo+") "+"MAJ, IP(port) : "+remoteUserPseudo+" => "+remoteUserIP+"("+remoteUserPortTCP+")");
73 73
 			this.remoteUsersList.set(index,tmpRemoteUser);
74 74
 		}
75 75
 		else {
76
-			System.out.println("("+this.pseudo+") - "+"Add new user IP(port) of user : "+remoteUserPseudo+" => "+remoteUserIP+"("+remoteUserPortTCP+")");
76
+			System.out.println("("+this.pseudo+") "+"Add new user IP(port) : "+remoteUserPseudo+" => "+remoteUserIP+"("+remoteUserPortTCP+")");
77 77
 			this.remoteUsersList.add(tmpRemoteUser);
78 78
 		}
79 79
 	}

+ 10
- 14
Application/Clavardage/src/model/Message.java View File

@@ -8,9 +8,8 @@ import java.text.SimpleDateFormat;
8 8
 public abstract class Message {
9 9
 	
10 10
 	/*** ATTRIBUTS ***/
11
-	private Date date;
12
-	private InetAddress autorIP;
13
-	
11
+	private String date;
12
+	private User autor;
14 13
 	/**
15 14
 	 *  Constructor of Message
16 15
 	 * @parametres
@@ -20,25 +19,22 @@ public abstract class Message {
20 19
 	 * 		
21 20
 	 * </p>
22 21
 	 */
23
-	public Message(InetAddress autorIP) {
24
-		this.autorIP = autorIP;
22
+	public Message(User autor) {
23
+		this.autor = autor;
25 24
 		DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
26
-		this.date = new Date();
25
+		this.date = dateFormat.format(new Date());
27 26
 	}
28 27
 	/*** GETTERS ***/
29
-	public Date getDate() {
28
+	public String getDate() {
30 29
 		return date;
31 30
 	}
32
-	public InetAddress getAutorIP() {
33
-		return autorIP;
31
+	public User getAutor() {
32
+		return autor;
34 33
 	}
35 34
 	
36 35
 	/*** SETTERS ***/
37
-	public void setDate(Date date) {
38
-		this.date = date;
39
-	}
40
-	public void setAutorIP(InetAddress autorIP) {
41
-		this.autorIP = autorIP;
36
+	public void setAutorIP(User autor) {
37
+		this.autor = autor;
42 38
 	}
43 39
 	
44 40
 	

+ 2
- 2
Application/Clavardage/src/model/Msg_Text.java View File

@@ -7,8 +7,8 @@ public class Msg_Text extends Message{
7 7
 	/*** ATTRIBUT ***/
8 8
 	private String text;
9 9
 	
10
-	public Msg_Text(InetAddress autorIP,String text) {
11
-		super(autorIP);
10
+	public Msg_Text(User autor,String text) {
11
+		super(autor);
12 12
 		this.text = text;
13 13
 	}
14 14
 

+ 79
- 41
Application/Clavardage/src/view/Interface.java View File

@@ -6,7 +6,6 @@ import java.awt.event.*;
6 6
 import java.io.IOException;
7 7
 
8 8
 import controller.Controller;
9
-import model.RemoteUser;
10 9
 
11 10
 public class Interface extends JFrame implements ActionListener, WindowListener {
12 11
 	
@@ -18,14 +17,15 @@ public class Interface extends JFrame implements ActionListener, WindowListener
18 17
 	public Controller controller;
19 18
 		
20 19
 	public JLabel Pseudolabel;
21
-	public JTextField PseudotextField;
20
+	public JLabel ChangePseudolabel;
21
+	public JTextField ChangePseudotextField;
22 22
 	
23 23
 	public JTextArea MessagetextArea;
24 24
 	public JTextField MessagetextField;
25 25
 	public JScrollPane scrollpane;
26 26
 	
27 27
 	public JButton RemoteUserButton;
28
-	public JComboBox RemoteUserbox;
28
+	public JComboBox<String> RemoteUserbox;
29 29
 	public JButton CloseConversationButton;
30 30
 	
31 31
 	//Specifies the look and feel to use. Valid values:
@@ -47,53 +47,89 @@ public class Interface extends JFrame implements ActionListener, WindowListener
47 47
 	public Component createComponents() {
48 48
 		
49 49
 		//Pseudo setup
50
-		PseudotextField = new JTextField();        
51
-		PseudotextField.setColumns(10);
52
-		PseudotextField.addActionListener(this);
53
-		Pseudolabel = new JLabel("Your current username is: " + controller.getMyUser().getPseudo());
54
-		Pseudolabel.setLabelFor(PseudotextField);
50
+		JPanel changePseudoPanel = new JPanel(new GridLayout(1, 0));
51
+		ChangePseudolabel = new JLabel("Change nickname : ");
52
+		changePseudoPanel.add(ChangePseudolabel);
53
+		ChangePseudotextField = new JTextField();        
54
+		ChangePseudotextField.setColumns(10);
55
+		ChangePseudotextField.addActionListener(this);
56
+		changePseudoPanel.add(ChangePseudotextField);
57
+		
58
+		Pseudolabel = new JLabel("Nickname : "+controller.getMyUser().getPseudo());
59
+		Pseudolabel.setLabelFor(ChangePseudotextField);
60
+		
61
+		
55 62
 		
56 63
 		//Remote user list setup
57
-		RemoteUserButton = new JButton("Click to get Remote User list");          
64
+		RemoteUserButton = new JButton("Start session");          
58 65
 		RemoteUserButton.addActionListener(this);
66
+		
67
+		
68
+		// Remote user list
59 69
 		//Converts the Userlist to a Pseudotab for treatment in actionPerformed
60
-		String[] pseudotab = new String[controller.getMyUser().getRemoteUsersList().size()];
61
-		for(int i=0; i < controller.getMyUser().getRemoteUsersList().size(); i++) {
62
-			pseudotab[i] = "(" + Integer.toString(i) + "): " + controller.getMyUser().getRemoteUsersList().get(i).getPseudo();
63
-		}
64
-		RemoteUserbox = new JComboBox(pseudotab);
70
+		String[] pseudotab = controller.askUpdateActiveUsers();
71
+		RemoteUserbox = new JComboBox<String>(pseudotab);
65 72
 		RemoteUserbox.setEditable(true);
66 73
 		RemoteUserbox.addActionListener(this);
67 74
 		RemoteUserbox.setVisible(false);
68
-		CloseConversationButton = new JButton("Click to close active chat");
75
+		
76
+		// Close session
77
+		CloseConversationButton = new JButton("Close session");
69 78
 		CloseConversationButton.addActionListener(this);
70 79
 		CloseConversationButton.setVisible(false);
71 80
 		
81
+		JPanel userListsPanel = new JPanel(new GridLayout(1, 0));
82
+	
83
+		userListsPanel.add(RemoteUserButton);
84
+		userListsPanel.add(RemoteUserbox);
85
+		userListsPanel.add(CloseConversationButton);
86
+
87
+		
72 88
 	    //Messages setup
73 89
 		MessagetextField = new JTextField();
74 90
 		MessagetextField.setColumns(10);
75 91
 		MessagetextField.addActionListener(this);
76
-		MessagetextArea = new JTextArea("Message field: ");
92
+		MessagetextArea = new JTextArea("Chat");
77 93
 		scrollpane = new JScrollPane();
78 94
 		scrollpane.getViewport().add(MessagetextArea);
79 95
 		scrollpane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
96
+		scrollpane.setPreferredSize(new Dimension(600,60));
80 97
 		MessagetextField.setVisible(false);
81 98
 		MessagetextArea.setVisible(false);
82 99
 		scrollpane.setVisible(false);
100
+		// Create a placeholder on JTextField
101
+		MessagetextField.addFocusListener(new FocusListener() {
102
+		       @Override
103
+		       public void focusGained(FocusEvent e) {
104
+		           if (MessagetextField.getText().equals("Your message")) {
105
+		        	   MessagetextField.setText("");
106
+		        	   MessagetextField.setForeground(Color.BLACK);
107
+		           }
108
+		       }
109
+		       @Override
110
+		       public void focusLost(FocusEvent e) {
111
+		           if (MessagetextField.getText().isEmpty()) {
112
+		        	   MessagetextField.setForeground(Color.GRAY);
113
+		        	   MessagetextField.setText("Your message");
114
+		           }
115
+		       }
116
+		       });
117
+
83 118
 		
84 119
 		/*
85 120
 		* An easy way to put space between a top-level container
86 121
 		* and its contents is to put the contents in a JPanel
87 122
 		* that has an "empty" border.
88 123
 		*/
89
-		JPanel pane = new JPanel(new GridLayout(0, 2));
90
-		pane.add(Pseudolabel);
91
-		pane.add(PseudotextField);
92
-		pane.add(RemoteUserButton);
93
-		pane.add(RemoteUserbox);
94
-		pane.add(scrollpane);
95
-		pane.add(MessagetextField);
96
-		pane.add(CloseConversationButton);
124
+		JPanel header = new JPanel(new GridLayout(0, 1));
125
+		header.add(Pseudolabel);
126
+		header.add(changePseudoPanel);
127
+		header.add(userListsPanel);
128
+		
129
+		JPanel pane = new JPanel(new BorderLayout());
130
+		pane.add(header,BorderLayout.NORTH);
131
+		pane.add(scrollpane,BorderLayout.CENTER);
132
+		pane.add(MessagetextField,BorderLayout.SOUTH);
97 133
 		pane.setBorder(BorderFactory.createEmptyBorder(
98 134
 									30, //top
99 135
 									30, //left
@@ -105,8 +141,8 @@ public class Interface extends JFrame implements ActionListener, WindowListener
105 141
 	}
106 142
 	
107 143
 	public void actionPerformed(ActionEvent e) {
108
-		if(e.getSource() == PseudotextField) {                //Changing pseudo
109
-			String Textinput = PseudotextField.getText();
144
+		if(e.getSource() == ChangePseudotextField) {                //Changing pseudo
145
+			String Textinput = ChangePseudotextField.getText();
110 146
 			Pseudolabel.setText("Your current username is: " + Textinput);
111 147
 			
112 148
 			try {
@@ -117,7 +153,7 @@ public class Interface extends JFrame implements ActionListener, WindowListener
117 153
 			}
118 154
 		}else if(e.getSource() == MessagetextField){          //Messages
119 155
 			String Textinput = MessagetextField.getText();
120
-			MessagetextArea.setText(MessagetextArea.getText() + controller.getMyUser().getPseudo() + ": " + Textinput + "\n");
156
+			MessagetextArea.setText(MessagetextArea.getText() + "\n" + controller.getMyUser().getPseudo() + " : " + Textinput );
121 157
 			MessagetextField.setText("");
122 158
 			controller.askToSend(Textinput); // ask to send to controller 
123 159
 			
@@ -129,15 +165,16 @@ public class Interface extends JFrame implements ActionListener, WindowListener
129 165
 			scrollpane.setVisible(false);
130 166
 			MessagetextField.setVisible(false);
131 167
 			CloseConversationButton.setVisible(false);
132
-		}else { // Choice in remote user list
168
+		}else if(e.getSource() == RemoteUserbox){ // Choice in remote user list
133 169
 			
134
-			JComboBox cb = (JComboBox)e.getSource();          //Casts obscurs pour récupérer le numéro du user dans la liste
135
-			int selectedUsernb = Integer.parseInt(String.valueOf(((String) cb.getSelectedItem()).charAt(1)));
170
+			//JComboBox cb = (JComboBox)e.getSource();          //Casts obscurs pour récupérer le numéro du user dans la liste
171
+			int selectedUsernb = RemoteUserbox.getSelectedIndex();
172
+					//String.valueOf(((String) cb.getSelectedItem()).charAt(1)));
136 173
 
137 174
 			// start or switch chat => get history 
138 175
 			String history = controller.askOpenSession(selectedUsernb);
139 176
 			// display it
140
-			MessagetextArea.setText("Message:"+history);
177
+			MessagetextArea.setText(history);
141 178
 			MessagetextField.setVisible(true);
142 179
 			scrollpane.setVisible(true);
143 180
 			MessagetextArea.setVisible(true);
@@ -198,14 +235,15 @@ public class Interface extends JFrame implements ActionListener, WindowListener
198 235
 		Interface app = new Interface(controller);
199 236
 		Component contents = app.createComponents();
200 237
 		frame.getContentPane().add(contents, BorderLayout.CENTER);
238
+		frame.setPreferredSize(new Dimension(400,300));
201 239
 		
202 240
 		//Ends all running background tasks upon closing the window
203 241
 		frame.addWindowListener(new java.awt.event.WindowAdapter() {
204 242
 		    @Override
205 243
 		    public void windowClosing(java.awt.event.WindowEvent windowEvent) {
206
-		        System.out.println("Window has been closed");
207
-		        app.controller.interfaceRunning = false;
208
-		        System.exit(0);
244
+		        System.out.println("("+controller.getMyUser().getPseudo()+") Window has been closed");
245
+		        controller.askForClose();
246
+		        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
209 247
 		    }
210 248
 		});	
211 249
 		
@@ -225,15 +263,15 @@ public class Interface extends JFrame implements ActionListener, WindowListener
225 263
 	public void windowClosing(WindowEvent e) {}
226 264
 
227 265
 	
228
-	public void notifyNewMessage() {
229
-		String newMessage = controller.askNewMessage();
230
-		//TOCHECK maybe better way to do it
231
-		if(newMessage!="") {
232
-			//TODO afficher le message
233
-			
234
-		}
266
+	public void notifyNewMessage(String msg) {
267
+		MessagetextArea.setText(MessagetextArea.getText() + "\n" + msg);
235 268
 		
236 269
 	}
270
+	
271
+	public void updateActiveUsers() {
272
+		DefaultComboBoxModel<String> model = new DefaultComboBoxModel<>( controller.askUpdateActiveUsers() );
273
+		RemoteUserbox.setModel( model );
274
+	}
237 275
 		/*
238 276
 	public static void main(String[] args) throws IOException {
239 277
 		//Schedule a job for the event-dispatching thread:

Loading…
Cancel
Save