Project

General

Profile

Statistics
| Revision:

root / src / protocols / BackupProtocol.java

History | View | Annotate | Download (1.99 KB)

1
package protocols;
2

    
3
import channels.MdbChannel;
4
import peer.Peer;
5
import utils.Chunk;
6
import utils.FileController;
7
import utils.Utils;
8

    
9
import java.io.IOException;
10
import java.security.NoSuchAlgorithmException;
11
import java.util.ArrayList;
12

    
13
public class BackupProtocol {
14

    
15
    FileController file;
16

    
17
    private int[] peers;
18
    private String fileId;
19
    private int chunkNo;
20

    
21
    public BackupProtocol(String[] requestArgs) throws IOException, NoSuchAlgorithmException {
22
        file = new FileController(requestArgs[0], Utils.version, Peer.getSenderId(),requestArgs[1],requestArgs[2]);
23
        backUpFile();
24
    }
25

    
26
    private void backUpFile() throws IOException, NoSuchAlgorithmException {
27
        file.openStream();
28
        file.hashFileId();
29
        int size = file.getSize();
30
        this.fileId=file.getHashedFileId();
31
        sendToPeers(size);
32
    }
33

    
34
    private void sendToPeers(int size) throws IOException, NoSuchAlgorithmException {
35
        
36
        for(int i=0; (i==0 || size > 0);i++){
37
            this.peers = new int[0];
38
            boolean done = false;
39
            int attempts = 0;
40
            int delay = 1000;
41

    
42
            size -= 64000;
43
            byte[] header = file.header(i);
44
            Chunk chunk = new Chunk(header,file);
45

    
46
            while(!done && attempts<5){
47
                System.out.println("BACKUP: Sending chunk of: " + file.getFileName() + "  ||  Size Remaining:" + size + " ||  Header: " + new String(header,0,header.length));
48

    
49
                this.chunkNo = i;
50
                MdbChannel.sendMessage(chunk.getBuffer());
51
                try{
52
                    Thread.sleep(delay);
53
                } catch(InterruptedException e){
54
                    e.getCause();
55
                }
56
                if(Integer.parseInt(file.getReplicationDeg()) <= this.peers.length){
57
                    done = true;
58
                }
59
                else{
60
                    attempts++;
61
                    delay=2*delay;
62
                }
63

    
64
            }
65
        }
66
        System.out.println(("DONE"));
67
    }
68
}