Project

General

Profile

Statistics
| Revision:

root / src / files / FileHandler.java @ 1

History | View | Annotate | Download (5.09 KB)

1 1 up20150524
package files;
2
3
4
import chord.ConnectionInfo;
5
import messages.BackupMessage;
6
7
import messages.MessageForwarder;
8
9
import chord.ChordManager;
10
11
import peer.Peer;
12
13
import java.io.File;
14
import java.io.IOException;
15
import java.math.BigInteger;
16
import java.net.InetAddress;
17
import java.nio.ByteBuffer;
18
import java.nio.channels.*;
19
import java.nio.charset.StandardCharsets;
20
import java.nio.file.*;
21
import java.nio.file.attribute.BasicFileAttributes;
22
import java.security.MessageDigest;
23
import java.security.NoSuchAlgorithmException;
24
import java.util.Comparator;
25
import java.util.List;
26
import java.util.concurrent.ExecutionException;
27
import java.util.concurrent.Future;
28
import java.util.concurrent.atomic.AtomicLong;
29
import java.util.stream.Collectors;
30
31
32
public class FileHandler {
33
34
    public static byte[] readFromFile(String filename) throws IOException, ExecutionException, InterruptedException {
35
36
        Path path = Paths.get(filename);
37
38
        AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ);
39
40
        int fileSize = (int) new File(filename).length();
41
42
        ByteBuffer buffer = ByteBuffer.allocate(fileSize);
43
44
        Future<Integer> operation = fileChannel.read(buffer, 0);
45
46
        operation.get();
47
48
        buffer.rewind();
49
50
        byte[] byteArray = new byte[buffer.remaining()];
51
52
        buffer.get(byteArray);
53
54
        return byteArray;
55
    }
56
57
    public static boolean checkFileExists(String filename) {
58
        Path path = Paths.get(filename);
59
60
        return Files.exists(path);
61
    }
62
63
    public static void writeFile(String filename, byte[] fileContent) throws IOException, ExecutionException, InterruptedException {
64
65
        Path path = Paths.get(filename);
66
67
        if (!checkFileExists(filename))
68
            Files.createFile(path);
69
70
        AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE);
71
72
        int fileSize = fileContent.length;
73
74
        ByteBuffer buffer = ByteBuffer.allocate(fileSize);
75
76
        buffer.put(fileContent);
77
        buffer.flip();
78
79
        Future<Integer> operation = fileChannel.write(buffer, 0);
80
        buffer.clear();
81
82
        operation.get();
83
84
    }
85
86
    public static String getFileSize(String filename) throws IOException {
87
88
        Path path = Paths.get("./testFiles/" + filename);
89
90
        return String.valueOf(Files.size(path));
91
    }
92
93
    public static void createDir(String type) {
94
95
        String typeDirName = "./peerDisk/peer" + Peer.getPeerAccessPoint() + "-" + ChordManager.peerHash + "/" + type;
96
97
        Path dirPath = Paths.get(typeDirName);
98
99
        boolean backupExists = Files.exists(dirPath);
100
101
        if (backupExists) {
102
            System.out.println("Directory already exists");
103
        } else {
104
            try {
105
                Files.createDirectories(dirPath);
106
            } catch (IOException ioExceptionObj) {
107
                System.out.println("Problem creating directory");
108
            }
109
        }
110
    }
111
112
    public static void clearStorageSpace() throws IOException {
113
        Path rootPath = Paths.get("./peerDisk/peer" + Peer.getPeerAccessPoint() + "-" + ChordManager.peerHash);
114
115
        final List<Path> pathsToDelete = Files.walk(rootPath).sorted(Comparator.reverseOrder()).collect(Collectors.toList());
116
        for(Path path : pathsToDelete) {
117
            if(Peer.storage.getSpaceReserved() < Peer.storage.getSpaceOcupied()) {
118
                    if(Files.isRegularFile(path)){
119
                    System.out.println("\n \n \n \n" + path);
120
                    if(Files.exists(path)){
121
                        if(!Files.isDirectory(path))
122
123
                            handleDeleteFile(path);
124
                    Files.deleteIfExists(path);
125
                    }
126
                    }
127
            }
128
        }
129
    }
130
131
132
    private static void handleDeleteFile(Path path) throws IOException {
133
        byte[] content = Files.readAllBytes(path);
134
        long filename;
135
        try {
136
           filename = Long.parseLong(path.getFileName().toString());
137
           DeleteHandler handler = new DeleteHandler(new ConnectionInfo(ChordManager.peerHash, InetAddress.getLocalHost().getHostAddress(), Peer.port), new BigInteger(path.getFileName().toString()), 1, content);
138
            Peer.executor.submit(handler);
139
        } catch(Exception e) {
140
141
        }
142
143
    }
144
145
146
    public static long getSize(Path startPath) throws IOException {
147
        final AtomicLong size = new AtomicLong(0);
148
149
        Files.walkFileTree(startPath, new SimpleFileVisitor<Path>() {
150
            @Override
151
            public FileVisitResult visitFile(Path file,
152
                                             BasicFileAttributes attrs) throws IOException {
153
                size.addAndGet(attrs.size());
154
                return FileVisitResult.CONTINUE;
155
            }
156
157
            @Override
158
            public FileVisitResult visitFileFailed(Path file, IOException exc)
159
                    throws IOException {
160
                return FileVisitResult.CONTINUE;
161
            }
162
        });
163
164
        return size.get();
165
    }
166
}