-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathutils.java
More file actions
300 lines (242 loc) · 11 KB
/
Copy pathutils.java
File metadata and controls
300 lines (242 loc) · 11 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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Comparator;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
public class utils {
public static void main(String[] args) {
String action = args.length > 0 ? args[0] : null;
String zipFile = args.length > 1 ? args[1] : "";
if (action == null || action.isBlank() || !(action.contains("-c") || action.contains("-u"))) {
System.err.print("Please provide a valid command: first argument should be -c for compressing, -u for uncompress");
}
try {
switch (action) {
case "-u": doUnzip(zipFile); break;
case "-c": doArchive(); break;
default:
System.err.printf("Can't manage action : '%s'", action);
}
} catch (InvalidPathException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
}
System.exit(0);
}
private static void doUnzip(final String zipFile) throws IOException {
if (zipFile == null || zipFile.isBlank()) {
System.err.print("Second argument: please provide a Zip File path");
}
Path source = Paths.get(zipFile);
Path target = Paths.get("source");
if (!source.toFile().exists()) {
System.err.printf("Zip File '%s' isn't a valid path", zipFile);
}
if (!source.toFile().canRead()) {
System.err.printf("Zip File '%s' isn't readable", zipFile);
}
// delete targetDir
if (target.toFile().exists()) {
Files.walk(target)
.sorted(Comparator.reverseOrder())
.map(Path::toFile)
.forEach(File::delete);
target.toFile().delete();
}
// create target at init
if (!target.toFile().exists()) {
target.toFile().mkdirs();
}
System.out.printf("Unzip main archive '%s'%n", source.toAbsolutePath());
utils.unzipFolder(source, target);
System.out.printf("Unzip all files into '%s'%n", target.toAbsolutePath().toString());
Files.list(target)
.filter(c -> c.toString().endsWith(".zip"))
.forEach(c -> {
try {
String filename = c.getFileName().toString();
filename = filename.substring(0, filename.lastIndexOf("."));
Path subtarget = Paths.get("source/" + filename);
System.out.printf("Unzip '%s' into '%s'%n", c.toAbsolutePath().toString(), subtarget.toAbsolutePath().toString());
unzipFolder(c.toAbsolutePath(), subtarget);
c.toFile().delete();
} catch (IOException e) {
e.printStackTrace();
}
});
System.out.println("Unzip Done");
}
private static void doArchive() throws IOException {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("YYYYMMdd-HHmmdd").withZone(ZoneId.systemDefault());
String targetZipFilename = "kapc_" + formatter.format(Instant.now()) + ".zip";
Path source = Paths.get("source");
Path targetDir = Paths.get("target");
// delete targetDir
if (targetDir.toFile().exists()) {
Files.walk(targetDir)
.sorted(Comparator.reverseOrder())
.map(Path::toFile)
.forEach(File::delete);
targetDir.toFile().delete();
}
// recreate targetDir
if (!targetDir.toFile().exists()) {
targetDir.toFile().mkdirs();
}
// zip all subdirectories
Files.list(source)
.filter(c -> c.toString().endsWith(".zip"))
.forEach(c -> {
try {
zipFolder(c.toAbsolutePath(), targetDir);
} catch (IOException e) {
e.printStackTrace();
}
});
// make one zip of all subdirectories
compress(targetDir, targetZipFilename);
}
private static void unzipFolder(Path source, Path target) throws IOException {
try (ZipInputStream zis = new ZipInputStream(new FileInputStream(source.toFile()))) {
// list files in zip
ZipEntry zipEntry = zis.getNextEntry();
while (zipEntry != null) {
boolean isDirectory = false;
// example 1.1
// some zip stored files and folders separately
// e.g data/
// data/folder/
// data/folder/file.txt
if (zipEntry.getName().endsWith(File.separator)) {
isDirectory = true;
}
Path newPath = zipSlipProtect(zipEntry, target);
if (isDirectory) {
Files.createDirectories(newPath);
} else {
// example 1.2
// some zip stored file path only, need create parent directories
// e.g data/folder/file.txt
if (newPath.getParent() != null) {
if (Files.notExists(newPath.getParent())) {
Files.createDirectories(newPath.getParent());
}
}
// copy files, nio
Files.copy(zis, newPath, StandardCopyOption.REPLACE_EXISTING);
// copy files, classic
/*try (FileOutputStream fos = new FileOutputStream(newPath.toFile())) {
byte[] buffer = new byte[1024];
int len;
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
}*/
}
zipEntry = zis.getNextEntry();
}
zis.closeEntry();
}
}
// protect zip slip attack
private static Path zipSlipProtect(ZipEntry zipEntry, Path targetDir)
throws IOException {
// test zip slip vulnerability
// Path targetDirResolved = targetDir.resolve("../../" + zipEntry.getName());
Path targetDirResolved = targetDir.resolve(zipEntry.getName());
// make sure normalized file still has targetDir as its prefix
// else throws exception
Path normalizePath = targetDirResolved.normalize();
if (!normalizePath.startsWith(targetDir)) {
throw new IOException("Bad zip entry: " + zipEntry.getName());
}
return normalizePath;
}
// zip a directory, including sub files and sub directories
private static void zipFolder(Path source, Path target) throws IOException {
// get folder name as zip file name
String zipFileName = target.toAbsolutePath() + File.separator + source.getFileName().toString() + ".zip";
try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFileName))) {
Files.walkFileTree(source, new SimpleFileVisitor<>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) {
// only copy files, no symbolic links
if (attributes.isSymbolicLink()) {
return FileVisitResult.CONTINUE;
}
try (FileInputStream fis = new FileInputStream(file.toFile())) {
Path targetFile = source.relativize(file);
zos.putNextEntry(new ZipEntry(targetFile.toString()));
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
// if large file, throws out of memory
// byte[] bytes = Files.readAllBytes(file);
// zos.write(bytes, 0, bytes.length);
zos.closeEntry();
System.out.printf("Zip file : %s into %s%n", file, zipFileName);
} catch (IOException e) {
e.printStackTrace();
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) {
System.err.printf("Unable to zip : %s%n%s%n", file, exc);
return FileVisitResult.CONTINUE;
}
});
}
}
// zip all files into one
private static void compress(Path sourceDir, String zipFileName) {
String zipFilePath = sourceDir.toFile().getAbsoluteFile() + File.separator + zipFileName;
System.out.printf("Creating Archive '%s'%n", zipFilePath);
try {
final ZipOutputStream outputStream = new ZipOutputStream(new FileOutputStream(zipFilePath));
Files.walkFileTree(sourceDir, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) {
try {
Path targetFile = sourceDir.relativize(file);
if (targetFile.toString().endsWith(".zip.zip")) {
outputStream.putNextEntry(new ZipEntry(targetFile.toString()));
byte[] bytes = Files.readAllBytes(file);
outputStream.write(bytes, 0, bytes.length);
outputStream.closeEntry();
targetFile.toFile().delete();
System.out.printf("Added '%s' into '%s'%n", targetFile.toAbsolutePath(), zipFilePath);
} else if (!targetFile.toString().equals(zipFileName)) {
System.out.printf("Maybe a warning: the directory '%s' contains other files than compressed directories %n", targetFile.toAbsolutePath());
}
} catch (IOException e) {
e.printStackTrace();
}
return FileVisitResult.CONTINUE;
}
});
outputStream.close();
System.out.printf("Archive '%s' Done !%n", zipFilePath);
} catch (IOException e) {
e.printStackTrace();
}
}
}