root / threads / ReceiveGetChunk.java @ 15
History | View | Annotate | Download (2.52 KB)
1 | 15 | up20160473 | |
---|---|---|---|
2 | package threads; |
||
3 | |||
4 | import java.io.File; |
||
5 | import java.io.FileInputStream; |
||
6 | import java.io.FileOutputStream; |
||
7 | import java.io.IOException; |
||
8 | import java.nio.charset.StandardCharsets; |
||
9 | import java.util.Random; |
||
10 | import java.util.concurrent.TimeUnit; |
||
11 | |||
12 | import chunk.*; |
||
13 | import server.*; |
||
14 | |||
15 | public class ReceiveGetChunk implements Runnable { |
||
16 | |||
17 | private String fileId; |
||
18 | private int chunkNum; |
||
19 | |||
20 | |||
21 | public ReceiveGetChunk( String fileId, int chunkNr) { |
||
22 | this.fileId = fileId;
|
||
23 | this.chunkNum = chunkNr;
|
||
24 | } |
||
25 | |||
26 | @Override
|
||
27 | public void run() { |
||
28 | |||
29 | for (int i = 0; i < Server.getStorage().getSavedChunks().size(); i++) { |
||
30 | if (isSameChunk(Server.getStorage().getSavedChunks().get(i).getfileId(), Server.getStorage().getSavedChunks().get(i).getNum()) && !isAbortSend()) {
|
||
31 | String header = "CHUNK " + "1.0" + " " + Server.getServerId() + " " + this.fileId + " " + this.chunkNum + "\r\n\r\n"; |
||
32 | |||
33 | try {
|
||
34 | byte[] asciiHeader = header.getBytes(StandardCharsets.US_ASCII); |
||
35 | |||
36 | String chunkPath = "database/" + Server.getServerId() + "/" + fileId + "." + chunkNum; |
||
37 | |||
38 | File file = new File(chunkPath); |
||
39 | byte[] body = new byte[(int) file.length()]; |
||
40 | FileInputStream in = new FileInputStream(file); |
||
41 | in.read(body); |
||
42 | |||
43 | byte[] message = new byte[asciiHeader.length + body.length]; |
||
44 | System.arraycopy(asciiHeader, 0, message, 0, asciiHeader.length); |
||
45 | System.arraycopy(body, 0, message, asciiHeader.length, body.length); |
||
46 | |||
47 | SendMessage sendThread = new SendMessage(message, "mdr"); |
||
48 | System.out.println("Sent" + "CHUNK " + "1.0" + " " + Server.getServerId() + " " + this.fileId + " " + this.chunkNum); |
||
49 | Random random = new Random(); |
||
50 | Server.getThreadLauncher().schedule(sendThread, random.nextInt(401), TimeUnit.MILLISECONDS); |
||
51 | } catch (IOException e) { |
||
52 | e.printStackTrace(); |
||
53 | } |
||
54 | |||
55 | } |
||
56 | |||
57 | } |
||
58 | } |
||
59 | private boolean isSameChunk(String fileId, int chunkNr) { |
||
60 | return fileId.equals(this.fileId) && chunkNr == this.chunkNum; |
||
61 | } |
||
62 | |||
63 | private boolean isAbortSend() { |
||
64 | for (int i = 0; i < Server.getStorage().getReceivedChunks().size(); i++) { |
||
65 | if (isSameChunk(Server.getStorage().getReceivedChunks().get(i).getfileId(), Server.getStorage().getReceivedChunks().get(i).getNum()))
|
||
66 | return true; |
||
67 | } |
||
68 | return false; |
||
69 | } |
||
70 | } |