-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPeerWorker.java
More file actions
788 lines (610 loc) · 21.3 KB
/
PeerWorker.java
File metadata and controls
788 lines (610 loc) · 21.3 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
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Map;
import javax.net.ssl.HostnameVerifier;
class PeerWorker implements Runnable {
Socket client = null;
public PeerWorker(Socket temp, int port) throws UnknownHostException,
IOException {
client = temp;
}
public PeerWorker() {
}
// Generic metod to send object to address: both in arguments.
public void sendMessageTo(String address, CANMessage message)
throws NumberFormatException, UnknownHostException, IOException {
String host[] = address.split(":");
Socket socket = new Socket(host[0], Integer.parseInt(host[1]));
ObjectOutputStream out = new ObjectOutputStream(
socket.getOutputStream());
out.writeObject(message);
out.close();
socket.close();
}
public void greedyRoute(CANMessage message) {
try {
// Get neighbor nearest to destination
ArrayList<ArrayList<Double>> distanceMatrix = getDistanceMatrix(message.destination);
String nextHop = getNextHop(distanceMatrix);
// Add self to path if search request.
if (message.requestType.equalsIgnoreCase("search")
|| message.requestType.equalsIgnoreCase("backuptarget"))
message.path.add(Peer.CANid + " : " + Peer.hostName);
sendMessageTo(nextHop, message);
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
private String getNextHop(ArrayList<ArrayList<Double>> distanceMatrix) {
int x = 0, y = 0;
double min = Double.MAX_VALUE;
for (int i = 0; i < distanceMatrix.size(); i++) {
// Calculating minimum distance to destination among neighbors
ArrayList<Double> direction = distanceMatrix.get(i);
for (int j = 0; j < direction.size(); j++) {
if (direction.get(j) < min) {
min = direction.get(j);
x = i;
y = j;
}
}
}
String nextHop = Peer.neighbours.get(x).get(y);
return nextHop;
}
private ArrayList<ArrayList<Double>> getDistanceMatrix(Point destination)
throws UnknownHostException, IOException {
CANMessage getDistance = new CANMessage("distance", Peer.CANid,
destination);
ObjectOutputStream out;
BufferedReader in;
InputStreamReader ir;
ArrayList<ArrayList<Double>> distanceMatrix = new ArrayList<ArrayList<Double>>();
// Get distance of neighbors to destination.
for (int i = 0; i < Peer.neighbours.size(); i++) {
distanceMatrix.add(new ArrayList<Double>());
ArrayList<String> direction = Peer.neighbours.get(i);
if (direction.isEmpty())
continue;
for (int j = 0; j < direction.size(); j++) {
String neighbor = direction.get(j);
String host[] = neighbor.split(":");
Socket socket = new Socket(host[0], Integer.parseInt(host[1]));
try {
out = new ObjectOutputStream(socket.getOutputStream());
out.writeObject(getDistance);
ir = new InputStreamReader(socket.getInputStream());
in = new BufferedReader(ir);
double reply = Double.parseDouble(in.readLine());
out.close();
in.close();
// Waiting for reply from neighbor.
distanceMatrix.get(i).add(reply);
socket.close();
} catch (Exception exp) {
System.out.println(exp.getMessage());
}
}
}
return distanceMatrix;
}
double getDistanceToPoint(Point destination) {
try {
double distance = Peer.peerZone.getDistanceToPoint(destination);
return distance;
} catch (Exception exp) {
return Double.MAX_VALUE;
}
}
private CANMessage handOverTempZone(String node) {
System.out.println("Attempting to transfer temp zone.");
// Hand over entire temp zone.
Zone newZone = Peer.tempZone;
Peer.tempZone = null;
// Hand over files in temp zone.
HashMap<String, String> files = new HashMap<String, String>();
Iterator<Map.Entry<String, String>> iter = Peer.files.entrySet()
.iterator();
while (iter.hasNext()) {
Map.Entry<String, String> entry = iter.next();
Point hash = Peer.getHashFileName(entry.getKey());
if (Peer.tempZone.isPointInZone(hash)) {
files.put(entry.getKey(), entry.getValue());
iter.remove();
}
}
ArrayList<ArrayList<String>> neighboursToSend = new ArrayList<ArrayList<String>>();
getCopyOfNeighbors(neighboursToSend);
CANMessage welcome = new CANMessage("welcome", newZone,
neighboursToSend, files);
return welcome;
}
void InitiateNodeJoin(String node) {
CANMessage welcome = null;
boolean flag = false, trigger = false;
ObjectOutputStream out;
try {
// Create new zone, neighbors and file list.
Zone newZone = null;
ArrayList<ArrayList<String>> neighboursToSend = new ArrayList<ArrayList<String>>();
HashMap<String, String> files = new HashMap<String, String>();
int count = 0;
getCopyOfNeighbors(neighboursToSend);
// Check if peer has temp zone it wants to hand over.
if (Peer.tempZone != null) {
welcome = handOverTempZone(node);
flag = true;
trigger = true;
}
else if (Peer.peerZone.isZoneSquare()
|| Peer.peerZone.isBroaderThanTaller()) {
newZone = Peer.peerZone.splitVertically();
files = new HashMap<String, String>();
Iterator<Map.Entry<String, String>> iter = Peer.files
.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, String> entry = iter.next();
Point hash = Peer.getHashFileName(entry.getKey());
if (newZone.isPointInZone(hash)) {
files.put(entry.getKey(), entry.getValue());
iter.remove();
}
}
// Clear all left neighbors.
neighboursToSend.get(0).clear();
// // Add self
neighboursToSend.get(0).add(Peer.CANid + ":" + Peer.hostName);
CANMessage message = new CANMessage("delete", Peer.CANid + ":"
+ Peer.hostName, 0, Peer.peerZone);
// Update this nodes right neighbors to remove it.
for (String neighbor : Peer.neighbours.get(2)) {
sendMessageTo(neighbor, message);
}
// Add new node to list of my neighbors on the right.
Peer.neighbours.get(2).clear();
Peer.neighbours.get(2).add(node);
} else {
newZone = Peer.peerZone.splitHorizontally();
files = new HashMap<String, String>();
Iterator<Map.Entry<String, String>> iter = Peer.files
.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, String> entry = iter.next();
Point hash = Peer.getHashFileName(entry.getKey());
if (newZone.isPointInZone(hash)) {
files.put(entry.getKey(), entry.getValue());
iter.remove();
}
}
// Clear all bottom neighbors.
neighboursToSend.get(3).clear();
// Add self as bottom neighbor
neighboursToSend.get(3).add(Peer.CANid + ":" + Peer.hostName);
CANMessage message = new CANMessage("delete", Peer.CANid + ":"
+ Peer.hostName, 3, Peer.peerZone);
// Update this nodes top neighbors to remove it.
for (String neighbor : Peer.neighbours.get(1)) {
sendMessageTo(neighbor, message);
}
// Add new node to list of my neighbors on top
Peer.neighbours.get(1).clear();
Peer.neighbours.get(1).add(node);
}
if (!flag)
welcome = new CANMessage("welcome", newZone, neighboursToSend,
files);
// Send new zone, files and neighbors to new peer.
sendMessageTo(node, welcome);
if (trigger) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
System.out.println(e.getMessage());
}
Peer.informNeighborsOfExistenceTemp();
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
private void getCopyOfNeighbors(
ArrayList<ArrayList<String>> neighboursToSend) {
for (int i = 0; i < Peer.neighbours.size(); i++) {
neighboursToSend.add(new ArrayList<String>());
ArrayList<String> direction = Peer.neighbours.get(i);
if (direction.isEmpty())
continue;
for (int j = 0; j < direction.size(); j++) {
neighboursToSend.get(i).add(direction.get(j));
}
}
}
void serviceMessage(CANMessage message) throws IOException,
ClassNotFoundException, NumberFormatException, InterruptedException {
// Peer wants to join
if (message.requestType.equals("join")) {
InitiateNodeJoin(message.source);
try {
Thread.sleep(1000, 0);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
System.out.println(e.getMessage());
}
Peer.informNeighborsOfExistence();
}
// Temporary merge for irregular join.
if (message.requestType.equals("tempmerge")) {
performTempMerge(message);
}
if (message.requestType.equals("area")) {
// Get area.
double area = Peer.peerZone.Area();
PrintStream out = new PrintStream(client.getOutputStream());
out.println(area);
}
else if (message.requestType.equals("found")
|| message.requestType.equals("notfound")) {
processSearchResult(message);
} else if (message.requestType.equals("foundtarget")) {
uploadFile(message);
}
// Calculating distance for greedy routing.
else if (message.requestType.equals("distance")) {
double distance = getDistanceToPoint(message.destination);
PrintStream out = new PrintStream(client.getOutputStream());
out.println(distance);
}
else if (message.requestType.equalsIgnoreCase("merge")) {
performMerge(message);
} else if (message.requestType.equalsIgnoreCase("check")) {
checkForFile(message);
}
// Updating neighbors
else if (message.requestType.equals("update")) {
updateNeighbors(message);
}
// Deleting neighbors
else if (message.requestType.equals("delete")) {
Peer.neighbours.get(message.side).remove(message.source);
}
// In CAN, update neighbors and stuff.
else if (message.requestType.equals("welcome")) {
getJoinDetails(message);
Peer.viewDetails();
} else if (message.requestType.equals("sendfile")) {
sendFile(message);
}
// Insert file at this location
else if (message.requestType.equals("insert")) {
insertFile(message);
}
// Insertion confirmation.
else if (message.requestType.equals("inserted")) {
System.out.println(message.message + " " + message.messageFrom);
}
else if (message.requestType.equals("search")) {
checkForFile(message);
} else if (message.requestType.equals("border")) {
getBorderAndAreaStats(message);
} else if (message.requestType.equalsIgnoreCase("backuptarget")) {
ArrayList<String> path = new ArrayList<String>(message.path);
path.add(Peer.CANid + " : " + Peer.hostName);
CANMessage searchStatus = new CANMessage(path, "foundtarget",
message.file, Peer.hostName + " " + Peer.CANid);
sendMessageTo(message.source, searchStatus);
}
else if (message.requestType.equalsIgnoreCase("backup")) {
File newFile = new File(Peer.getDir() + "/" + Peer.hostName + "/"
+ message.message);
try {
// // File already exists here. Deleting file to maintain consistency.
// if (newFile.exists()) {
// System.out
// .println("This file already exists. Deleting file to maintain fragment consistency");
// newFile.delete();
// }
FileOutputStream fos = new FileOutputStream(newFile, false);
byte[] buffer = new byte[1024];
int count;
InputStream in = client.getInputStream();
// System.out.println(in.available());
while ((count = in.read(buffer)) != -1) {
fos.write(buffer, 0, count);
}
if (!newFile.getName().contains("_list"))
System.out.println(newFile.getName() + " received.");
fos.close();
client.close();
} catch (Exception exp) {
exp.printStackTrace();
}
}
}
private void sendFile(CANMessage message) throws NumberFormatException,
UnknownHostException, IOException {
String dirString = Peer.getDir() + "/" + Peer.hostName;
String file = dirString + "/" + message.file;
// System.out.println(client.getRemoteSocketAddress() + " wants " +
// file);
String requester = client.getRemoteSocketAddress().toString();
requester = requester.substring(1);
String host[] = requester.split(":");
// System.out.println("Making connection to " + host[0] + " at " +
// message.sendToPort);
Socket s = new Socket(host[0], message.sendToPort);
byte[] buffer = new byte[1024];
int count;
OutputStream out = s.getOutputStream();
BufferedInputStream in = new BufferedInputStream(new FileInputStream(
file));
// System.out.println("sending " + file);
while ((count = in.read(buffer)) != -1) {
out.write(buffer, 0, count);
out.flush();
}
// System.out.println("File sent");
// file.delete();
s.close();
}
private void updateNeighbors(CANMessage message) throws IOException {
String reply = "no";
if (Peer.isInCAN) {
if (Peer.peerZone.isOverlap(message.zone)) {
reply = "yes";
if (!Peer.neighbours.get(message.side).contains(message.source)) {
Peer.neighbours.get(message.side).add(message.source);
}
} else {
Peer.neighbours.get(message.side).remove(message.source);
}
String source = message.source;
String host[] = source.split(":");
PrintStream out = new PrintStream(client.getOutputStream());
out.println(reply);
out.close();
// socket.close();
}
}
private void processSearchResult(CANMessage message) {
if (message.requestType.equals("found")) {
System.out.println("File found at : " + message.messageFrom);
// Print path to file.
System.out.println();
System.out.println("Search route to file:");
for (String node : message.path) {
System.out.println(node);
}
} else
System.out.println("Failure.");
}
private void uploadFile(CANMessage message) throws UnknownHostException,
IOException, InterruptedException {
String target = message.messageFrom;
int index = target.indexOf(" ");
target = target.substring(index + 1);
// System.out.println("File target is: " + message.messageFrom);
String host[] = target.split(":");
Socket s = new Socket(host[0], Integer.parseInt(host[1]));
CANMessage backupMessage = new CANMessage("backup", message.message, "");
ObjectOutputStream os = new ObjectOutputStream(s.getOutputStream());
sendMessageToNode(target, backupMessage, os);
if (message.message == null)
System.out.println("File null !!");
else {
// System.out.println(message.file);
// File name is in message objects message field inserted in method
// service message "backuptarget" case of if-else structure.
File file = new File(Peer.getDir() + "/" + message.message);
streamFile(file, os, s);
}
}
// Streams file over out stream over open socket.
public void streamFile(File file, ObjectOutputStream outStream, Socket s) {
try{
byte[] buffer = new byte[1024];
int count;
OutputStream out = s.getOutputStream();
BufferedInputStream in = new BufferedInputStream(new FileInputStream(
file));
// System.out.println("sending " + file);
while ((count = in.read(buffer)) != -1) {
out.write(buffer, 0, count);
out.flush();
}
// System.out.println("File sent");
// file.delete();
s.close();
}catch(Exception exp){
// System.out.println("stream :" + exp.getMessage());
}
}
public void sendMessageToNode(String address, CANMessage message,
ObjectOutputStream out) throws NumberFormatException,
UnknownHostException, IOException, InterruptedException {
String host[] = address.split(":");
Socket socket = new Socket(host[0], Integer.parseInt(host[1]));
out.writeObject(message);
}
static void copy(InputStream in, OutputStream out) throws IOException {
System.out.println("In copy");
byte[] buf = new byte[8192];
int len = 0;
while ((len = in.read(buf)) != -1) {
System.out.println("writing" + len + " bytes");
out.write(buf, 0, len);
System.out.println("Wrote");
}
System.out.println("Exiting copy");
}
@SuppressWarnings("unchecked")
private void performMerge(CANMessage message) {
// Get all files
Peer.files
.putAll((Map<? extends String, ? extends String>) message.files);
// Merge zones.
Peer.peerZone.merge((Zone) message.newZone);
mergeNeighbors(message, "regular");
}
private void performTempMerge(CANMessage message) {
// Get all files
Peer.files
.putAll((Map<? extends String, ? extends String>) message.files);
Peer.tempZone = (Zone) message.newZone;
mergeNeighbors(message, "temp");
}
private void mergeNeighbors(CANMessage message, String type) {
ArrayList<ArrayList<String>> receivedNeighbors = (ArrayList<ArrayList<String>>) message.neighbors;
ListIterator<ArrayList<String>> directionIterator = receivedNeighbors
.listIterator();
int dir = 0;
while (directionIterator.hasNext()) {
ArrayList<String> direction = directionIterator.next();
ListIterator<String> neighborIterator = direction.listIterator();
while (neighborIterator.hasNext()) {
String str = new String(neighborIterator.next());
// Ignoring already existing neighbors.
if (!Peer.neighbours.get(dir).contains(str)) {
// Ignoring self.
if (!str.equalsIgnoreCase(Peer.CANid + ":" + Peer.hostName)) {
Peer.neighbours.get(dir).add(str);
}
}
}
dir++;
if (type.equalsIgnoreCase("regular"))
Peer.informNeighborsOfExistence();
else
Peer.informNeighborsOfExistenceTemp();
}
}
private void getBorderAndAreaStats(CANMessage message) {
boolean sameArea = false;
boolean completeOverLap = false;
if (message.zone.Area() == Peer.peerZone.Area())
sameArea = true;
if (Peer.peerZone.isEdgeCompleteOverlap(message.zone))
completeOverLap = true;
try {
PrintStream out = new PrintStream(client.getOutputStream());
out.println(sameArea);
out.println(completeOverLap);
out.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
public void checkForFile(CANMessage message) throws IOException {
boolean found = checkIfFilePresentInYourDir(message.file);
// System.out.println("Replying to " + message.source);
String host[] = message.source.split(":");
Socket socket = new Socket(host[0], Integer.parseInt(host[1]));
OutputStream out = socket.getOutputStream();
PrintStream ps = new PrintStream(out);
if (found)
ps.println(Peer.CANid);
else
ps.println("notfound");
socket.close();
}
public boolean checkIfFilePresentInYourDir(String file) {
// Get full path name for file and return true if exists.
String path = Peer.getDir() + Peer.hostName + "/" + file;
// path = "/home/mandeep/got.pdf";
File filePath = new File(path);
return filePath.exists();
}
private void insertFile(CANMessage message) {
Peer.files.put(message.file, message.file);
try {
CANMessage confirm = new CANMessage("inserted", "File inserted at "
+ Peer.hostName, Peer.CANid);
sendMessageTo(message.source, confirm);
} catch (NumberFormatException e) {
System.out.println(e.getMessage());
} catch (UnknownHostException e) {
System.out.println(e.getMessage());
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
private void getJoinDetails(CANMessage message) {
Peer.peerZone = (Zone) message.newZone;
Peer.neighbours = (ArrayList<ArrayList<String>>) message.neighbors;
Peer.files = (HashMap<String, String>) message.files;
Peer.isInCAN = true;
Peer.informNeighborsOfExistence();
}
public void myMethod(CANMessage message) throws NumberFormatException, ClassNotFoundException, IOException, InterruptedException{
processMessage(message);
}
public void processMessage(CANMessage message) throws IOException,
ClassNotFoundException, NumberFormatException, InterruptedException {
if (message.requestType.equals("update")
|| message.requestType.equals("delete")
|| message.requestType.equals("welcome")
|| message.requestType.equals("distance")
|| message.requestType.equals("inserted")
|| message.requestType.equals("found")
|| message.requestType.equals("foundtarget")
|| message.requestType.equals("notfound")
|| message.requestType.equals("border")
|| message.requestType.equals("merge")
|| message.requestType.equals("area")
|| message.requestType.equals("backup")
|| message.requestType.equals("sendfile")
|| message.requestType.equals("tempmerge")
|| message.requestType.equals("backup")) {
serviceMessage(message);
} else if (Peer.peerZone.isPointInZone(message.destination)) {
serviceMessage(message);
} else {
greedyRoute(message);
}
}
public void run() {
ObjectInputStream ipReader = null;
try {
if (client == null)
System.out
.println("Error initializing thread client for Peer.");
else {
ipReader = new ObjectInputStream(client.getInputStream());
// read CAN message from peer.
CANMessage message = (CANMessage) ipReader.readObject();
processMessage(message);
}
} catch (EOFException eof) {
// System.out.println("eof");
} catch (Exception exp) {
// System.out.println("wrun:" + exp.getMessage());;
}
}
public static void main(String args[]) throws IOException {
int port = Utilities.getAvailablePort();
ServerSocket s = new ServerSocket(port);
PeerWorker w = new PeerWorker();
CANMessage m = new CANMessage(new ArrayList<String>(), "check", s
.getInetAddress().toString(), new Point(3., 4.0), "got.pdf");
w.checkForFile(m);
}
}