root / threads / ManageRestored.java @ 15
History | View | Annotate | Download (2.1 KB)
1 | 15 | up20160473 | package threads; |
---|---|---|---|
2 | import java.io.*; |
||
3 | import java.util.*; |
||
4 | import server.Server; |
||
5 | |||
6 | public class ManageRestored implements Runnable { |
||
7 | |||
8 | private String fileName; |
||
9 | |||
10 | public ManageRestored(String fileName) { |
||
11 | this.fileName = fileName;
|
||
12 | } |
||
13 | |||
14 | @Override
|
||
15 | public void run() { |
||
16 | |||
17 | if (!Server.getStorage().getRemainingChunks().containsValue("false")) { |
||
18 | if (restoreFile())
|
||
19 | System.out.println("> File restored!\n"); |
||
20 | else System.out.println("ERROR: File not restored.\n"); |
||
21 | } else System.out.println("ERROR: File not restored, chunks missing.\n"); |
||
22 | |||
23 | Server.getStorage().getRemainingChunks().clear(); |
||
24 | } |
||
25 | |||
26 | private boolean restoreFile() { |
||
27 | String filePath = "database/" + Server.getServerId() + "/" + this.fileName; |
||
28 | File file = new File(filePath); |
||
29 | byte[] body; |
||
30 | |||
31 | try {
|
||
32 | FileOutputStream fos = new FileOutputStream(file, true); |
||
33 | |||
34 | if (!file.exists()) {
|
||
35 | file.getParentFile().mkdirs(); |
||
36 | file.createNewFile(); |
||
37 | } |
||
38 | |||
39 | List<String> sortedChunkKeys = new ArrayList<>(Server.getStorage().getRemainingChunks().keySet()); |
||
40 | |||
41 | sortedChunkKeys.sort((o1, o2) -> { |
||
42 | int chunkNr1 = Integer.valueOf(o1.split(".")[1]); |
||
43 | int chunkNr2 = Integer.valueOf(o2.split(".")[1]); |
||
44 | return Integer.compare(chunkNr1, chunkNr2); |
||
45 | }); |
||
46 | |||
47 | for (String key : sortedChunkKeys) { |
||
48 | String chunkPath = Server.getServerId() + "/" + key; |
||
49 | |||
50 | File chunkFile = new File(chunkPath); |
||
51 | |||
52 | if (!chunkFile.exists()) {
|
||
53 | return false; |
||
54 | } |
||
55 | |||
56 | body = new byte[(int) chunkFile.length()]; |
||
57 | FileInputStream in = new FileInputStream(chunkFile); |
||
58 | |||
59 | in.read(body); |
||
60 | fos.write(body); |
||
61 | |||
62 | chunkFile.delete(); |
||
63 | in.close(); |
||
64 | } |
||
65 | |||
66 | fos.close(); |
||
67 | return true; |
||
68 | } catch (IOException e) { |
||
69 | e.printStackTrace(); |
||
70 | } |
||
71 | return false; |
||
72 | } |
||
73 | } |