-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPeer.java
More file actions
1164 lines (943 loc) · 39.4 KB
/
Peer.java
File metadata and controls
1164 lines (943 loc) · 39.4 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
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.Console;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.BindException;
import java.net.ConnectException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.ListIterator;
import java.util.Random;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class Peer {
public static Zone peerZone;
public static Zone tempZone;
public static ArrayList<ArrayList<String>> neighbours = new ArrayList<ArrayList<String>>();
public static HashMap<String, String> files = new HashMap<>();
public static String bootStrap;
public static int bootstrapPort;
public static int portforCAN;
public static String ip = null;
public static String CANid = null;
public static String hostName = null;
public static String userName = null;
public static String password = null;
public static boolean oldUser = false;
public static String getDir() {
return "/home/stu12/s11/mhs1841/Documents/";
}
public static boolean isInCAN = false;
Peer(String bootStrap, int port) {
Peer.bootstrapPort = port;
Peer.bootStrap = bootStrap;
for (int i = 0; i < 4; i++) {
neighbours.add(new ArrayList<String>());
}
try {
ip = InetAddress.getLocalHost().toString().split("/")[1];
hostName = InetAddress.getLocalHost().toString().split("/")[0];
} catch (UnknownHostException e) {
System.out.println(e.getMessage());
}
}
private void sendJoinRequest(String response) throws UnknownHostException {
Point destination = getRandomPoint();
String ip = InetAddress.getLocalHost().toString().split("/")[1];
CANMessage message = new CANMessage("join", ip + ":"
+ String.valueOf(Peer.portforCAN) + ":" + hostName, destination);
String host[] = response.split(":");
try {
// Create socket to entry point and specific port.
Socket socket = new Socket(host[0], Integer.parseInt(host[1]));
ObjectOutputStream output = new ObjectOutputStream(
socket.getOutputStream());
// Send out the join message.
output.writeObject(message);
} catch (Exception exp) {
System.out.println(exp.getMessage());
}
}
private String getRandomNeighbor() {
ListIterator<ArrayList<String>> directionIterator = Peer.neighbours
.listIterator();
while (directionIterator.hasNext()) {
ArrayList<String> direction = directionIterator.next();
ListIterator<String> neighborIterator = direction.listIterator();
while (neighborIterator.hasNext()) {
String neighbor = neighborIterator.next();
return neighbor;
}
}
return null;
}
private void giveBootStrapAlternateEntryPoint() {
Socket socket = null;
PrintStream out = null;
try {
socket = new Socket(bootStrap, bootstrapPort);
out = new PrintStream(socket.getOutputStream());
String nnn = getRandomNeighbor();
// System.out.println(nnn);
out.println(nnn);
out.println(nnn);
out.close();
socket.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
System.out.println(e1.getMessage());
}
}
private void initiateMerge(String merger, String mergerType)
throws NumberFormatException, UnknownHostException, IOException {
// Give all my info to peer who is taking over.
CANMessage mergePackage = new CANMessage("tempmerge", Peer.peerZone,
Peer.neighbours, Peer.files);
giveBootStrapAlternateEntryPoint();
informNeighborsOfDeparture();
String host[] = merger.split(":");
Socket socket = new Socket(host[0], Integer.parseInt(host[1]));
ObjectOutputStream out = new ObjectOutputStream(
socket.getOutputStream());
out.writeObject(mergePackage);
out.close();
System.out.println("Sent out irregular merge request to " + merger);
socket.close();
Peer.files.clear();
Peer.peerZone = null;
Peer.neighbours = null;
Peer.isInCAN = false;
System.out.println();
System.out.println("Leaving CAN. Restart program to rejoin.");
System.exit(0);
}
private void initiateMerge(String merger) throws NumberFormatException,
UnknownHostException, IOException {
// Give all my info to peer who is taking over.
CANMessage mergePackage = new CANMessage("merge", Peer.peerZone,
Peer.neighbours, Peer.files);
giveBootStrapAlternateEntryPoint();
informNeighborsOfDeparture();
String host[] = merger.split(":");
Socket socket = new Socket(host[0], Integer.parseInt(host[1]));
ObjectOutputStream out = new ObjectOutputStream(
socket.getOutputStream());
out.writeObject(mergePackage);
out.close();
socket.close();
Peer.files.clear();
Peer.peerZone = null;
Peer.neighbours = null;
Peer.isInCAN = false;
System.out.println();
System.out.println("Leaving CAN. Restart program to rejoin.");
System.exit(0);
}
private String getSmallestNeighbor() {
double min = Double.MAX_VALUE;
String smallestPeer = null;
ListIterator<ArrayList<String>> directionIterator = Peer.neighbours
.listIterator();
while (directionIterator.hasNext()) {
ArrayList<String> direction = directionIterator.next();
ListIterator<String> neighborIterator = direction.listIterator();
while (neighborIterator.hasNext()) {
String neighbor = neighborIterator.next();
String host[] = neighbor.split(":");
try {
Socket socket = new Socket(host[0],
Integer.parseInt(host[1]));
ObjectOutputStream out = new ObjectOutputStream(
socket.getOutputStream());
InputStreamReader ireader = new InputStreamReader(
socket.getInputStream());
BufferedReader in = new BufferedReader(ireader);
CANMessage areaProbe = new CANMessage("area");
out.writeObject(areaProbe);
double area = Double.parseDouble(in.readLine());
if (area <= min) {
smallestPeer = new String(neighbor);
min = area;
}
in.close();
out.close();
socket.close();
} catch (Exception exp) {
System.out.println(exp.getMessage());
}
}
}
return smallestPeer;
}
private void attemptIrregularMerge() throws NumberFormatException,
UnknownHostException, IOException {
String smallest = getSmallestNeighbor();
if (smallest == null) {
System.out.println();
System.out.println("Leaving CAN. Restart program to rejoin CAN");
System.exit(0);
}
System.out.println("Smallest neighbor is : " + smallest);
initiateMerge(smallest, "temp");
}
private void informNeighborsOfDeparture() {
int i = 0;
ListIterator<ArrayList<String>> directionIterator = Peer.neighbours
.listIterator();
while (directionIterator.hasNext()) {
ArrayList<String> direction = directionIterator.next();
ListIterator<String> neighborIterator = direction.listIterator();
while (neighborIterator.hasNext()) {
String neighbor = neighborIterator.next();
String host[] = neighbor.split(":");
try {
// Contact neighbor with delete message.
Socket socket = new Socket(host[0],
Integer.parseInt(host[1]));
ObjectOutputStream out = new ObjectOutputStream(
socket.getOutputStream());
InputStreamReader ireader = new InputStreamReader(
socket.getInputStream());
BufferedReader in = new BufferedReader(ireader);
CANMessage message = new CANMessage("delete", Peer.CANid
+ ":" + Peer.hostName, (i + 2) % 4, Peer.peerZone);
out.writeObject(message);
} catch (ConnectException exp) {
System.out.println("Unable to connect to " + neighbor);
} catch (Exception exp) {
System.out.println(exp.getMessage());
}
}
// Go up a direction
i++;
}
}
public static synchronized void informNeighborsOfExistenceTemp() {
int i = 0;
ListIterator<ArrayList<String>> directionIterator = Peer.neighbours
.listIterator();
while (directionIterator.hasNext()) {
ArrayList<String> direction = directionIterator.next();
ListIterator<String> neighborIterator = direction.listIterator();
while (neighborIterator.hasNext()) {
String neighbor = new String(neighborIterator.next());
String host[] = neighbor.split(":");
try {
Socket socket = new Socket(host[0],
Integer.parseInt(host[1]));
ObjectOutputStream out = new ObjectOutputStream(
socket.getOutputStream());
InputStreamReader ireader = new InputStreamReader(
socket.getInputStream());
BufferedReader in = new BufferedReader(ireader);
CANMessage message = new CANMessage("update", Peer.CANid
+ ":" + Peer.hostName, (i + 2) % 4, Peer.tempZone);
out.writeObject(message);
String isNeighbor = in.readLine();
if (isNeighbor != null && isNeighbor.equals("no")) {
neighborIterator.remove();
}
in.close();
out.close();
socket.close();
} catch (NumberFormatException e) {
System.out.println(e.getMessage());
} catch (UnknownHostException e) {
System.out.println(e.getMessage());
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
i++;
}
}
public static synchronized void informNeighborsOfExistence() {
int i = 0;
ListIterator<ArrayList<String>> directionIterator = Peer.neighbours
.listIterator();
while (directionIterator.hasNext()) {
ArrayList<String> direction = directionIterator.next();
ListIterator<String> neighborIterator = direction.listIterator();
while (neighborIterator.hasNext()) {
String neighbor = new String(neighborIterator.next());
String host[] = neighbor.split(":");
try {
Socket socket = new Socket(host[0],
Integer.parseInt(host[1]));
ObjectOutputStream out = new ObjectOutputStream(
socket.getOutputStream());
InputStreamReader ireader = new InputStreamReader(
socket.getInputStream());
BufferedReader in = new BufferedReader(ireader);
CANMessage message = new CANMessage("update", Peer.CANid
+ ":" + Peer.hostName, (i + 2) % 4, Peer.peerZone);
out.writeObject(message);
String isNeighbor = in.readLine();
// Removing peers that are not neighbors anymore.
if (isNeighbor != null && isNeighbor.equals("no")) {
neighborIterator.remove();
}
in.close();
out.close();
socket.close();
} catch (ConnectException exp) {
System.out.println("Unable to connect to " + neighbor);
} catch (NumberFormatException e) {
System.out.println(e.getMessage());
} catch (UnknownHostException e) {
System.out.println(e.getMessage());
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println(e.getMessage());
}
}
i++;
}
}
private String getMergeCandidate() {
ArrayList<String> secondBest = new ArrayList<String>();
ListIterator<ArrayList<String>> directionIterator = Peer.neighbours
.listIterator();
while (directionIterator.hasNext()) {
ArrayList<String> direction = directionIterator.next();
ListIterator<String> neighborIterator = direction.listIterator();
while (neighborIterator.hasNext()) {
String neighbor = neighborIterator.next();
String host[] = neighbor.split(":");
try {
Socket socket = new Socket(host[0],
Integer.parseInt(host[1]));
ObjectOutputStream out = new ObjectOutputStream(
socket.getOutputStream());
InputStreamReader ireader = new InputStreamReader(
socket.getInputStream());
BufferedReader in = new BufferedReader(ireader);
CANMessage probe = new CANMessage("border", Peer.peerZone);
out.writeObject(probe);
boolean sameArea = Boolean.parseBoolean(in.readLine());
boolean overlap = Boolean.parseBoolean(in.readLine());
// Add to second choice list if edges at least overlap.
if (overlap)
secondBest.add(new String(neighbor));
if (sameArea && overlap)
return neighbor;
} catch (Exception exp) {
System.out.println(exp.getMessage());
}
}
}
// Return random second choice peers for take over.
if (!secondBest.isEmpty()) {
Random r = new Random();
int random = r.nextInt(secondBest.size());
return secondBest.get(random);
}
return null;
}
private Point getRandomPoint() {
Random r = new Random();
int x = r.nextInt(10);
int y = r.nextInt(10);
Point destination = new Point(x, y);
return destination;
}
private void joinCAN() throws IOException, BindException, Exception {
// Get port peer is dedicating to CAN
int port = getPortForCAN();
Socket socketToServer = new Socket();
try {
socketToServer.connect(new InetSocketAddress(bootStrap,
Peer.bootstrapPort));
} catch (IOException e) {
System.out.println(e.getMessage());
}
try {
InputStreamReader ipreader = new InputStreamReader(
socketToServer.getInputStream());
BufferedReader input = new BufferedReader(ipreader);
PrintStream output = new PrintStream(
socketToServer.getOutputStream());
output.println("authenticate");
login(input, output);
// System.out.println("sending join");
output.println("join");
output.println(portforCAN);
// Wait for response.
String response = input.readLine();
// First peer in CAN
if (response.equals("owner")) {
// Assign full space.
Peer.peerZone = new Zone(new Point(0.0, 0.0), new Point(10.0,
10.0));
isInCAN = true;
viewDetails();
startListeningInCAN();
informNeighborsOfExistence();
// System.out.println("Done");
} else if (response.equals("unrecognizedcommand"))
System.out.println("Server did not recognize command");
else {
sendJoinRequest(response);
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
// System.out.println(isInCAN);
// while(!isInCAN);
// System.out.println(isInCAN);
// System.out.println("HEEEEEEEEEEEERRRRRREEEE" + oldUser);
// if (oldUser) {
// System.out.println("Retreiving file list");
// getFile(userName + "_list.txt");
// System.out.println("Got file");
// moveFile(getDir() + hostName + "/ret/" + userName + "_list.txt");
// // new File(getDir()+hostName+"/ret/",userName+"_list.txt");
// System.out.println("do you want to view list of file you uploaded");
// Scanner sc = new Scanner(System.in);
// String reply1 = sc.next();
// if (reply1.equalsIgnoreCase("y")) {
// displayUserList();
// }
// } else {
if (!oldUser) {
// System.out.println("Backing up new file");
try {
backupFile(getDir() + userName + "_list.txt");
// new File(getDir()+hostName+"/ret/",userName+"_list.txt");
} catch (Exception e) {
e.printStackTrace();
}
}
// }
// System.out.println("All done !!!");
}
public Boolean authenticateUser(String username, String password,
BufferedReader input, PrintStream output) throws IOException,
ClassNotFoundException {
output.println("authenticate");
output.println(username);
output.println(password);
String reply = null;
try {
reply = input.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (reply.equals("loginsucc")) {
System.out.println("login succesfull");
oldUser = true;
return true;
} else {
if (reply.equalsIgnoreCase("wrongpass"))
return false;
else {
System.out.println("Username not found.");
System.out.println("Sign up?(y/n):");
Scanner in = new Scanner(System.in);
String decision = in.next();
if (decision.equalsIgnoreCase("y")) {
signup(input, output);
return true;
} else
return false;
}
}
}
private void moveFile(String path) throws IOException {
File oldFile = new File(path);
File newFile = new File(getDir() + userName + "_list.txt");
InputStream in = new FileInputStream(oldFile);
OutputStream out = new FileOutputStream(newFile);
byte[] buffer = new byte[1024];
int readbuff;
while ((readbuff = in.read(buffer)) > 0) {
out.write(buffer, 0, readbuff);
}
in.close();
out.close();
oldFile.delete();
}
private void displayUserList() throws Exception {
// System.out.println("Retreiving file list");
getFile(userName + "_list.txt");
// System.out.println("Got file");
File f = new File(getDir() + hostName + "/ret/" + userName
+ "_list.txt");
if (f.exists()) {
moveFile(getDir() + hostName + "/ret/" + userName + "_list.txt");
String path = getDir() + userName + "_list.txt";
try {
FileReader fc = new FileReader(path);
BufferedReader br = new BufferedReader(fc);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (FileNotFoundException e) {
System.out.println("file not found");
}
}
}
private void signup(BufferedReader input, PrintStream output)
throws IOException {
output.println("signup");
output.println(userName);
output.println(password);
String reply = input.readLine();
if (reply.equalsIgnoreCase("signupsucc"))
try {
createUserFileList();
} catch (Exception e) {
System.out.println("Error in creating file filelist");
// e.getStackTrace();
}
}
private void createUserFileList() {
String userlistfilename = getDir() + userName + "_list.txt";
try {
PrintWriter writer = new PrintWriter(userlistfilename, "UTF-8");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
public void login(BufferedReader input, PrintStream output) {
try {
boolean flag = true;
do {
if (!flag) {
System.out.println("Invalid Username/password");
}
System.out.print("Enter User Name: ");
Scanner sc = new Scanner(System.in);
userName = sc.next();
Console c = System.console();
char[] passArray = c.readPassword("Enter password: ");
password = new String(passArray);
flag = authenticateUser(userName, password, input, output);
} while (!flag);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
private void startListeningInCAN() throws IOException {
try {
File dir = new File("/home/stu12/s11/mhs1841/Documents/"
+ Peer.hostName);
if (!dir.exists())
dir.mkdir();
File ret = new File(dir.getAbsoluteFile() + "/ret");
if (!ret.exists())
ret.mkdir();
} catch (Exception exp) {
exp.printStackTrace();
}
// System.out.println("Listening at port: " + portforCAN);
new Thread(new PeerBackground(Peer.portforCAN)).start();
}
private int getPortForCAN() throws BindException, IOException {
System.out.print("Dedicated port : ");
Scanner in = new Scanner(System.in);
int port = in.nextInt();
// System.out.println("Port returned : " + port);
Peer.portforCAN = port;
Peer.CANid = ip + ":" + String.valueOf(Peer.portforCAN);
startListeningInCAN();
return port;
}
public static void viewDetails() {
System.out.println();
try {
System.out.print("Peer: "
+ InetAddress.getLocalHost().getCanonicalHostName());
System.out.println(" @ " + Peer.CANid);
} catch (UnknownHostException e) {
System.out.println(e.getMessage());
}
// System.out.println("Zone: " + Peer.peerZone.toString());
// if (tempZone != null)
// System.out.println("Zone: " + Peer.tempZone.toString());
// // Printing neighbor details
// System.out.println("Neighbors:");
// int count = 0;
// for (ArrayList<String> direction : neighbours) {
// if (!direction.isEmpty()) {
// if (count == 0)
// System.out.print(" Left: ");
// else if (count == 1)
// System.out.print(" Top: ");
// else if (count == 2)
// System.out.print(" Right: ");
// else
// System.out.print(" Bottom: ");
// System.out.println(direction);
// }
// count++;
// }
// System.out.println("Files:");
// System.out.print(" ");
// for (String filename : files.keySet()) {
// System.out.print(filename + " ");
// }
System.out.println();
}
private static void search(String filename) {
Point locationOfFile = getHashFileName(filename);
if (peerZone.isPointInZone(locationOfFile)) {
if (files.keySet().contains(filename))
System.out.println("File is here with you at " + hostName + ":"
+ CANid);
else
System.out.println("Failure!");
}
// else release into CAN.
else {
PeerWorker worker = new PeerWorker();
ArrayList<String> path = new ArrayList<String>();
CANMessage search = new CANMessage(path, "search", CANid,
locationOfFile, filename);
worker.greedyRoute(search);
}
}
private void insertFile(String filename) {
Point insertionPoint = getHashFileName(filename);
// Check if destination is in own zone and insert.
if (peerZone.isPointInZone(insertionPoint)) {
files.put(filename, filename);
System.out.println("File inserted here :" + Peer.CANid + ":"
+ Peer.hostName);
}
// else release into CAN.
else {
PeerWorker worker = new PeerWorker();
CANMessage insert = new CANMessage("insert", Peer.CANid,
insertionPoint, filename);
worker.greedyRoute(insert);
}
}
public void backupFile(String filename) throws Exception {
File checkIfFileExists = new File(filename);
if (!checkIfFileExists.exists())
System.out.println("File not found.");
String oldName = filename;
Utilities.encrypt(filename, Peer.userName, Peer.password);
// Split encrypted file
filename = filename + ".enc";
Utilities.splitFile(filename, 2);
File encrypt = new File(filename);
for (int part = 1; part <= 2; ++part) {
// Get point where file is supposed to go based on hashes.
File file = new File(filename + ".00" + part);
String firstHash = Utilities.sha1(file.getName());
// first Copy
sendToTarget(file, firstHash);
// second copy
String secondHash = Utilities.sha1(firstHash);
sendToTarget(file, secondHash);
}
File f = new File(oldName);
// Write backed up file to file list.
String path = getDir() + userName + "_list.txt";
if (!f.getName().contains("_list")) {
try (PrintWriter out = new PrintWriter(new BufferedWriter(
new FileWriter(path, true)))) {
out.println(f.getName());
} catch (IOException e) {
// exception handling left as an exercise for the reader
}
}
backupUpdatedFileList(path);
}
private void backupUpdatedFileList(String filename) throws Exception {
File checkIfFileExists = new File(filename);
if (!checkIfFileExists.exists())
System.out.println("File not found.");
String oldName = filename;
Utilities.encrypt(filename, Peer.userName, Peer.password);
// Split encrypted file
filename = filename + ".enc";
Utilities.splitFile(filename, 2);
File encrypt = new File(filename);
for (int part = 1; part <= 2; ++part) {
// Get point where file is supposed to go based on hashes.
File file = new File(filename + ".00" + part);
String firstHash = Utilities.sha1(file.getName());
// first Copy
sendToTarget(file, firstHash);
// second copy
String secondHash = Utilities.sha1(firstHash);
sendToTarget(file, secondHash);
}
}
public void getFile(String filename) throws Exception {
// System.out.println("Retreiving " + filename);
String part1At, part2At;
String originalFileName = filename;
String newFileName = filename + ".dec";
// Looking for .enc files at remote location.
filename = filename + ".enc";
part1At = doPart(filename, 1);
// System.out.println("Found part 1 @" + part1At);
// Find part 1.
if (part1At == null) {
System.out
.println("Part 1 replicas not found. File cannot be recovered.");
return;
}
// Find part 2
part2At = doPart(filename, 2);
// System.out.println("Found part 2 @" + part1At);
if (part2At == null) {
System.out
.println("Part 2 replicas not found. File cannot be recovered.");
return;
}
// Both parts found, download parallelly.
parallelDownload(part1At, part2At, filename);
/*
* Join fragments. Arguments: filename = path of fragments...directory
* path ending with /ret/ 2nd argument is name of fragments. 3rd
* argument is number of parts. 4th arg is name of file to be stored
* after decryption
*/
String pathOfFragments = getDir() + hostName + "/ret/";
System.out.print("Joining fragments... ");
Utilities.join(pathOfFragments, filename, 2, newFileName);
System.out.println("complete.");
System.out.print("Decrypting...");
Utilities.decrypt(pathOfFragments + newFileName, Peer.userName,
Peer.password, originalFileName);
System.out.println("complete.");
}
private void parallelDownload(String part1At, String part2At,
String filename) throws InterruptedException {
ExecutorService es = Executors.newCachedThreadPool();
/*
* Args to parallel downloader constructor: 1st = name of file as stored
* in remote loccation 2nd = Address of remote location 3rd = File name
* for downloaded file. Join using this file name
*/
ParallelDownloader p1 = new ParallelDownloader(filename + ".001",
part1At, filename + ".001");
ParallelDownloader p2 = new ParallelDownloader(filename + ".002",
part2At, filename + ".002");
es.execute(p1);
es.execute(p2);
boolean finsihed = es.awaitTermination(4, TimeUnit.SECONDS);
// System.out.println("Fragments downloaded.");
}
private String doPart(String filename, int partNo)
throws NoSuchAlgorithmException, IOException,
NumberFormatException, ClassNotFoundException, InterruptedException {
String part1At = null;
// Compute file name for part.
String id = filename + ".00" + String.valueOf(partNo);
for (int replica = 1; replica <= 2; ++replica) {
// Get hash for replica 1 and compute location.
String hash = Utilities.sha1(id);
Point locationOfPart_1 = getHashFileName(hash);
// System.out.println(locationOfPart_1);
// Get open socket to receive replies.
int port = Utilities.getAvailablePort();
ServerSocket s = new ServerSocket(port);
String source = ip + ":" + String.valueOf(port);
/*
* Message containing: "check" command source = this/requesting
* peers ID. filename with appropriate part number.
*/
CANMessage m = new CANMessage(new ArrayList<String>(), "check",
source, locationOfPart_1, filename + ".00"
+ String.valueOf(partNo));
PeerWorker w = new PeerWorker();
w.myMethod(m);
// System.out.println("Wating for reply");
// Wait for reply.
Socket reply = s.accept();
// System.out.println("gotreply");
InputStream stream = reply.getInputStream();
InputStreamReader ipReader = new InputStreamReader(stream);
BufferedReader input = new BufferedReader(ipReader);
// System.out.println("Reading");
String found = input.readLine();
// System.out.println(" Got reply: " + found);
// File not found, try second copy.
if (found.equalsIgnoreCase("notfound")) {
id = hash;
continue;
} else {
part1At = found;
break;
}
}
// Return address of location where file fragment found.
return part1At;
}
private void sendToTarget(File file, String hash)
throws NumberFormatException, ClassNotFoundException, IOException,
InterruptedException {
Point targetForFirstPiece = getHashFileName(hash);
// Send message to target coordinates.