root / threads / ReceivePutchunk.java @ 15
History | View | Annotate | Download (2.24 KB)
1 |
package threads; |
---|---|
2 |
|
3 |
import java.io.File; |
4 |
import java.io.FileOutputStream; |
5 |
import java.io.IOException; |
6 |
import chunk.*; |
7 |
import server.*; |
8 |
|
9 |
public class ReceivePutchunk implements Runnable { |
10 |
|
11 |
private Double version; |
12 |
private String fileId; |
13 |
private int chunkNr; |
14 |
private int replicationDegree; |
15 |
private byte[] content; |
16 |
|
17 |
public ReceivePutchunk(double version, String fileId, int chunkNr, int replicationDegree, byte[] content) { |
18 |
this.version = version;
|
19 |
this.fileId = fileId;
|
20 |
this.chunkNr = chunkNr;
|
21 |
this.replicationDegree = replicationDegree;
|
22 |
this.content = content;
|
23 |
} |
24 |
|
25 |
@Override
|
26 |
public void run() { |
27 |
|
28 |
String key = fileId + "." + chunkNr; |
29 |
|
30 |
for (int i = 0; i < Server.getStorage().getFiles().size(); i++) { |
31 |
if (Server.getStorage().getFiles().get(i).getFileId().equals(fileId))
|
32 |
return;
|
33 |
} |
34 |
|
35 |
if (version == 2.0) { |
36 |
if (Server.getStorage().getStoredTimes().get(key) >= replicationDegree)
|
37 |
return;
|
38 |
|
39 |
if (Server.getStorage().getSpaceAvailable() >= content.length) {
|
40 |
Chunk chunk = null;
|
41 |
try {
|
42 |
chunk = new Chunk(chunkNr, fileId, replicationDegree, content.length);
|
43 |
} catch (IOException e1) { |
44 |
e1.printStackTrace(); |
45 |
} |
46 |
|
47 |
if (!Server.getStorage().addSavedChunk(chunk)) {
|
48 |
return;
|
49 |
} |
50 |
|
51 |
Server.getStorage().decSpaceAvailable(content.length); |
52 |
|
53 |
//creates the file and saves the chunk
|
54 |
try {
|
55 |
String filename = Server.getServerId() + "/" + fileId + "." + chunkNr; |
56 |
|
57 |
File file = new File(filename); |
58 |
if (!file.exists()) {
|
59 |
file.getParentFile().mkdirs(); |
60 |
file.createNewFile(); |
61 |
} |
62 |
|
63 |
try (FileOutputStream fos = new FileOutputStream(filename)) { |
64 |
fos.write(content); |
65 |
} |
66 |
|
67 |
} catch (IOException e) { |
68 |
e.printStackTrace(); |
69 |
} |
70 |
|
71 |
Server.getStorage().incStoredOccurrences(fileId, chunkNr); |
72 |
String header = "STORED " + "1.0" + " " + Server.getServerId() + " " + fileId + " " + chunkNr |
73 |
+ "\r\n\r\n";
|
74 |
System.out.println(
|
75 |
"Sent " + "STORED " + "1.0" + " " + Server.getServerId() + " " + fileId + " " + chunkNr); |
76 |
try {
|
77 |
Server.getmc().sendMessage(header.getBytes()); |
78 |
} catch (IOException e) { |
79 |
e.printStackTrace(); |
80 |
} |
81 |
} else {
|
82 |
System.out.println("Not enough space in this peer " + fileId + "_" + chunkNr); |
83 |
} |
84 |
|
85 |
} |
86 |
} |
87 |
} |