root / src / peer / protocols / restore / Restore.java @ 3
History | View | Annotate | Download (1.64 KB)
1 |
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 |
int i=0; |
48 |
while (i < chunksNo) {
|
49 |
sendGetChunk(i + 1);
|
50 |
BlockingQueue<Chunk> queue = ChunkManagement.getInstance().getRestoreChunks();
|
51 |
try {
|
52 |
System.out.println("Waiting for chunk " + (i+1)); |
53 |
Chunk chunk = queue.take(); |
54 |
if (chunk.getFileID().equals(fileId) && chunk.getChunkNo() == i+1){ |
55 |
chunks[i] = chunk; |
56 |
i++; |
57 |
System.out.println("received chunk " + chunk.getChunkNo()); |
58 |
} |
59 |
} catch (InterruptedException e) { |
60 |
e.printStackTrace(); |
61 |
} |
62 |
} |
63 |
peer.getDisk().restoreFile(chunks,originalFile.getName()); |
64 |
} |
65 |
|
66 |
@Override
|
67 |
public void run() { |
68 |
restore(); |
69 |
} |
70 |
|
71 |
} |