root / BackupFile.java
History | View | Annotate | Download (2.42 KB)
1 |
import java.io.File; |
---|---|
2 |
import java.nio.charset.StandardCharsets; |
3 |
import java.security.MessageDigest; |
4 |
import java.security.NoSuchAlgorithmException; |
5 |
import java.util.concurrent.ConcurrentHashMap; |
6 |
|
7 |
/**
|
8 |
* BackupFile
|
9 |
*/
|
10 |
public class BackupFile { |
11 |
private File file; |
12 |
private String fileId; |
13 |
private int desiredReplicationDegree; |
14 |
private ConcurrentHashMap<Integer, Chunk> chunksMap = new ConcurrentHashMap<>(); |
15 |
|
16 |
public BackupFile(String fileId) { |
17 |
this.fileId = fileId;
|
18 |
} |
19 |
|
20 |
public void addChunk(int chunkNo, Chunk chunk) { |
21 |
this.chunksMap.put(chunkNo, chunk);
|
22 |
} |
23 |
|
24 |
public BackupFile(String pathname, int desiredReplicationDegree) |
25 |
throws NoSuchAlgorithmException { |
26 |
this.file = new File(pathname); |
27 |
this.desiredReplicationDegree = desiredReplicationDegree;
|
28 |
this.fileId = generateFileId(this.getPathname(), this.file.lastModified()); |
29 |
|
30 |
} |
31 |
|
32 |
//Generates a unique FileId with the combined pathname & last modified info
|
33 |
public static String generateFileId(String pathname, long lastModified) throws NoSuchAlgorithmException { |
34 |
String str = pathname + lastModified;
|
35 |
|
36 |
MessageDigest digest = MessageDigest.getInstance("SHA-256"); |
37 |
byte[] hash = digest.digest(str.getBytes(StandardCharsets.UTF_8)); |
38 |
|
39 |
StringBuffer hexString = new StringBuffer(); |
40 |
for (int i = 0; i < hash.length; i++) { |
41 |
String hex = Integer.toHexString(0xff & hash[i]); |
42 |
if (hex.length() == 1) |
43 |
hexString.append('0');
|
44 |
hexString.append(hex); |
45 |
} |
46 |
return hexString.toString();
|
47 |
} |
48 |
|
49 |
/**
|
50 |
* @return the desiredReplicationDegree
|
51 |
*/
|
52 |
public int getDesiredReplicationDegree() { |
53 |
return desiredReplicationDegree;
|
54 |
} |
55 |
|
56 |
/**
|
57 |
* @return the pathname
|
58 |
*/
|
59 |
public String getPathname() { |
60 |
return this.file.getPath(); |
61 |
} |
62 |
|
63 |
/**
|
64 |
* @return the fileId
|
65 |
*/
|
66 |
public String getFileId() { |
67 |
return fileId;
|
68 |
} |
69 |
|
70 |
public File getFile() { |
71 |
return this.file; |
72 |
} |
73 |
|
74 |
public ConcurrentHashMap<Integer, Chunk> getChunksMap() { |
75 |
return this.chunksMap; |
76 |
} |
77 |
|
78 |
public void removeChunk(int chunkNo, Peer peer){ |
79 |
this.chunksMap.remove(chunkNo);
|
80 |
File chunk = new File("Peer-" + peer.getSenderId() + File.separator + "Chunks" + File.separator + this.fileId + File.separator + chunkNo); |
81 |
peer.removeStorage(chunk.length()); |
82 |
chunk.delete(); |
83 |
} |
84 |
|
85 |
|
86 |
} |