Project

General

Profile

Statistics
| Revision:

root / src / messages / BackupMessage.java

History | View | Annotate | Download (2.12 KB)

1
package messages;
2

    
3
import chord.ChordManager;
4
import chord.ConnectionInfo;
5
import files.FileHandler;
6
import peer.Peer;
7
import protocols.Backup;
8

    
9
import java.io.IOException;
10
import java.math.BigInteger;
11
import java.util.concurrent.ExecutionException;
12

    
13
public class BackupMessage extends Message {
14
    private int repDegree;
15
    private BigInteger hashFile;
16
    private ConnectionInfo ci;
17
    private byte[] body;
18
    private String ipAddress;
19
    private int port;
20

    
21
    public BackupMessage(ConnectionInfo ci, BigInteger hashFile, int repDegree, byte[] body,String ipAddress,int port) {
22
        this.ci = ci;
23
        this.hashFile = hashFile;
24
        this.repDegree = repDegree;
25
        this.body = body;
26
        this.ipAddress = ipAddress;
27
        this.port = port;
28
    }
29

    
30
    @Override
31
    public String getIpAddress() {
32
        return this.ipAddress;
33
    }
34

    
35
    @Override
36
    public int getPort() {
37
        return this.port;
38
    }
39
    @Override
40
    public String toString() {
41
        return "BACKUP " + this.hashFile + " " + this.repDegree;
42
    }
43

    
44
    public void handleMessage() {
45
        if (Peer.storage.getSpaceOcupied() + body.length > Peer.storage.getSpaceReserved()) {
46
            MessageForwarder.sendMessage(new BackupMessage(ci, hashFile, repDegree, body, ChordManager.getFingerTable().get(0).getIp(), ChordManager.getFingerTable().get(0).getPort()));
47
        } else {
48

    
49
            try {
50
                FileHandler.writeFile("./peerDisk/peer" + Peer.getPeerAccessPoint() + "-" + ChordManager.peerHash + "/backup/" + hashFile, body);
51
            } catch (IOException e) {
52
                e.printStackTrace();
53
            } catch (ExecutionException e) {
54
                e.printStackTrace();
55
            } catch (InterruptedException e) {
56
                e.printStackTrace();
57
            }
58

    
59
            if(repDegree - 1 > 0)
60
                MessageForwarder.sendMessage(new BackupMessage(ci, hashFile, repDegree - 1, body, ChordManager.getFingerTable().get(0).getIp(), ChordManager.getFingerTable().get(0).getPort()));
61
            MessageForwarder.sendMessage(new BackupCompleteMessage(this.hashFile, this.repDegree, ci.getIp(), ci.getPort()));
62

    
63
        }
64
    }
65
}