Project

General

Profile

Statistics
| Revision:

root / src / utils / FileController.java

History | View | Annotate | Download (6.95 KB)

1 1 up20140508
package utils;
2
3
import java.io.*;
4
import java.nio.charset.StandardCharsets;
5
import java.nio.file.FileSystems;
6
import java.nio.file.Files;
7
import java.nio.file.Path;
8
import java.nio.file.attribute.BasicFileAttributes;
9
import java.security.MessageDigest;
10
import java.security.NoSuchAlgorithmException;
11
import java.util.Iterator;
12
import java.util.Map;
13
import java.util.Set;
14
15
public class FileController implements Serializable {
16
    private String messageType;
17
    private String version;
18
    private int senderId; //id of the server that has sent the message
19
    private String fileId; //metadata of file
20
    private byte[] body;
21
22
    private String hashedFileId; //hashed string with SHA256
23
24
    private String chunkNo; //together with the FileId specifies a chunk in the file.
25
    private String replicationDeg; //up to 9
26
    private int fileSize;
27
28
    private File file;
29
    private FileInputStream fileStream;
30
31
    public FileController(String m, String v, int s, String f, String r) throws IOException {
32
        this.messageType = m;
33
        this.version = v;
34
        this.senderId = s;
35
        this.fileId = f;
36
        this.replicationDeg = r;
37
    }
38
39
    public FileController(String[] receivedArray, byte[] bodyByteArray){
40
        String headerMsg = receivedArray[0];
41
        String[] headerTokens = headerMsg.split("\\s+");
42
43
        this.messageType = headerTokens[0];
44
        this.version = headerTokens[1];
45
        this.chunkNo = headerTokens[4];
46
47
        this.hashedFileId = headerTokens[3];
48
        if(headerTokens.length >= 6)
49
            this.replicationDeg = headerTokens[5];
50
        else
51
            this.replicationDeg = "";
52
        this.senderId = Integer.parseInt(headerTokens[2]);
53
54
        this.body = bodyByteArray;
55
        this.fileId = null;
56
    }
57
58
    public String getFileMetadata(String f) throws IOException {
59
        Path file = FileSystems.getDefault().getPath("test", f);
60
        BasicFileAttributes attr = Files.readAttributes(file, BasicFileAttributes.class);
61
62
        return f + "-" + attr.lastModifiedTime() + "-" + attr.creationTime();
63
    }
64
65
    public String getFileName(){
66
        return this.fileId;
67
    }
68
69
    public void saveToDisk(int senderId, String chunckNo) throws IOException {
70
        System.out.println("saving to disk...  ||  Sender ID: " + senderId + "  ||  ChunkNo: " + chunkNo);
71
        File storage = new File("storage");
72
73
        // if the directory does not exist, create it
74
        if (!storage.exists()) {
75
            System.out.println("creating directory to store chunks: " + storage.getName());
76
            boolean result = false;
77
78
            try{
79
                storage.mkdir();
80
                result = true;
81
            }
82
            catch(SecurityException se){
83
                //handle it
84
            }
85
            if(result) {
86
                System.out.println("Storage Directory created");
87
            }
88
        }
89
90
        //directory for backup
91
        File backup = new File ("storage/Backup");
92
93
        // if the directory does not exist, create it
94
        if (!backup.exists()) {
95
            System.out.println("creating directory to store chunks: " + backup.getName());
96
            boolean result = false;
97
98
            try{
99
                backup.mkdir();
100
                result = true;
101
            }
102
            catch(SecurityException se){
103
                //handle it
104
            }
105
            if(result) {
106
                System.out.println("Backup Directory created");
107
            }
108
        }
109
        //directory for peerid
110
        File peerId = new File ("storage/Backup/Peer" + senderId);
111
112
        // if the directory does not exist, create it
113
        if (!peerId.exists()) {
114
            System.out.println("creating directory to store chunks: " + peerId.getName());
115
            boolean result = false;
116
117
            try{
118
                peerId.mkdir();
119
                result = true;
120
            }
121
            catch(SecurityException se){
122
                //handle it
123
            }
124
            if(result) {
125
                System.out.println("PeerId Directory created");
126
            }
127
        }
128
        //directory for hashed file id
129
        //System.out.println(this.hashedFileId);
130
        File hashedDir = new File("storage/Backup/Peer" + senderId + "/"+ this.hashedFileId);
131
        // if the directory does not exist, create it
132
        if (!hashedDir.exists()) {
133
            System.out.println("creating directory to store chunks: " + hashedDir.getName());
134
            boolean result = false;
135
136
            try{
137
                hashedDir.mkdir();
138
                result = true;
139
            }
140
            catch(SecurityException se){
141
                //handle it
142
            }
143
            if(result) {
144
                System.out.println("file Directory created");
145
            }
146
        }
147
148
        //now store the chunck
149
        File chunk = new File("storage/Backup/Peer" + senderId + "/"+ this.hashedFileId + "/" + chunckNo);
150
151
        FileOutputStream fos = new FileOutputStream(chunk);
152
        fos.write(this.body);
153
        fos.close();
154
155
156
157
158
    }
159
160
    public void hashFileId() throws NoSuchAlgorithmException, IOException { //reference https://www.baeldung.com/sha-256-hashing-java
161
        //add a little more info to hash this fileId;
162
        String fileIdWithMetadata = getFileMetadata(this.fileId);
163
164
165
        if(!Utils.hashDatabase.containsKey(this.fileId)){
166
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
167
            byte[] encodedhash = digest.digest(
168
                    fileIdWithMetadata.getBytes(StandardCharsets.UTF_8));
169
            String hexHash = Utils.encodeHexString(encodedhash);
170
            this.hashedFileId = hexHash;
171
172
            Utils.hashDatabase.put(this.fileId,hexHash);
173
        }
174
        else this.hashedFileId = Utils.hashDatabase.get(this.fileId);
175
    }
176
177
    public void openStream() throws FileNotFoundException {
178
        this.file = new File("test/" + getFileName());
179
        this.fileStream = new FileInputStream(this.file);
180
        this.fileSize = ((int) this.file.length());
181
    }
182
183
    public byte[] header(int chunkNo){
184
        String header = "";
185
        switch(messageType){
186
            case "BACKUP":
187
                header = messageType + " " + version + " " + senderId + " " + hashedFileId + " " + chunkNo + " " + replicationDeg + "\r\n\r\n";
188
                break;
189
            case "RESTORE":
190
                header = messageType + " " + version + " " + senderId + " " + hashedFileId + " " + chunkNo + "\r\n\r\n";
191
                break;
192
193
        }
194
        byte[] buffer = header.getBytes();
195
        return buffer;
196
    }
197
198
    public int getSenderId() {
199
        return senderId;
200
    }
201
202
    public String getHashedFileId() {
203
        return hashedFileId;
204
    }
205
206
    public int getSize() {
207
        return fileSize;
208
    }
209
210
    public FileInputStream getFileStream(){
211
        return fileStream;
212
    }
213
214
    public String getReplicationDeg(){
215
        return replicationDeg;
216
    }
217
218
    public String getChunkNo() {
219
        return chunkNo;
220
    }
221
222
    public String getVersion() {
223
        return this.version;
224
    }
225
226
    public byte[] getBody(){
227
        return body;
228
    }
229
}