root / src / peer / protocols / restore / Restore.java @ 2
History | View | Annotate | Download (1.71 KB)
1 | 2 | up20150644 | package peer.protocols.restore; |
---|---|---|---|
2 | |||
3 | import java.io.File; |
||
4 | import java.io.IOException; |
||
5 | import java.util.concurrent.BlockingQueue; |
||
6 | |||
7 | import chunk.Chunk; |
||
8 | import disk.ChunkManagement; |
||
9 | import message.Message; |
||
10 | import peer.Peer; |
||
11 | import peer.channels.Sender; |
||
12 | import peer.channels.SenderUDP; |
||
13 | |||
14 | /**
|
||
15 | * Restore
|
||
16 | */
|
||
17 | public class Restore implements Runnable { |
||
18 | |||
19 | private Peer peer;
|
||
20 | private String filePath; |
||
21 | private File file; |
||
22 | |||
23 | public Restore(Peer peer, String filePath) { |
||
24 | this.peer = peer;
|
||
25 | this.filePath = filePath;
|
||
26 | file = new File(filePath); |
||
27 | } |
||
28 | |||
29 | public void sendGetChunk(int chunkNo) { |
||
30 | Message message = Message.parseGetChunkMessage(Chunk.generateFileId(file), chunkNo, peer); |
||
31 | try {
|
||
32 | peer.sendToMc(message); |
||
33 | } catch (IOException e) { |
||
34 | e.printStackTrace(); |
||
35 | } |
||
36 | } |
||
37 | |||
38 | public void restore() { |
||
39 | File originalFile = new File(filePath); |
||
40 | if (!originalFile.exists()) {
|
||
41 | System.out.println("file not found"); |
||
42 | return;
|
||
43 | } |
||
44 | int chunksNo = Chunk.getNumberOfFileChunks(originalFile);
|
||
45 | Chunk[] chunks = new Chunk[chunksNo]; |
||
46 | String fileId = Chunk.generateFileId(originalFile);
|
||
47 | for (int i = 0; i < chunksNo; i++) { |
||
48 | sendGetChunk(i + 1);
|
||
49 | BlockingQueue<Chunk> queue = ChunkManagement.getInstance().getRestoreChunks();
|
||
50 | try {
|
||
51 | System.out.println("Waiting for chunk " + (i+1)); |
||
52 | Chunk chunk = queue.take(); |
||
53 | if (chunk.getFileID().equals(fileId)){
|
||
54 | chunks[i] = chunk; |
||
55 | System.out.println("received chunk " + chunk.getChunkNo()); |
||
56 | } |
||
57 | else {
|
||
58 | queue.put(chunk); |
||
59 | } |
||
60 | } catch (InterruptedException e) { |
||
61 | e.printStackTrace(); |
||
62 | } |
||
63 | } |
||
64 | peer.getDisk().restoreFile(chunks,originalFile.getName()); |
||
65 | } |
||
66 | |||
67 | @Override
|
||
68 | public void run() { |
||
69 | restore(); |
||
70 | } |
||
71 | |||
72 | } |