-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPathStorage.java
More file actions
98 lines (84 loc) · 2.88 KB
/
PathStorage.java
File metadata and controls
98 lines (84 loc) · 2.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package ru.javaops.webapp.storage;
import ru.javaops.webapp.exception.StorageException;
import ru.javaops.webapp.model.Resume;
import ru.javaops.webapp.storage.serialisation_strategy.SerialisationStrategy;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class PathStorage extends AbstractStorage<Path> {
private final Path directory;
private final SerialisationStrategy serialisationStrategy;
protected PathStorage(String dir, SerialisationStrategy serialisationStrategy) {
directory = Paths.get(dir);
Objects.requireNonNull(directory, "directory must not be null");
if (!Files.isDirectory(directory) || !Files.isWritable(directory)) {
throw new IllegalArgumentException(dir + " is not directory or is not writable");
}
this.serialisationStrategy = serialisationStrategy;
}
@Override
public void clear() {
getAllFiles().forEach(this::doDelete);
}
@Override
public int size() {
return (int) getAllFiles().count();
}
@Override
protected Path getSearchKey(String uuid) {
return Paths.get(String.valueOf(directory), uuid);
}
@Override
protected void doUpdate(Path path, Resume r) {
try {
serialisationStrategy.serialize(r, new BufferedOutputStream(Files.newOutputStream(path)));
} catch (IOException e) {
throw new StorageException("Path write error", r.getUuid(), e);
}
}
@Override
protected boolean isExist(Path path) {
return Files.exists(path);
}
@Override
protected void doSave(Path path, Resume r) {
try {
Files.createFile(path);
} catch (IOException e) {
throw new StorageException("Couldn't create Path " + path.toAbsolutePath(), path.getFileName().toString(), e);
}
doUpdate(path, r);
}
@Override
protected Resume doGet(Path path) {
try {
return serialisationStrategy.deserialize(new BufferedInputStream(Files.newInputStream(path)));
} catch (IOException e) {
throw new StorageException("Path read error", path.getFileName().toString(), e);
}
}
@Override
protected void doDelete(Path path) {
try {
Files.delete(path);
} catch (IOException e) {
throw new StorageException("Path delete error", path.getFileName().toString());
}
}
@Override
protected List<Resume> doCopyAll() {
return getAllFiles().map(this::doGet).collect(Collectors.toList());
}
private Stream<Path> getAllFiles() {
try {
return Files.list(directory);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}