-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClient.java
More file actions
520 lines (494 loc) · 19.8 KB
/
Client.java
File metadata and controls
520 lines (494 loc) · 19.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
package BACKUPER;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Vector;
public class Client extends JFrame implements ActionListener {
private JButton chooseFileButton;
private JButton startBuckupButton;
private JButton clearButton;
private JLabel userNameLabel;
private JLabel passwordLabel;
private JLabel restoreLabel;
private JComboBox restoreComboBox;
private JButton createUser;
private JTextArea userNameArea;
private JTextArea IPArea;
private JTextArea IPArea_newUser;
private JPasswordField passwordArea;
private JTextArea login;
private JPasswordField password;
private JButton logIn;
private JButton newUser;
private JButton restoreButton;
private JFileChooser fileChooser;
private JList fileQue;
private JList filesArchivied;
private JFrame logInFrame;
private DefaultListModel listModelQue;
private DefaultListModel listModelSent;
private ArrayList<FileMetaData> que;
private ArrayList<FileMetaData> filesSent;
private PrintWriter outNotify;
private BufferedReader bufferedReader;
private OutputStream outputStream;
private static int curiosity = 0;
Socket socket = null;
private static int port=-1;
JFrame newUserFrame;
private boolean loggedIn=false;
private JLabel userLoginLabel;
private JButton logout;
private Vector<String> restoreFiles;
private int filesNumber;
private int ignored;
private BufferedInputStream bis;
private boolean connected = true;
public static JProgressBar progressBar;
private static JFrame busyFrame;
private final static int bufferSize=16384;
public Client() {
prepareLogInWindow();
prepareWindow();
que = new ArrayList<>();
filesSent=new ArrayList<>();
}
public static void main(String[] args) {
new Client();
try {
System.out.println(InetAddress.getLocalHost().getHostAddress());
}
catch (Exception e){
System.err.println(e);
}
}
private void getAttainablePort(String IP) throws IOException {
if(port==-1) {
Socket socket = new Socket(IP, 12129);
InputStream inputStream = socket.getInputStream();
BufferedReader portReader = new BufferedReader(new InputStreamReader(inputStream));
port = Integer.parseInt(portReader.readLine());
System.out.println("Nowoustawiony port: "+port);
socket.close();
}
else{
System.out.println("Poprzednio ustawiony port: "+port);
}
}
private void setConnection(String IP){
try {
getAttainablePort(IP);
socket = new Socket(IP, port);
InputStream inputStream = socket.getInputStream();
outNotify = new PrintWriter(socket.getOutputStream(), true);
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
outputStream=socket.getOutputStream();
bis = new BufferedInputStream(inputStream);
}
catch (IOException e){
System.err.println("Error establishing the connection with server!: "+e);
}
}
public String getFileName(String filePath){
char tmp;
int i = 0;
String fileName_tmp="";
int file_src_length = filePath.length();
while((tmp = filePath.charAt(file_src_length-1-i))!='\\') {
fileName_tmp += tmp;
i++;
}
StringBuilder builder=new StringBuilder(fileName_tmp);
return builder.reverse().toString();
}
private void sendMetaData(FileMetaData fileData){
String filePath=fileData.getFilePath();
outNotify.println(fileData.getFileLength());
outNotify.println(filePath);
}
public void sendFile(FileMetaData fileData, OutputStream out){
try {
File file = new File(fileData.getFilePath());
long fileLength = fileData.getFileLength();
FileInputStream inputLocal = new FileInputStream(file);
int read=0;
int offset=0;
int off=0;
while(!receive().equals(MyProtocol.READY));
System.out.println("Zaczynam przesyłanie pliku: "+fileData.getFilePath());
while (offset < fileLength) {
byte[] buffer = new byte[bufferSize];
while(off<bufferSize && ((read =inputLocal.read(buffer, off, bufferSize - off)) != -1)) {
off+=read;
}
out.write(buffer, 0, off);
out.flush();
offset+=off;
System.out.println("Wczytano "+off+" bajtów do bufora");
off=0;
}
out.flush();
System.out.println("Wysłano "+offset+" bajtów");
} catch (Exception e){
JOptionPane.showMessageDialog(null,"Utracono połączenie, włącz aplikację ponownie.");
System.err.println(e);
}
}
private void fillVector() {
String tmp = receive();
restoreComboBox.removeAllItems();
if(tmp.equals(MyProtocol.FILEEXIST)) {
int amount = Integer.parseInt(receive());
System.out.println(amount);
System.out.println(tmp);
if (amount != 0) {
for (int i = 0; i < amount; i++) {
restoreComboBox.addItem(receive());
}
}
}else
System.out.println(tmp);
}
private void prepareLogInWindow(){
logInFrame=new JFrame();
logInFrame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosed(WindowEvent e) {
super.windowClosed(e);
}
});
JPanel contentFrame=(JPanel)logInFrame.getContentPane();
contentFrame.setLayout(new GridLayout(8,1));
JLabel IPAreaText=new JLabel("Adres IP serwera");
JLabel loginLabel=new JLabel("Login");
JLabel passwordLabel=new JLabel("Hasło");
IPArea=new JTextArea();
login=new JTextArea();
password=new JPasswordField();
logIn=new JButton("Zaloguj");
logIn.addActionListener(this);
createUser=new JButton("Załóż konto");
createUser.addActionListener(this);
login.setBounds(0,0,400,25);
password.setBounds(0,0,400,25);
logIn.setBounds(0,0,400,100);
login.setBorder(BorderFactory.createLineBorder(new Color(000000)));
password.setBorder(BorderFactory.createLineBorder(new Color(0x000000)));
contentFrame.add(loginLabel);
contentFrame.add(login);
contentFrame.add(passwordLabel);
contentFrame.add(password);
contentFrame.add(IPAreaText);
contentFrame.add(IPArea);
contentFrame.add(logIn);
contentFrame.add(createUser);
logInFrame.setSize(new Dimension(400,240));
logInFrame.setLocation(100,100);
logInFrame.setVisible(true);
logInFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private void prepareNewUserWindow(){
newUserFrame=new JFrame();
newUserFrame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
logInFrame.setVisible(true);
super.windowClosing(e);
}
});
JPanel contentFrame=(JPanel)newUserFrame.getContentPane();
JLabel IPAreaText_newUser=new JLabel("Adres IP serwera");
IPArea_newUser=new JTextArea();
userNameLabel=new JLabel("Nazwa użytkownika");
userNameArea=new JTextArea();
passwordLabel=new JLabel("Hasło");
passwordArea=new JPasswordField();
newUser=new JButton("Załóż konto");
newUser.addActionListener(this);
contentFrame.setLayout(new GridLayout(7,1));
newUserFrame.setSize(new Dimension(300,280));
contentFrame.add(userNameLabel);
contentFrame.add(userNameArea);
contentFrame.add(passwordLabel);
contentFrame.add(passwordArea);
contentFrame.add(IPAreaText_newUser);
contentFrame.add(IPArea_newUser);
contentFrame.add(newUser);
newUserFrame.setVisible(true);
}
private void prepareWindow() {
addWindowListener(new WindowAdapter() {
@Override
public void windowClosed(WindowEvent e) {
super.windowClosed(e);
}
});
JLabel toSendLabel=new JLabel("Files to be send:");
JLabel sentLabel=new JLabel("Files sent:");
logout=new JButton("LOGOUT");
logout.addActionListener(this);
userLoginLabel=new JLabel();
chooseFileButton = new JButton("Wybierz pliki do przesłania");
startBuckupButton = new JButton("Rozpocznij przesyłanie");
clearButton = new JButton("Clear history");
fileChooser = new JFileChooser();
fileChooser.setMultiSelectionEnabled(true);
restoreLabel = new JLabel("Przywróć pliki:");
restoreComboBox = new JComboBox();
restoreButton = new JButton("Odtwórz plik");
listModelQue = new DefaultListModel();
fileQue = new JList(listModelQue);
listModelSent = new DefaultListModel();
filesArchivied = new JList(listModelSent);
fileQue.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
fileQue.setVisibleRowCount(5);
chooseFileButton.addActionListener(this);
startBuckupButton.addActionListener(this);
clearButton.addActionListener(this);
restoreButton.addActionListener(this);
JPanel contentFrame=(JPanel)this.getContentPane();
contentFrame.setLayout(new GridLayout(12,2));
contentFrame.add(chooseFileButton);
contentFrame.add(toSendLabel);
contentFrame.add(new JScrollPane(fileQue));
contentFrame.add(sentLabel);
contentFrame.add(new JScrollPane(filesArchivied));
contentFrame.add(clearButton);
contentFrame.add(startBuckupButton);
contentFrame.add(restoreLabel);
contentFrame.add(restoreComboBox);
contentFrame.add(restoreButton);
contentFrame.add(userLoginLabel);
contentFrame.add(logout);
setSize(new Dimension(650,650));
setLocation(300,200);
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
outNotify.println(MyProtocol.LOGOUT);
super.windowClosing(e);
System.exit(0);
}
});
setVisible(false);
}
private void prepareBusyFrame() {
busyFrame = new JFrame();
busyFrame.setLayout(new GridBagLayout());
busyFrame.setTitle("Proszę czekać");
JLabel busyLabel = new JLabel("Trwa przesyłanie plików");
busyFrame.setBounds(500,500,500,50);
busyLabel.setBounds(100,50,200,50);
busyFrame.add(busyLabel);
busyFrame.setVisible(true);
}
private String receive(){
try{
return bufferedReader.readLine();
}
catch (IOException e){
System.err.println(e);
return null;
}
}
@SuppressWarnings("deprecated")
@Override
public void actionPerformed(ActionEvent e) {
Object clicked = e.getSource();
if(clicked == chooseFileButton) {
if(fileChooser.showOpenDialog(chooseFileButton) == JFileChooser.APPROVE_OPTION){
File[] chosenFiles = fileChooser.getSelectedFiles();
for (File file:chosenFiles) {
String name=file.getPath();
long length=file.length();
listModelQue.addElement(name);
que.add(new FileMetaData(name,length));
System.out.println("Your choice: "+name);
}
}
}
else if(clicked == startBuckupButton) {
try {
prepareBusyFrame();
busyFrame.setVisible(true);
outNotify.println(MyProtocol.SENDFILE);
outNotify.println(que.size());
for (FileMetaData data : que) {
sendMetaData(data);
}
for (FileMetaData data:que) {
while(!(receive().equals(MyProtocol.READY))){
curiosity++;
System.out.println("WAITING..");
}
sendFile(data,outputStream);
outputStream.flush();
filesSent.add(data);
listModelSent.addElement(data.getFilePath());
}
listModelQue.clear();
fillVector();
if(listModelSent.size() != 0)
JOptionPane.showMessageDialog(null, "Poprawnie przesłano " +que.size()+ " plików.");
busyFrame.setVisible(false);
que.clear();
}
catch (IOException e1){
System.err.println(e1);
}
}
else if(clicked == clearButton) {
listModelSent.clear();
filesSent.clear();
}
else if (clicked == restoreButton) {
try {
prepareBusyFrame();
busyFrame.setVisible(true);
String fileTMP = restoreComboBox.getSelectedItem().toString();
outNotify.println(MyProtocol.RESTOREFILE);
outNotify.println(fileTMP);
long fileLength;
String rec = receive();
if (rec.equals(MyProtocol.READY))
fileLength = Long.parseLong(receive());
else
fileLength = Long.parseLong(rec);
String pathToSave = receive();
File fileOut = new File(pathToSave);
FileOutputStream outputLocal = new FileOutputStream(fileOut);
outNotify.println(MyProtocol.READY);
System.out.println(fileLength);
int offset = 0;
int off = 0;
int read;
long numbOfPacks = fileLength / bufferSize;
long rest = fileLength % bufferSize;
if (rest != 0)
numbOfPacks++;
for (int j = 0; j < numbOfPacks - 1; j++) {
byte[] buffer = new byte[bufferSize];
while (off < bufferSize && ((read = bis.read(buffer, off, bufferSize - off)) != -1)) {
off += read;
}
outputLocal.write(buffer, 0, off);
offset += off;
off = 0;
}
byte[] buffer = new byte[(int)rest];
while (off < rest && ((read = bis.read(buffer, off, (int)(rest - off))) != -1)) {
off += read;
}
outputLocal.write(buffer, 0, off);
//byte[] fileBytes = new byte[(int)fileLength];
System.out.println("fine");
//System.out.println("Wczytano bajtów: " + offset + "/" + fileLength);
//outputLocal.write(fileBytes, 0, (int)fileLength);
JOptionPane.showMessageDialog(null, "Poprawnie odtworzona plik: " + fileTMP);
busyFrame.setVisible(false);
outputLocal.flush();
}
catch (IOException er) {
JOptionPane.showMessageDialog(null, "Utracono połączenie, włącz ponownie aplikację.");
System.err.println(er);
System.err.println("Błąd przywracania pliku: " +er);
}
}
else if(clicked == logIn)
{
try {
String loginText = login.getText();
String passwordText = password.getText();
String IP=IPArea.getText();
if(IP.isEmpty())
IP="localhost";
if(socket==null) {
setConnection(IP);
System.out.println("Ustalono połączenie: " + port);
}
outNotify.println(MyProtocol.LOGIN);
outNotify.println(loginText);
outNotify.println(passwordText);
String request = receive();
switch (request){
case (MyProtocol.FAILED):
System.out.println("Nie udało się zalogować!");
JOptionPane.showMessageDialog(null, "Błędny login, lub hasło");
login.setBorder(BorderFactory.createLineBorder(new Color(0xff0000)));
password.setBorder(BorderFactory.createLineBorder(new Color(0xff0000)));
break;
case (MyProtocol.LOGGEDIN):
System.out.println("Udało się zalogować!");
userLoginLabel.setText("Zalogowano jako: "+loginText+".");
loggedIn=true;
logInFrame.setVisible(false);
setVisible(true);
fillVector();
break;
default:
System.out.println("PROBLEM!");
socket.close();
break;
}
}
catch (IOException e1){
System.err.println(e1);
}
}
else if(clicked==createUser){
logInFrame.setVisible(false);
prepareNewUserWindow();
}
else if(clicked==newUser){
String name=userNameArea.getText();
String password=passwordArea.getText();
String IP_newUser=IPArea_newUser.getText();
if(IP_newUser.isEmpty())
IP_newUser="localhost";
if(socket==null) {
setConnection(IP_newUser);
System.out.println("Ustalono połączenie: " + port);
}
outNotify.println(MyProtocol.NEWUSER);
outNotify.println(name);
outNotify.println(password);
String response=receive();
switch (response){
case(MyProtocol.FAILED):
userNameArea.setBorder(BorderFactory.createLineBorder(new Color(0xff0000)));
passwordArea.setBorder(BorderFactory.createLineBorder(new Color(0xff0000)));
break;
case (MyProtocol.READY):
newUserFrame.setVisible(false);
logInFrame.setVisible(true);
login.setText(name);
break;
default:
break;
}
}
else if(clicked==logout){
outNotify.println(MyProtocol.LOGOUT);
try{
socket.close();
socket=null;
}
catch (IOException e1){
System.err.println("Error loggin out (client): "+e1);
socket=null;
}
port=-1;
logInFrame.setVisible(true);
setVisible(false);
login.setText("");
password.setText("");
}
}
}