· 4 years ago · Jan 15, 2021, 02:02 PM
1>>>>>>>>>>>>>>>>>>>>>>>>>>Download.java>>>>>>>>>>>>>>>>>>>>>>>>>>
2
3package com.socket;
4
5import com.ui.ChatFrame;
6import java.io.*;
7import java.net.*;
8import java.util.logging.Level;
9import java.util.logging.Logger;
10
11public class Download implements Runnable{
12
13 public ServerSocket server;
14 public Socket socket;
15 public int port;
16 public String saveTo = "";
17 public InputStream In;
18 public FileOutputStream Out;
19 public ChatFrame ui;
20
21 public Download(String saveTo, ChatFrame ui){
22 try {
23 server = new ServerSocket(0);
24 port = server.getLocalPort();
25 this.saveTo = saveTo;
26 this.ui = ui;
27 }
28 catch (IOException ex) {
29 System.out.println("Exception [Download : Download(...)]");
30 }
31 }
32
33 @Override
34 public void run() {
35 try {
36 socket = server.accept();
37 System.out.println("Download : "+socket.getRemoteSocketAddress());
38
39 In = socket.getInputStream();
40 Out = new FileOutputStream(saveTo);
41
42 byte[] buffer = new byte[1024];
43 int count;
44
45 while((count = In.read(buffer)) >= 0){
46 Out.write(buffer, 0, count);
47 }
48
49 Out.flush();
50
51 ui.jTextArea1.append("[Application > Me] : Download complete\n");
52
53 if(Out != null){ Out.close(); }
54 if(In != null){ In.close(); }
55 if(socket != null){ socket.close(); }
56 }
57 catch (Exception ex) {
58 System.out.println("Exception [Download : run(...)]");
59 }
60 }
61}
62
63
64
65>>>>>>>>>>>>>>>>>>>>>>>>>>History.java>>>>>>>>>>>>>>>>>>>>>>>>>>
66
67package com.socket;
68
69import java.io.*;
70import java.util.ArrayList;
71import javax.xml.parsers.DocumentBuilder;
72import javax.xml.parsers.DocumentBuilderFactory;
73import javax.xml.transform.Transformer;
74import javax.xml.transform.TransformerFactory;
75import javax.xml.transform.dom.DOMSource;
76import javax.xml.transform.stream.StreamResult;
77import org.w3c.dom.*;
78import com.ui.HistoryFrame;
79import javax.swing.table.DefaultTableModel;
80
81public class History {
82
83 public String filePath;
84
85 public History(String filePath){
86 this.filePath = filePath;
87 }
88
89 public void addMessage(Message msg, String time){
90
91 try {
92 DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
93 DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
94 Document doc = docBuilder.parse(filePath);
95
96 Node data = doc.getFirstChild();
97
98 Element message = doc.createElement("message");
99 Element _sender = doc.createElement("sender"); _sender.setTextContent(msg.sender);
100 Element _content = doc.createElement("content"); _content.setTextContent(msg.content);
101 Element _recipient = doc.createElement("recipient"); _recipient.setTextContent(msg.recipient);
102 Element _time = doc.createElement("time"); _time.setTextContent(time);
103
104 message.appendChild(_sender); message.appendChild(_content); message.appendChild(_recipient); message.appendChild(_time);
105 data.appendChild(message);
106
107 TransformerFactory transformerFactory = TransformerFactory.newInstance();
108 Transformer transformer = transformerFactory.newTransformer();
109 DOMSource source = new DOMSource(doc);
110 StreamResult result = new StreamResult(new File(filePath));
111 transformer.transform(source, result);
112
113 }
114 catch(Exception ex){
115 System.out.println("Exceptionmodify xml");
116 }
117 }
118
119 public void FillTable(HistoryFrame frame){
120
121 DefaultTableModel model = (DefaultTableModel) frame.jTable1.getModel();
122
123 try{
124 File fXmlFile = new File(filePath);
125 DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
126 DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
127 Document doc = dBuilder.parse(fXmlFile);
128 doc.getDocumentElement().normalize();
129
130 NodeList nList = doc.getElementsByTagName("message");
131
132 for (int temp = 0; temp < nList.getLength(); temp++) {
133 Node nNode = nList.item(temp);
134 if (nNode.getNodeType() == Node.ELEMENT_NODE) {
135 Element eElement = (Element) nNode;
136 model.addRow(new Object[]{getTagValue("sender", eElement), getTagValue("content", eElement), getTagValue("recipient", eElement), getTagValue("time", eElement)});
137 }
138 }
139 }
140 catch(Exception ex){
141 System.out.println("Filling Exception");
142 }
143 }
144
145 public static String getTagValue(String sTag, Element eElement) {
146 NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();
147 Node nValue = (Node) nlList.item(0);
148 return nValue.getNodeValue();
149 }
150}
151
152>>>>>>>>>>>>>>>>>>>>>>>>>>Message.java>>>>>>>>>>>>>>>>>>>>>>>>>>
153package com.socket;
154
155import java.io.Serializable;
156
157public class Message implements Serializable{
158
159 private static final long serialVersionUID = 1L;
160 public String type, sender, content, recipient;
161
162 public Message(String type, String sender, String content, String recipient){
163 this.type = type; this.sender = sender; this.content = content; this.recipient = recipient;
164 }
165
166 @Override
167 public String toString(){
168 return "{type='"+type+"', sender='"+sender+"', content='"+content+"', recipient='"+recipient+"'}";
169 }
170}
171
172
173>>>>>>>>>>>>>>>>>>>>>>>>>>Socketclient.java>>>>>>>>>>>>>>>>>>>>>>>>>>
174package com.socket;
175
176import com.ui.ChatFrame;
177import java.io.*;
178import java.net.*;
179import java.util.Date;
180import javax.swing.JFileChooser;
181import javax.swing.JOptionPane;
182import javax.swing.table.DefaultTableModel;
183
184public class SocketClient implements Runnable{
185
186 public int port;
187 public String serverAddr;
188 public Socket socket;
189 public ChatFrame ui;
190 public ObjectInputStream In;
191 public ObjectOutputStream Out;
192 public History hist;
193
194 public SocketClient(ChatFrame frame) throws IOException{
195 ui = frame; this.serverAddr = ui.serverAddr; this.port = ui.port;
196 socket = new Socket(InetAddress.getByName(serverAddr), port);
197
198 Out = new ObjectOutputStream(socket.getOutputStream());
199 Out.flush();
200 In = new ObjectInputStream(socket.getInputStream());
201
202 hist = ui.hist;
203 }
204
205 @Override
206 public void run() {
207 boolean keepRunning = true;
208 while(keepRunning){
209 try {
210 Message msg = (Message) In.readObject();
211 System.out.println("Incoming : "+msg.toString());
212
213 if(msg.type.equals("message")){
214 if(msg.recipient.equals(ui.username)){
215 ui.jTextArea1.append("["+msg.sender +" > Me] : " + msg.content + "\n");
216 }
217 else{
218 ui.jTextArea1.append("["+ msg.sender +" > "+ msg.recipient +"] : " + msg.content + "\n");
219 }
220
221 if(!msg.content.equals(".bye") && !msg.sender.equals(ui.username)){
222 String msgTime = (new Date()).toString();
223
224 try{
225 hist.addMessage(msg, msgTime);
226 DefaultTableModel table = (DefaultTableModel) ui.historyFrame.jTable1.getModel();
227 table.addRow(new Object[]{msg.sender, msg.content, "Me", msgTime});
228 }
229 catch(Exception ex){}
230 }
231 }
232 else if(msg.type.equals("login")){
233 if(msg.content.equals("TRUE")){
234 ui.jButton2.setEnabled(false); ui.jButton3.setEnabled(false);
235 ui.jButton4.setEnabled(true); ui.jButton5.setEnabled(true);
236 ui.jTextArea1.append("[SERVER > Me] : Login Successful\n");
237 ui.jTextField3.setEnabled(false); ui.jPasswordField1.setEnabled(false);
238 }
239 else{
240 ui.jTextArea1.append("[SERVER > Me] : Login Failed\n");
241 }
242 }
243 else if(msg.type.equals("test")){
244 ui.jButton1.setEnabled(false);
245 ui.jButton2.setEnabled(true); ui.jButton3.setEnabled(true);
246 ui.jTextField3.setEnabled(true); ui.jPasswordField1.setEnabled(true);
247 ui.jTextField1.setEditable(false); ui.jTextField2.setEditable(false);
248 ui.jButton7.setEnabled(true);
249 }
250 else if(msg.type.equals("newuser")){
251 if(!msg.content.equals(ui.username)){
252 boolean exists = false;
253 for(int i = 0; i < ui.model.getSize(); i++){
254 if(ui.model.getElementAt(i).equals(msg.content)){
255 exists = true; break;
256 }
257 }
258 if(!exists){ ui.model.addElement(msg.content); }
259 }
260 }
261 else if(msg.type.equals("signup")){
262 if(msg.content.equals("TRUE")){
263 ui.jButton2.setEnabled(false); ui.jButton3.setEnabled(false);
264 ui.jButton4.setEnabled(true); ui.jButton5.setEnabled(true);
265 ui.jTextArea1.append("[SERVER > Me] : Singup Successful\n");
266 }
267 else{
268 ui.jTextArea1.append("[SERVER > Me] : Signup Failed\n");
269 }
270 }
271 else if(msg.type.equals("signout")){
272 if(msg.content.equals(ui.username)){
273 ui.jTextArea1.append("["+ msg.sender +" > Me] : Bye\n");
274 ui.jButton1.setEnabled(true); ui.jButton4.setEnabled(false);
275 ui.jTextField1.setEditable(true); ui.jTextField2.setEditable(true);
276
277 for(int i = 1; i < ui.model.size(); i++){
278 ui.model.removeElementAt(i);
279 }
280
281 ui.clientThread.stop();
282 }
283 else{
284 ui.model.removeElement(msg.content);
285 ui.jTextArea1.append("["+ msg.sender +" > All] : "+ msg.content +" has signed out\n");
286 }
287 }
288 else if(msg.type.equals("upload_req")){
289
290 if(JOptionPane.showConfirmDialog(ui, ("Accept '"+msg.content+"' from "+msg.sender+" ?")) == 0){
291
292 JFileChooser jf = new JFileChooser();
293 jf.setSelectedFile(new File(msg.content));
294 int returnVal = jf.showSaveDialog(ui);
295
296 String saveTo = jf.getSelectedFile().getPath();
297 if(saveTo != null && returnVal == JFileChooser.APPROVE_OPTION){
298 Download dwn = new Download(saveTo, ui);
299 Thread t = new Thread(dwn);
300 t.start();
301 //send(new Message("upload_res", (""+InetAddress.getLocalHost().getHostAddress()), (""+dwn.port), msg.sender));
302 send(new Message("upload_res", ui.username, (""+dwn.port), msg.sender));
303 }
304 else{
305 send(new Message("upload_res", ui.username, "NO", msg.sender));
306 }
307 }
308 else{
309 send(new Message("upload_res", ui.username, "NO", msg.sender));
310 }
311 }
312 else if(msg.type.equals("upload_res")){
313 if(!msg.content.equals("NO")){
314 int port = Integer.parseInt(msg.content);
315 String addr = msg.sender;
316
317 ui.jButton5.setEnabled(false); ui.jButton6.setEnabled(false);
318 Upload upl = new Upload(addr, port, ui.file, ui);
319 Thread t = new Thread(upl);
320 t.start();
321 }
322 else{
323 ui.jTextArea1.append("[SERVER > Me] : "+msg.sender+" rejected file request\n");
324 }
325 }
326 else{
327 ui.jTextArea1.append("[SERVER > Me] : Unknown message type\n");
328 }
329 }
330 catch(Exception ex) {
331 keepRunning = false;
332 ui.jTextArea1.append("[Application > Me] : Connection Failure\n");
333 ui.jButton1.setEnabled(true); ui.jTextField1.setEditable(true); ui.jTextField2.setEditable(true);
334 ui.jButton4.setEnabled(false); ui.jButton5.setEnabled(false); ui.jButton5.setEnabled(false);
335
336 for(int i = 1; i < ui.model.size(); i++){
337 ui.model.removeElementAt(i);
338 }
339
340 ui.clientThread.stop();
341
342 System.out.println("Exception SocketClient run()");
343 ex.printStackTrace();
344 }
345 }
346 }
347
348 public void send(Message msg){
349 try {
350 Out.writeObject(msg);
351 Out.flush();
352 System.out.println("Outgoing : "+msg.toString());
353
354 if(msg.type.equals("message") && !msg.content.equals(".bye")){
355 String msgTime = (new Date()).toString();
356 try{
357 hist.addMessage(msg, msgTime);
358 DefaultTableModel table = (DefaultTableModel) ui.historyFrame.jTable1.getModel();
359 table.addRow(new Object[]{"Me", msg.content, msg.recipient, msgTime});
360 }
361 catch(Exception ex){}
362 }
363 }
364 catch (IOException ex) {
365 System.out.println("Exception SocketClient send()");
366 }
367 }
368
369 public void closeThread(Thread t){
370 t = null;
371 }
372}
373
374>>>>>>>>>>>>>>>>>>>>>>>>>>Upload.java>>>>>>>>>>>>>>>>>>>>>>>>>>
375package com.socket;
376
377import com.ui.ChatFrame;
378import java.io.*;
379import java.net.*;
380import java.util.logging.Level;
381import java.util.logging.Logger;
382
383public class Upload implements Runnable{
384
385 public String addr;
386 public int port;
387 public Socket socket;
388 public FileInputStream In;
389 public OutputStream Out;
390 public File file;
391 public ChatFrame ui;
392
393 public Upload(String addr, int port, File filepath, ChatFrame frame){
394 super();
395 try {
396 file = filepath; ui = frame;
397 socket = new Socket(InetAddress.getByName(addr), port);
398 Out = socket.getOutputStream();
399 In = new FileInputStream(filepath);
400 }
401 catch (Exception ex) {
402 System.out.println("Exception [Upload : Upload(...)]");
403 }
404 }
405
406 @Override
407 public void run() {
408 try {
409 byte[] buffer = new byte[1024];
410 int count;
411
412 while((count = In.read(buffer)) >= 0){
413 Out.write(buffer, 0, count);
414 }
415 Out.flush();
416
417 ui.jTextArea1.append("[Applcation > Me] : File upload complete\n");
418 ui.jButton5.setEnabled(true); ui.jButton6.setEnabled(true);
419 ui.jTextField5.setVisible(true);
420
421 if(In != null){ In.close(); }
422 if(Out != null){ Out.close(); }
423 if(socket != null){ socket.close(); }
424 }
425 catch (Exception ex) {
426 System.out.println("Exception [Upload : run()]");
427 ex.printStackTrace();
428 }
429 }
430
431}
432>>>>>>>>>>>>>>>>>>>>>>>>>>HistoryFrame.java>>>>>>>>>>>>>>>>>>>>>>>>>>swing
433package com.ui;
434
435import com.socket.History;
436
437public class HistoryFrame extends javax.swing.JFrame {
438
439 public History hist;
440
441 public HistoryFrame() {
442 initComponents();
443 }
444
445 public HistoryFrame(History hist){
446 initComponents();
447 this.hist = hist;
448 hist.FillTable(this);
449 }
450
451 @SuppressWarnings("unchecked")
452 // <editor-fold defaultstate="collapsed" desc="Generated Code">
453 private void initComponents() {
454
455 jLabel1 = new javax.swing.JLabel();
456 jScrollPane1 = new javax.swing.JScrollPane();
457 jTable1 = new javax.swing.JTable();
458
459 setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
460 setTitle("Chat History");
461
462 jLabel1.setText("History : ");
463
464 jTable1.setModel(new javax.swing.table.DefaultTableModel(
465 new Object [][] {
466
467 },
468 new String [] {
469 "Sender", "Message", "To", "Time"
470 }
471 ) {
472 Class[] types = new Class [] {
473 java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
474 };
475 boolean[] canEdit = new boolean [] {
476 false, false, false, false
477 };
478
479 public Class getColumnClass(int columnIndex) {
480 return types [columnIndex];
481 }
482
483 public boolean isCellEditable(int rowIndex, int columnIndex) {
484 return canEdit [columnIndex];
485 }
486 });
487 jScrollPane1.setViewportView(jTable1);
488 jTable1.getColumnModel().getColumn(1).setPreferredWidth(200);
489
490 javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
491 getContentPane().setLayout(layout);
492 layout.setHorizontalGroup(
493 layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
494 .addGroup(layout.createSequentialGroup()
495 .addContainerGap()
496 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
497 .addGroup(layout.createSequentialGroup()
498 .addComponent(jLabel1)
499 .addGap(0, 0, Short.MAX_VALUE))
500 .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 485, Short.MAX_VALUE))
501 .addContainerGap())
502 );
503 layout.setVerticalGroup(
504 layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
505 .addGroup(layout.createSequentialGroup()
506 .addContainerGap()
507 .addComponent(jLabel1)
508 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
509 .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 289, Short.MAX_VALUE)
510 .addContainerGap())
511 );
512
513 pack();
514 }// </editor-fold>
515
516 public static void main(String args[]) {
517 /* Set the Nimbus look and feel */
518 //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
519 /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
520 * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
521 */
522 try {
523 for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
524 if ("Nimbus".equals(info.getName())) {
525 javax.swing.UIManager.setLookAndFeel(info.getClassName());
526 break;
527 }
528 }
529 } catch (ClassNotFoundException ex) {
530 java.util.logging.Logger.getLogger(HistoryFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
531 } catch (InstantiationException ex) {
532 java.util.logging.Logger.getLogger(HistoryFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
533 } catch (IllegalAccessException ex) {
534 java.util.logging.Logger.getLogger(HistoryFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
535 } catch (javax.swing.UnsupportedLookAndFeelException ex) {
536 java.util.logging.Logger.getLogger(HistoryFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
537 }
538 //</editor-fold>
539
540 /* Create and display the form */
541 java.awt.EventQueue.invokeLater(new Runnable() {
542 public void run() {
543 new HistoryFrame().setVisible(true);
544 }
545 });
546 }
547 // Variables declaration - do not modify
548 private javax.swing.JLabel jLabel1;
549 private javax.swing.JScrollPane jScrollPane1;
550 public javax.swing.JTable jTable1;
551 // End of variables declaration
552}
553
554
555>>>>>>>>>>>>>>>>>>>>>>>>>>ChatFrame.java>>>>>>>>>>>>>>>>>>>>>>>>>>swing
556package com.ui;
557
558import com.socket.History;
559import com.socket.Message;
560import com.socket.SocketClient;
561import java.awt.event.WindowEvent;
562import java.awt.event.WindowListener;
563import java.io.File;
564import javax.swing.DefaultListModel;
565import javax.swing.JFileChooser;
566import javax.swing.JFrame;
567import javax.swing.UIManager;
568import oracle.jrockit.jfr.JFR;
569
570public class ChatFrame extends javax.swing.JFrame {
571
572 public SocketClient client;
573 public int port;
574 public String serverAddr, username, password;
575 public Thread clientThread;
576 public DefaultListModel model;
577 public File file;
578 public String historyFile = "D:/History.xml";
579 public HistoryFrame historyFrame;
580 public History hist;
581
582 public ChatFrame() {
583 initComponents();
584 this.setTitle("jMessenger");
585 model.addElement("All");
586 jList1.setSelectedIndex(0);
587
588 jTextField6.setEditable(false);
589
590 this.addWindowListener(new WindowListener() {
591
592 @Override public void windowOpened(WindowEvent e) {}
593 @Override public void windowClosing(WindowEvent e) { try{ client.send(new Message("message", username, ".bye", "SERVER")); clientThread.stop(); }catch(Exception ex){} }
594 @Override public void windowClosed(WindowEvent e) {}
595 @Override public void windowIconified(WindowEvent e) {}
596 @Override public void windowDeiconified(WindowEvent e) {}
597 @Override public void windowActivated(WindowEvent e) {}
598 @Override public void windowDeactivated(WindowEvent e) {}
599 });
600
601 hist = new History(historyFile);
602 }
603
604 public boolean isWin32(){
605 return System.getProperty("os.name").startsWith("Windows");
606 }
607
608 @SuppressWarnings("unchecked")
609 // <editor-fold defaultstate="collapsed" desc="Generated Code">
610 private void initComponents() {
611
612 jLabel1 = new javax.swing.JLabel();
613 jTextField1 = new javax.swing.JTextField();
614 jLabel2 = new javax.swing.JLabel();
615 jTextField2 = new javax.swing.JTextField();
616 jButton1 = new javax.swing.JButton();
617 jTextField3 = new javax.swing.JTextField();
618 jLabel3 = new javax.swing.JLabel();
619 jLabel4 = new javax.swing.JLabel();
620 jButton3 = new javax.swing.JButton();
621 jPasswordField1 = new javax.swing.JPasswordField();
622 jSeparator1 = new javax.swing.JSeparator();
623 jScrollPane1 = new javax.swing.JScrollPane();
624 jTextArea1 = new javax.swing.JTextArea();
625 jScrollPane2 = new javax.swing.JScrollPane();
626 jList1 = new javax.swing.JList();
627 jLabel5 = new javax.swing.JLabel();
628 jTextField4 = new javax.swing.JTextField();
629 jButton4 = new javax.swing.JButton();
630 jButton2 = new javax.swing.JButton();
631 jSeparator2 = new javax.swing.JSeparator();
632 jTextField5 = new javax.swing.JTextField();
633 jButton5 = new javax.swing.JButton();
634 jButton6 = new javax.swing.JButton();
635 jLabel6 = new javax.swing.JLabel();
636 jLabel7 = new javax.swing.JLabel();
637 jTextField6 = new javax.swing.JTextField();
638 jButton7 = new javax.swing.JButton();
639 jButton8 = new javax.swing.JButton();
640
641 setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
642
643 jLabel1.setText("Host Address : ");
644
645 jTextField1.setText("localhost");
646
647 jLabel2.setText("Host Port : ");
648
649 jTextField2.setText("13000");
650
651 jButton1.setText("Connect");
652 jButton1.addActionListener(new java.awt.event.ActionListener() {
653 public void actionPerformed(java.awt.event.ActionEvent evt) {
654 jButton1ActionPerformed(evt);
655 }
656 });
657
658 jTextField3.setText("Anurag");
659 jTextField3.setEnabled(false);
660
661 jLabel3.setText("Password :");
662
663 jLabel4.setText("Username :");
664
665 jButton3.setText("SignUp");
666 jButton3.setEnabled(false);
667 jButton3.addActionListener(new java.awt.event.ActionListener() {
668 public void actionPerformed(java.awt.event.ActionEvent evt) {
669 jButton3ActionPerformed(evt);
670 }
671 });
672
673 jPasswordField1.setText("password");
674 jPasswordField1.setEnabled(false);
675
676 jTextArea1.setColumns(20);
677 jTextArea1.setFont(new java.awt.Font("Consolas", 0, 12)); // NOI18N
678 jTextArea1.setRows(5);
679 jScrollPane1.setViewportView(jTextArea1);
680
681 jList1.setModel((model = new DefaultListModel()));
682 jScrollPane2.setViewportView(jList1);
683
684 jLabel5.setText("Message : ");
685
686 jButton4.setText("Send Message ");
687 jButton4.setEnabled(false);
688 jButton4.addActionListener(new java.awt.event.ActionListener() {
689 public void actionPerformed(java.awt.event.ActionEvent evt) {
690 jButton4ActionPerformed(evt);
691 }
692 });
693
694 jButton2.setText("Login");
695 jButton2.setEnabled(false);
696 jButton2.addActionListener(new java.awt.event.ActionListener() {
697 public void actionPerformed(java.awt.event.ActionEvent evt) {
698 jButton2ActionPerformed(evt);
699 }
700 });
701
702 jButton5.setText("...");
703 jButton5.setEnabled(false);
704 jButton5.addActionListener(new java.awt.event.ActionListener() {
705 public void actionPerformed(java.awt.event.ActionEvent evt) {
706 jButton5ActionPerformed(evt);
707 }
708 });
709
710 jButton6.setText("Send");
711 jButton6.setEnabled(false);
712 jButton6.addActionListener(new java.awt.event.ActionListener() {
713 public void actionPerformed(java.awt.event.ActionEvent evt) {
714 jButton6ActionPerformed(evt);
715 }
716 });
717
718 jLabel6.setText("File :");
719
720 jLabel7.setText("History File :");
721
722 jButton7.setText("...");
723 jButton7.setEnabled(false);
724 jButton7.addActionListener(new java.awt.event.ActionListener() {
725 public void actionPerformed(java.awt.event.ActionEvent evt) {
726 jButton7ActionPerformed(evt);
727 }
728 });
729
730 jButton8.setText("Show");
731 jButton8.setEnabled(false);
732 jButton8.addActionListener(new java.awt.event.ActionListener() {
733 public void actionPerformed(java.awt.event.ActionEvent evt) {
734 jButton8ActionPerformed(evt);
735 }
736 });
737
738 javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
739 getContentPane().setLayout(layout);
740 layout.setHorizontalGroup(
741 layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
742 .addGroup(layout.createSequentialGroup()
743 .addContainerGap()
744 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
745 .addComponent(jSeparator2)
746 .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.TRAILING)
747 .addGroup(layout.createSequentialGroup()
748 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
749 .addComponent(jLabel1)
750 .addComponent(jLabel4)
751 .addComponent(jLabel7))
752 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
753 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
754 .addGroup(layout.createSequentialGroup()
755 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
756 .addComponent(jTextField3)
757 .addComponent(jTextField1))
758 .addGap(18, 18, 18)
759 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
760 .addComponent(jLabel2)
761 .addComponent(jLabel3))
762 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
763 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
764 .addComponent(jTextField2)
765 .addComponent(jPasswordField1)))
766 .addComponent(jTextField6))
767 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
768 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
769 .addComponent(jButton1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
770 .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
771 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
772 .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
773 .addComponent(jButton7, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE))
774 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
775 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
776 .addComponent(jButton8, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
777 .addComponent(jButton3, javax.swing.GroupLayout.DEFAULT_SIZE, 81, Short.MAX_VALUE)))))
778 .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
779 .addComponent(jScrollPane1)
780 .addGap(18, 18, 18)
781 .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE))
782 .addGroup(layout.createSequentialGroup()
783 .addGap(23, 23, 23)
784 .addComponent(jLabel6)
785 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
786 .addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, 378, javax.swing.GroupLayout.PREFERRED_SIZE)
787 .addGap(18, 18, 18)
788 .addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
789 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
790 .addComponent(jButton6, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE))
791 .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
792 .addComponent(jLabel5)
793 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
794 .addComponent(jTextField4)
795 .addGap(18, 18, 18)
796 .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE)))
797 .addContainerGap())
798 );
799 layout.setVerticalGroup(
800 layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
801 .addGroup(layout.createSequentialGroup()
802 .addContainerGap()
803 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
804 .addComponent(jLabel1)
805 .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
806 .addComponent(jLabel2)
807 .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
808 .addComponent(jButton1))
809 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
810 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
811 .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
812 .addComponent(jLabel3)
813 .addComponent(jLabel4)
814 .addComponent(jButton3)
815 .addComponent(jPasswordField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
816 .addComponent(jButton2))
817 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
818 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
819 .addComponent(jLabel7)
820 .addComponent(jTextField6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
821 .addComponent(jButton7)
822 .addComponent(jButton8))
823 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
824 .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
825 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
826 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
827 .addComponent(jScrollPane1)
828 .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 264, Short.MAX_VALUE))
829 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
830 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
831 .addComponent(jButton4)
832 .addComponent(jLabel5)
833 .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
834 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
835 .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
836 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
837 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE, false)
838 .addComponent(jButton6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
839 .addComponent(jButton5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
840 .addComponent(jLabel6)
841 .addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
842 .addContainerGap())
843 );
844
845 pack();
846 }// </editor-fold>
847
848 private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
849 serverAddr = jTextField1.getText(); port = Integer.parseInt(jTextField2.getText());
850
851 if(!serverAddr.isEmpty() && !jTextField2.getText().isEmpty()){
852 try{
853 client = new SocketClient(this);
854 clientThread = new Thread(client);
855 clientThread.start();
856 client.send(new Message("test", "testUser", "testContent", "SERVER"));
857 }
858 catch(Exception ex){
859 jTextArea1.append("[Application > Me] : Server not found\n");
860 }
861 }
862 }
863
864 private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
865 username = jTextField3.getText();
866 password = jPasswordField1.getText();
867
868 if(!username.isEmpty() && !password.isEmpty()){
869 client.send(new Message("login", username, password, "SERVER"));
870 }
871 }
872
873 private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
874 String msg = jTextField4.getText();
875 String target = jList1.getSelectedValue().toString();
876
877 if(!msg.isEmpty() && !target.isEmpty()){
878 jTextField4.setText("");
879 client.send(new Message("message", username, msg, target));
880 }
881 }
882
883 private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
884 username = jTextField3.getText();
885 password = jPasswordField1.getText();
886
887 if(!username.isEmpty() && !password.isEmpty()){
888 client.send(new Message("signup", username, password, "SERVER"));
889 }
890 }
891
892 private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {
893 JFileChooser fileChooser = new JFileChooser();
894 fileChooser.showDialog(this, "Select File");
895 file = fileChooser.getSelectedFile();
896
897 if(file != null){
898 if(!file.getName().isEmpty()){
899 jButton6.setEnabled(true); String str;
900
901 if(jTextField5.getText().length() > 30){
902 String t = file.getPath();
903 str = t.substring(0, 20) + " [...] " + t.substring(t.length() - 20, t.length());
904 }
905 else{
906 str = file.getPath();
907 }
908 jTextField5.setText(str);
909 }
910 }
911 }
912
913 private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {
914 long size = file.length();
915 if(size < 120 * 1024 * 1024){
916 client.send(new Message("upload_req", username, file.getName(), jList1.getSelectedValue().toString()));
917 }
918 else{
919 jTextArea1.append("[Application > Me] : File is size too large\n");
920 }
921 }
922
923 private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {
924 JFileChooser jf = new JFileChooser();
925 jf.showDialog(this, "Select File");
926
927 if(!jf.getSelectedFile().getPath().isEmpty()){
928 historyFile = jf.getSelectedFile().getPath();
929 if(this.isWin32()){
930 historyFile = historyFile.replace("/", "\\");
931 }
932 jTextField6.setText(historyFile);
933 jTextField6.setEditable(false);
934 jButton7.setEnabled(false);
935 jButton8.setEnabled(true);
936 hist = new History(historyFile);
937
938 historyFrame = new HistoryFrame(hist);
939 historyFrame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
940 historyFrame.setVisible(false);
941 }
942 }
943
944 private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {
945 historyFrame.setLocation(this.getLocation());
946 historyFrame.setVisible(true);
947 }
948
949 public static void main(String args[]) {
950 try {
951 UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
952 }
953 catch(Exception ex){
954 System.out.println("Look & Feel exception");
955 }
956
957 java.awt.EventQueue.invokeLater(new Runnable() {
958 public void run() {
959 new ChatFrame().setVisible(true);
960 }
961 });
962 }
963 // Variables declaration - do not modify
964 public javax.swing.JButton jButton1;
965 public javax.swing.JButton jButton2;
966 public javax.swing.JButton jButton3;
967 public javax.swing.JButton jButton4;
968 public javax.swing.JButton jButton5;
969 public javax.swing.JButton jButton6;
970 public javax.swing.JButton jButton7;
971 public javax.swing.JButton jButton8;
972 private javax.swing.JLabel jLabel1;
973 private javax.swing.JLabel jLabel2;
974 private javax.swing.JLabel jLabel3;
975 private javax.swing.JLabel jLabel4;
976 private javax.swing.JLabel jLabel5;
977 private javax.swing.JLabel jLabel6;
978 private javax.swing.JLabel jLabel7;
979 public javax.swing.JList jList1;
980 public javax.swing.JPasswordField jPasswordField1;
981 private javax.swing.JScrollPane jScrollPane1;
982 private javax.swing.JScrollPane jScrollPane2;
983 private javax.swing.JSeparator jSeparator1;
984 private javax.swing.JSeparator jSeparator2;
985 public javax.swing.JTextArea jTextArea1;
986 public javax.swing.JTextField jTextField1;
987 public javax.swing.JTextField jTextField2;
988 public javax.swing.JTextField jTextField3;
989 public javax.swing.JTextField jTextField4;
990 public javax.swing.JTextField jTextField5;
991 public javax.swing.JTextField jTextField6;
992 // End of variables declaration
993}
994
995>>>>>>>>>>>>>>>>>>>>>>>>>>ServerFrame.java>>>>>>>>>>>>>>>>>>>>>>>>>>swing
996package com.socket;
997
998import java.awt.Color;
999import java.awt.event.KeyEvent;
1000import java.awt.event.KeyListener;
1001import java.io.File;
1002import javax.swing.JFileChooser;
1003import javax.swing.UIManager;
1004
1005public class ServerFrame extends javax.swing.JFrame {
1006
1007 public SocketServer server;
1008 public Thread serverThread;
1009 public String filePath = "D:/Data.xml";
1010 public JFileChooser fileChooser;
1011
1012 public ServerFrame() {
1013 initComponents();
1014 jTextField3.setEditable(false);
1015 jTextField3.setBackground(Color.WHITE);
1016
1017 fileChooser = new JFileChooser();
1018 jTextArea1.setEditable(false);
1019 }
1020
1021 public boolean isWin32(){
1022 return System.getProperty("os.name").startsWith("Windows");
1023 }
1024
1025 @SuppressWarnings("unchecked")
1026 // <editor-fold defaultstate="collapsed" desc="Generated Code">
1027 private void initComponents() {
1028
1029 jButton1 = new javax.swing.JButton();
1030 jScrollPane1 = new javax.swing.JScrollPane();
1031 jTextArea1 = new javax.swing.JTextArea();
1032 jLabel3 = new javax.swing.JLabel();
1033 jTextField3 = new javax.swing.JTextField();
1034 jButton2 = new javax.swing.JButton();
1035
1036 setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
1037 setTitle("jServer");
1038
1039 jButton1.setText("Start Server");
1040 jButton1.setEnabled(false);
1041 jButton1.addActionListener(new java.awt.event.ActionListener() {
1042 public void actionPerformed(java.awt.event.ActionEvent evt) {
1043 jButton1ActionPerformed(evt);
1044 }
1045 });
1046
1047 jTextArea1.setColumns(20);
1048 jTextArea1.setFont(new java.awt.Font("Consolas", 0, 12)); // NOI18N
1049 jTextArea1.setRows(5);
1050 jScrollPane1.setViewportView(jTextArea1);
1051
1052 jLabel3.setText("Database File : ");
1053
1054 jButton2.setText("Browse...");
1055 jButton2.addActionListener(new java.awt.event.ActionListener() {
1056 public void actionPerformed(java.awt.event.ActionEvent evt) {
1057 jButton2ActionPerformed(evt);
1058 }
1059 });
1060
1061 javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
1062 getContentPane().setLayout(layout);
1063 layout.setHorizontalGroup(
1064 layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
1065 .addGroup(layout.createSequentialGroup()
1066 .addContainerGap()
1067 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
1068 .addComponent(jScrollPane1)
1069 .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
1070 .addComponent(jLabel3)
1071 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
1072 .addComponent(jTextField3, javax.swing.GroupLayout.DEFAULT_SIZE, 282, Short.MAX_VALUE)
1073 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
1074 .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
1075 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
1076 .addComponent(jButton1)))
1077 .addContainerGap())
1078 );
1079 layout.setVerticalGroup(
1080 layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
1081 .addGroup(layout.createSequentialGroup()
1082 .addContainerGap()
1083 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
1084 .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
1085 .addComponent(jLabel3)
1086 .addComponent(jButton2)
1087 .addComponent(jButton1))
1088 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
1089 .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 287, Short.MAX_VALUE)
1090 .addContainerGap())
1091 );
1092
1093 pack();
1094 }// </editor-fold>
1095
1096 private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
1097 server = new SocketServer(this);
1098 jButton1.setEnabled(false); jButton2.setEnabled(false);
1099 }
1100
1101 public void RetryStart(int port){
1102 if(server != null){ server.stop(); }
1103 server = new SocketServer(this, port);
1104 }
1105
1106 private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
1107 fileChooser.showDialog(this, "Select");
1108 File file = fileChooser.getSelectedFile();
1109
1110 if(file != null){
1111 filePath = file.getPath();
1112 if(this.isWin32()){ filePath = filePath.replace("\\", "/"); }
1113 jTextField3.setText(filePath);
1114 jButton1.setEnabled(true);
1115 }
1116 }
1117
1118 public static void main(String args[]) {
1119
1120 try{
1121 UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
1122 }
1123 catch(Exception ex){
1124 System.out.println("Look & Feel Exception");
1125 }
1126
1127 java.awt.EventQueue.invokeLater(new Runnable() {
1128 public void run() {
1129 new ServerFrame().setVisible(true);
1130 }
1131 });
1132 }
1133 // Variables declaration - do not modify
1134 private javax.swing.JButton jButton1;
1135 private javax.swing.JButton jButton2;
1136 private javax.swing.JLabel jLabel3;
1137 private javax.swing.JScrollPane jScrollPane1;
1138 public javax.swing.JTextArea jTextArea1;
1139 private javax.swing.JTextField jTextField3;
1140 // End of variables declaration
1141}
1142
1143>>>>>>>>>>>>>>>>>>>>>>>>>>Database.java>>>>>>>>>>>>>>>>>>>>>>>>>>
1144package com.socket;
1145
1146import java.io.*;
1147import javax.xml.parsers.DocumentBuilder;
1148import javax.xml.parsers.DocumentBuilderFactory;
1149import javax.xml.transform.Transformer;
1150import javax.xml.transform.TransformerFactory;
1151import javax.xml.transform.dom.DOMSource;
1152import javax.xml.transform.stream.StreamResult;
1153import org.w3c.dom.*;
1154
1155public class Database {
1156
1157 public String filePath;
1158
1159 public Database(String filePath){
1160 this.filePath = filePath;
1161 }
1162
1163 public boolean userExists(String username){
1164
1165 try{
1166 File fXmlFile = new File(filePath);
1167 DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
1168 DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
1169 Document doc = dBuilder.parse(fXmlFile);
1170 doc.getDocumentElement().normalize();
1171
1172 NodeList nList = doc.getElementsByTagName("user");
1173
1174 for (int temp = 0; temp < nList.getLength(); temp++) {
1175 Node nNode = nList.item(temp);
1176 if (nNode.getNodeType() == Node.ELEMENT_NODE) {
1177 Element eElement = (Element) nNode;
1178 if(getTagValue("username", eElement).equals(username)){
1179 return true;
1180 }
1181 }
1182 }
1183 return false;
1184 }
1185 catch(Exception ex){
1186 System.out.println("Database exception : userExists()");
1187 return false;
1188 }
1189 }
1190
1191 public boolean checkLogin(String username, String password){
1192
1193 if(!userExists(username)){ return false; }
1194
1195 try{
1196 File fXmlFile = new File(filePath);
1197 DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
1198 DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
1199 Document doc = dBuilder.parse(fXmlFile);
1200 doc.getDocumentElement().normalize();
1201
1202 NodeList nList = doc.getElementsByTagName("user");
1203
1204 for (int temp = 0; temp < nList.getLength(); temp++) {
1205 Node nNode = nList.item(temp);
1206 if (nNode.getNodeType() == Node.ELEMENT_NODE) {
1207 Element eElement = (Element) nNode;
1208 if(getTagValue("username", eElement).equals(username) && getTagValue("password", eElement).equals(password)){
1209 return true;
1210 }
1211 }
1212 }
1213 System.out.println("Hippie");
1214 return false;
1215 }
1216 catch(Exception ex){
1217 System.out.println("Database exception : userExists()");
1218 return false;
1219 }
1220 }
1221
1222 public void addUser(String username, String password){
1223
1224 try {
1225 DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
1226 DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
1227 Document doc = docBuilder.parse(filePath);
1228
1229 Node data = doc.getFirstChild();
1230
1231 Element newuser = doc.createElement("user");
1232 Element newusername = doc.createElement("username"); newusername.setTextContent(username);
1233 Element newpassword = doc.createElement("password"); newpassword.setTextContent(password);
1234
1235 newuser.appendChild(newusername); newuser.appendChild(newpassword); data.appendChild(newuser);
1236
1237 TransformerFactory transformerFactory = TransformerFactory.newInstance();
1238 Transformer transformer = transformerFactory.newTransformer();
1239 DOMSource source = new DOMSource(doc);
1240 StreamResult result = new StreamResult(new File(filePath));
1241 transformer.transform(source, result);
1242
1243 }
1244 catch(Exception ex){
1245 System.out.println("Exceptionmodify xml");
1246 }
1247 }
1248
1249 public static String getTagValue(String sTag, Element eElement) {
1250 NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();
1251 Node nValue = (Node) nlList.item(0);
1252 return nValue.getNodeValue();
1253 }
1254}
1255
1256>>>>>>>>>>>>>>>>>>>>>>>>>>SocketServer.java>>>>>>>>>>>>>>>>>>>>>>>>>>
1257package com.socket;
1258
1259import java.io.*;
1260import java.net.*;
1261
1262class ServerThread extends Thread {
1263
1264 public SocketServer server = null;
1265 public Socket socket = null;
1266 public int ID = -1;
1267 public String username = "";
1268 public ObjectInputStream streamIn = null;
1269 public ObjectOutputStream streamOut = null;
1270 public ServerFrame ui;
1271
1272 public ServerThread(SocketServer _server, Socket _socket){
1273 super();
1274 server = _server;
1275 socket = _socket;
1276 ID = socket.getPort();
1277 ui = _server.ui;
1278 }
1279
1280 public void send(Message msg){
1281 try {
1282 streamOut.writeObject(msg);
1283 streamOut.flush();
1284 }
1285 catch (IOException ex) {
1286 System.out.println("Exception [SocketClient : send(...)]");
1287 }
1288 }
1289
1290 public int getID(){
1291 return ID;
1292 }
1293
1294 @SuppressWarnings("deprecation")
1295 public void run(){
1296 ui.jTextArea1.append("\nServer Thread " + ID + " running.");
1297 while (true){
1298 try{
1299 Message msg = (Message) streamIn.readObject();
1300 server.handle(ID, msg);
1301 }
1302 catch(Exception ioe){
1303 System.out.println(ID + " ERROR reading: " + ioe.getMessage());
1304 server.remove(ID);
1305 stop();
1306 }
1307 }
1308 }
1309
1310 public void open() throws IOException {
1311 streamOut = new ObjectOutputStream(socket.getOutputStream());
1312 streamOut.flush();
1313 streamIn = new ObjectInputStream(socket.getInputStream());
1314 }
1315
1316 public void close() throws IOException {
1317 if (socket != null) socket.close();
1318 if (streamIn != null) streamIn.close();
1319 if (streamOut != null) streamOut.close();
1320 }
1321}
1322
1323
1324
1325
1326
1327public class SocketServer implements Runnable {
1328
1329 public ServerThread clients[];
1330 public ServerSocket server = null;
1331 public Thread thread = null;
1332 public int clientCount = 0, port = 13000;
1333 public ServerFrame ui;
1334 public Database db;
1335
1336 public SocketServer(ServerFrame frame){
1337
1338 clients = new ServerThread[50];
1339 ui = frame;
1340 db = new Database(ui.filePath);
1341
1342 try{
1343 server = new ServerSocket(port);
1344 port = server.getLocalPort();
1345 ui.jTextArea1.append("Server startet. IP : " + InetAddress.getLocalHost() + ", Port : " + server.getLocalPort());
1346 start();
1347 }
1348 catch(IOException ioe){
1349 ui.jTextArea1.append("Can not bind to port : " + port + "\nRetrying");
1350 ui.RetryStart(0);
1351 }
1352 }
1353
1354 public SocketServer(ServerFrame frame, int Port){
1355
1356 clients = new ServerThread[50];
1357 ui = frame;
1358 port = Port;
1359 db = new Database(ui.filePath);
1360
1361 try{
1362 server = new ServerSocket(port);
1363 port = server.getLocalPort();
1364 ui.jTextArea1.append("Server startet. IP : " + InetAddress.getLocalHost() + ", Port : " + server.getLocalPort());
1365 start();
1366 }
1367 catch(IOException ioe){
1368 ui.jTextArea1.append("\nCan not bind to port " + port + ": " + ioe.getMessage());
1369 }
1370 }
1371
1372 public void run(){
1373 while (thread != null){
1374 try{
1375 ui.jTextArea1.append("\nWaiting for a client ...");
1376 addThread(server.accept());
1377 }
1378 catch(Exception ioe){
1379 ui.jTextArea1.append("\nServer accept error: \n");
1380 ui.RetryStart(0);
1381 }
1382 }
1383 }
1384
1385 public void start(){
1386 if (thread == null){
1387 thread = new Thread(this);
1388 thread.start();
1389 }
1390 }
1391
1392 @SuppressWarnings("deprecation")
1393 public void stop(){
1394 if (thread != null){
1395 thread.stop();
1396 thread = null;
1397 }
1398 }
1399
1400 private int findClient(int ID){
1401 for (int i = 0; i < clientCount; i++){
1402 if (clients[i].getID() == ID){
1403 return i;
1404 }
1405 }
1406 return -1;
1407 }
1408
1409 public synchronized void handle(int ID, Message msg){
1410 if (msg.content.equals(".bye")){
1411 Announce("signout", "SERVER", msg.sender);
1412 remove(ID);
1413 }
1414 else{
1415 if(msg.type.equals("login")){
1416 if(findUserThread(msg.sender) == null){
1417 if(db.checkLogin(msg.sender, msg.content)){
1418 clients[findClient(ID)].username = msg.sender;
1419 clients[findClient(ID)].send(new Message("login", "SERVER", "TRUE", msg.sender));
1420 Announce("newuser", "SERVER", msg.sender);
1421 SendUserList(msg.sender);
1422 }
1423 else{
1424 clients[findClient(ID)].send(new Message("login", "SERVER", "FALSE", msg.sender));
1425 }
1426 }
1427 else{
1428 clients[findClient(ID)].send(new Message("login", "SERVER", "FALSE", msg.sender));
1429 }
1430 }
1431 else if(msg.type.equals("message")){
1432 if(msg.recipient.equals("All")){
1433 Announce("message", msg.sender, msg.content);
1434 }
1435 else{
1436 findUserThread(msg.recipient).send(new Message(msg.type, msg.sender, msg.content, msg.recipient));
1437 clients[findClient(ID)].send(new Message(msg.type, msg.sender, msg.content, msg.recipient));
1438 }
1439 }
1440 else if(msg.type.equals("test")){
1441 clients[findClient(ID)].send(new Message("test", "SERVER", "OK", msg.sender));
1442 }
1443 else if(msg.type.equals("signup")){
1444 if(findUserThread(msg.sender) == null){
1445 if(!db.userExists(msg.sender)){
1446 db.addUser(msg.sender, msg.content);
1447 clients[findClient(ID)].username = msg.sender;
1448 clients[findClient(ID)].send(new Message("signup", "SERVER", "TRUE", msg.sender));
1449 clients[findClient(ID)].send(new Message("login", "SERVER", "TRUE", msg.sender));
1450 Announce("newuser", "SERVER", msg.sender);
1451 SendUserList(msg.sender);
1452 }
1453 else{
1454 clients[findClient(ID)].send(new Message("signup", "SERVER", "FALSE", msg.sender));
1455 }
1456 }
1457 else{
1458 clients[findClient(ID)].send(new Message("signup", "SERVER", "FALSE", msg.sender));
1459 }
1460 }
1461 else if(msg.type.equals("upload_req")){
1462 if(msg.recipient.equals("All")){
1463 clients[findClient(ID)].send(new Message("message", "SERVER", "Uploading to 'All' forbidden", msg.sender));
1464 }
1465 else{
1466 findUserThread(msg.recipient).send(new Message("upload_req", msg.sender, msg.content, msg.recipient));
1467 }
1468 }
1469 else if(msg.type.equals("upload_res")){
1470 if(!msg.content.equals("NO")){
1471 String IP = findUserThread(msg.sender).socket.getInetAddress().getHostAddress();
1472 findUserThread(msg.recipient).send(new Message("upload_res", IP, msg.content, msg.recipient));
1473 }
1474 else{
1475 findUserThread(msg.recipient).send(new Message("upload_res", msg.sender, msg.content, msg.recipient));
1476 }
1477 }
1478 }
1479 }
1480
1481 public void Announce(String type, String sender, String content){
1482 Message msg = new Message(type, sender, content, "All");
1483 for(int i = 0; i < clientCount; i++){
1484 clients[i].send(msg);
1485 }
1486 }
1487
1488 public void SendUserList(String toWhom){
1489 for(int i = 0; i < clientCount; i++){
1490 findUserThread(toWhom).send(new Message("newuser", "SERVER", clients[i].username, toWhom));
1491 }
1492 }
1493
1494 public ServerThread findUserThread(String usr){
1495 for(int i = 0; i < clientCount; i++){
1496 if(clients[i].username.equals(usr)){
1497 return clients[i];
1498 }
1499 }
1500 return null;
1501 }
1502
1503 @SuppressWarnings("deprecation")
1504 public synchronized void remove(int ID){
1505 int pos = findClient(ID);
1506 if (pos >= 0){
1507 ServerThread toTerminate = clients[pos];
1508 ui.jTextArea1.append("\nRemoving client thread " + ID + " at " + pos);
1509 if (pos < clientCount-1){
1510 for (int i = pos+1; i < clientCount; i++){
1511 clients[i-1] = clients[i];
1512 }
1513 }
1514 clientCount--;
1515 try{
1516 toTerminate.close();
1517 }
1518 catch(IOException ioe){
1519 ui.jTextArea1.append("\nError closing thread: " + ioe);
1520 }
1521 toTerminate.stop();
1522 }
1523 }
1524
1525 private void addThread(Socket socket){
1526 if (clientCount < clients.length){
1527 ui.jTextArea1.append("\nClient accepted: " + socket);
1528 clients[clientCount] = new ServerThread(this, socket);
1529 try{
1530 clients[clientCount].open();
1531 clients[clientCount].start();
1532 clientCount++;
1533 }
1534 catch(IOException ioe){
1535 ui.jTextArea1.append("\nError opening thread: " + ioe);
1536 }
1537 }
1538 else{
1539 ui.jTextArea1.append("\nClient refused: maximum " + clients.length + " reached.");
1540 }
1541 }
1542}
1543
1544>>>>>>>>>>>>>>>>>>>>>>>>>>Message.java>>>>>>>>>>>>>>>>>>>>>>>>>>
1545package com.socket;
1546
1547import java.io.Serializable;
1548
1549public class Message implements Serializable{
1550
1551 private static final long serialVersionUID = 1L;
1552 public String type, sender, content, recipient;
1553
1554 public Message(String type, String sender, String content, String recipient){
1555 this.type = type; this.sender = sender; this.content = content; this.recipient = recipient;
1556 }
1557
1558 @Override
1559 public String toString(){
1560 return "{type='"+type+"', sender='"+sender+"', content='"+content+"', recipient='"+recipient+"'}";
1561 }
1562}