Debian Codegraph @

src/main/org/h2/store/fs/disk/FilePathDisk.java

raw
1 /*
2 * Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0,
3 * and the EPL 1.0 (https://h2database.com/html/license.html).
4 * Initial Developer: H2 Group
5 */
6 package org.h2.store.fs.disk;
7
8 import java.io.FileNotFoundException;
9 import java.io.IOException;
10 import java.io.InputStream;
11 import java.io.OutputStream;
12 import java.net.URI;
13 import java.net.URL;
14 import java.nio.channels.FileChannel;
15 import java.nio.file.AccessDeniedException;
16 import java.nio.file.AtomicMoveNotSupportedException;
17 import java.nio.file.CopyOption;
18 import java.nio.file.DirectoryNotEmptyException;
19 import java.nio.file.FileAlreadyExistsException;
20 import java.nio.file.FileStore;
21 import java.nio.file.FileSystem;
22 import java.nio.file.FileSystemNotFoundException;
23 import java.nio.file.FileSystems;
24 import java.nio.file.Files;
25 import java.nio.file.NoSuchFileException;
26 import java.nio.file.OpenOption;
27 import java.nio.file.Path;
28 import java.nio.file.Paths;
29 import java.nio.file.StandardCopyOption;
30 import java.nio.file.StandardOpenOption;
31 import java.nio.file.attribute.DosFileAttributeView;
32 import java.nio.file.attribute.PosixFileAttributeView;
33 import java.nio.file.attribute.PosixFilePermission;
34 import java.util.ArrayList;
35 import java.util.Collections;
36 import java.util.HashMap;
37 import java.util.HashSet;
38 import java.util.List;
39 import java.util.Map;
40 import java.util.stream.Stream;
41
42 import org.h2.api.ErrorCode;
43 import org.h2.engine.SysProperties;
44 import org.h2.message.DbException;
45 import org.h2.store.fs.FilePath;
46 import org.h2.store.fs.FileUtils;
47 import org.h2.util.IOUtils;
48
49 /**
50 * This file system stores files on disk.
51 * This is the most common file system.
52 */
53 public class FilePathDisk extends FilePath {
54
55 private static final String CLASSPATH_PREFIX = "classpath:";
56
57 @Override
58 public FilePathDisk getPath(String path) {
59 FilePathDisk p = new FilePathDisk();
60 p.name = translateFileName(path);
61 return p;
62 }
63
64
65 @Override
66 public long size() {
67 if (name.startsWith(CLASSPATH_PREFIX)) {
68 String path = this.name.substring("classpath:".length());
69 if (!path.startsWith("/")) {
70 path = "/" + path;
71 }
72 URL url = this.getClass().getResource(path);
73 if (url == null) {
74 return 0L;
75 }
76 try {
77 URI uri = url.toURI();
78 if ("file".equals(url.getProtocol())) {
79 return Files.size(Paths.get(uri));
80 }
81 try {
82 // If filesystem is opened, let it be closed by the code that opened it.
83 // This way subsequent access to the FS does not fail
84 FileSystems.getFileSystem(uri);
85 return Files.size(Paths.get(uri));
86 } catch (FileSystemNotFoundException e) {
87 Map<String, String> env = new HashMap<>();
88 env.put("create", "true");
89 // If filesystem was not opened, open it and close it after access to avoid resource leak.
90 try (FileSystem fs = FileSystems.newFileSystem(uri, env)) {
91 return Files.size(Paths.get(uri));
92 }
93 }
94 } catch (Exception ex) {
95 return 0L;
96 }
97 }
98 try {
99 return Files.size(Paths.get(name));
100 } catch (IOException e) {
101 return 0L;
102 }
103 }
104
105 /**
106 * Translate the file name to the native format. This will replace '\' with
107 * '/' and expand the home directory ('~').
108 *
109 * @param fileName the file name
110 * @return the native file name
111 */
112 protected static String translateFileName(String fileName) {
113 fileName = fileName.replace('\\', '/');
114 if (fileName.startsWith("file:")) {
115 fileName = fileName.substring(5);
116 } else if (fileName.startsWith("nio:")) {
117 fileName = fileName.substring(4);
118 }
119 return expandUserHomeDirectory(fileName);
120 }
121
122 /**
123 * Expand '~' to the user home directory. It is only be expanded if the '~'
124 * stands alone, or is followed by '/' or '\'.
125 *
126 * @param fileName the file name
127 * @return the native file name
128 */
129 public static String expandUserHomeDirectory(String fileName) {
130 if (fileName.startsWith("~") && (fileName.length() == 1 ||
131 fileName.startsWith("~/"))) {
132 String userDir = SysProperties.USER_HOME;
133 fileName = userDir + fileName.substring(1);
134 }
135 return fileName;
136 }
137
138 @Override
139 public void moveTo(FilePath newName, boolean atomicReplace) {
140 Path oldFile = Paths.get(name);
141 Path newFile = Paths.get(newName.name);
142 if (!Files.exists(oldFile)) {
143 throw DbException.get(ErrorCode.FILE_RENAME_FAILED_2, name + " (not found)", newName.name);
144 }
145 if (atomicReplace) {
146 try {
147 Files.move(oldFile, newFile, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
148 return;
149 } catch (AtomicMoveNotSupportedException ex) {
150 // Ignore
151 } catch (IOException ex) {
152 throw DbException.get(ErrorCode.FILE_RENAME_FAILED_2, ex, name, newName.name);
153 }
154 }
155 CopyOption[] copyOptions = atomicReplace ? new CopyOption[] { StandardCopyOption.REPLACE_EXISTING }
156 : new CopyOption[0];
157 IOException cause;
158 try {
159 Files.move(oldFile, newFile, copyOptions);
160 } catch (FileAlreadyExistsException ex) {
161 throw DbException.get(ErrorCode.FILE_RENAME_FAILED_2, name, newName + " (exists)");
162 } catch (IOException ex) {
163 cause = ex;
164 for (int i = 0; i < SysProperties.MAX_FILE_RETRY; i++) {
165 IOUtils.trace("rename", name + " >" + newName, null);
166 try {
167 Files.move(oldFile, newFile, copyOptions);
168 return;
169 } catch (FileAlreadyExistsException ex2) {
170 throw DbException.get(ErrorCode.FILE_RENAME_FAILED_2, name, newName + " (exists)");
171 } catch (IOException ex2) {
172 cause = ex;
173 }
174 wait(i);
175 }
176 throw DbException.get(ErrorCode.FILE_RENAME_FAILED_2, cause, name, newName.name);
177 }
178 }
179
180 private static void wait(int i) {
181 if (i == 8) {
182 System.gc();
183 }
184 try {
185 // sleep at most 256 ms
186 long sleep = Math.min(256, i * i);
187 Thread.sleep(sleep);
188 } catch (InterruptedException e) {
189 // ignore
190 }
191 }
192
193 @Override
194 public boolean createFile() {
195 Path file = Paths.get(name);
196 for (int i = 0; i < SysProperties.MAX_FILE_RETRY; i++) {
197 try {
198 Files.createFile(file);
199 return true;
200 } catch (FileAlreadyExistsException e) {
201 return false;
202 } catch (IOException e) {
203 // 'access denied' is really a concurrent access problem
204 wait(i);
205 }
206 }
207 return false;
208 }
209
210 @Override
211 public boolean exists() {
212 return Files.exists(Paths.get(name));
213 }
214
215 @Override
216 public void delete() {
217 Path file = Paths.get(name);
218 IOException cause = null;
219 for (int i = 0; i < SysProperties.MAX_FILE_RETRY; i++) {
220 IOUtils.trace("delete", name, null);
221 try {
222 Files.deleteIfExists(file);
223 return;
224 } catch (DirectoryNotEmptyException e) {
225 throw DbException.get(ErrorCode.FILE_DELETE_FAILED_1, e, name);
226 } catch (AccessDeniedException e) {
227 // On Windows file systems, delete a readonly file can cause AccessDeniedException,
228 // we should change readonly attribute to false and then delete file
229 try {
230 FileStore fileStore = Files.getFileStore(file);
231 if (!fileStore.supportsFileAttributeView(PosixFileAttributeView.class)
232 && fileStore.supportsFileAttributeView(DosFileAttributeView.class)) {
233 Files.setAttribute(file, "dos:readonly", false);
234 Files.delete(file);
235 }
236 } catch (IOException ioe) {
237 cause = ioe;
238 }
239 } catch (IOException e) {
240 cause = e;
241 }
242 wait(i);
243 }
244 throw DbException.get(ErrorCode.FILE_DELETE_FAILED_1, cause, name);
245 }
246
247 @Override
248 public List<FilePath> newDirectoryStream() {
249 try (Stream<Path> files = Files.list(toRealPath(Paths.get(name)))) {
250 return files.collect(ArrayList::new, (t, u) -> t.add(getPath(u.toString())), ArrayList::addAll);
251 } catch (NoSuchFileException e) {
252 return Collections.emptyList();
253 } catch (IOException e) {
254 throw DbException.convertIOException(e, name);
255 }
256 }
257
258 @Override
259 public boolean canWrite() {
260 try {
261 return Files.isWritable(Paths.get(name));
262 } catch (Exception e) {
263 // Catch security exceptions
264 return false;
265 }
266 }
267
268 @Override
269 public boolean setReadOnly() {
270 Path f = Paths.get(name);
271 try {
272 FileStore fileStore = Files.getFileStore(f);
273 /*
274 * Need to check PosixFileAttributeView first because
275 * DosFileAttributeView is also supported by recent Java versions on
276 * non-Windows file systems, but it doesn't affect real access
277 * permissions.
278 */
279 if (fileStore.supportsFileAttributeView(PosixFileAttributeView.class)) {
280 HashSet<PosixFilePermission> permissions = new HashSet<>();
281 for (PosixFilePermission p : Files.getPosixFilePermissions(f)) {
282 switch (p) {
283 case OWNER_WRITE:
284 case GROUP_WRITE:
285 case OTHERS_WRITE:
286 break;
287 default:
288 permissions.add(p);
289 }
290 }
291 Files.setPosixFilePermissions(f, permissions);
292 } else if (fileStore.supportsFileAttributeView(DosFileAttributeView.class)) {
293 Files.setAttribute(f, "dos:readonly", true);
294 } else {
295 return false;
296 }
297 return true;
298 } catch (IOException e) {
299 return false;
300 }
301 }
302
303 @Override
304 public FilePathDisk toRealPath() {
305 return getPath(toRealPath(Paths.get(name)).toString());
306 }
307
308 private static Path toRealPath(Path path) {
309 try {
310 path = path.toRealPath();
311 } catch (IOException e) {
312 /*
313 * File does not exist or isn't accessible, try to get the real path
314 * of parent directory.
315 *
316 * toRealPath() can also throw AccessDeniedException on accessible
317 * remote directory on Windows if other directories on remote drive
318 * aren't accessible, but toAbsolutePath() should work.
319 */
320 path = parentToRealPath(path.toAbsolutePath().normalize());
321 }
322 return path;
323 }
324
325 private static Path parentToRealPath(Path path) {
326 Path parent = path.getParent();
327 if (parent == null) {
328 return path;
329 }
330 try {
331 parent = parent.toRealPath();
332 } catch (IOException e) {
333 parent = parentToRealPath(parent);
334 }
335 return parent.resolve(path.getFileName());
336 }
337
338 @Override
339 public FilePath getParent() {
340 Path p = Paths.get(name).getParent();
341 return p == null ? null : getPath(p.toString());
342 }
343
344 @Override
345 public boolean isDirectory() {
346 return Files.isDirectory(Paths.get(name));
347 }
348
349 @Override
350 public boolean isRegularFile() {
351 return Files.isRegularFile(Paths.get(name));
352 }
353
354 @Override
355 public boolean isAbsolute() {
356 return Paths.get(name).isAbsolute();
357 }
358
359 @Override
360 public long lastModified() {
361 try {
362 return Files.getLastModifiedTime(Paths.get(name)).toMillis();
363 } catch (IOException e) {
364 return 0L;
365 }
366 }
367
368 @Override
369 public void createDirectory() {
370 Path dir = Paths.get(name);
371 try {
372 Files.createDirectory(dir);
373 } catch (FileAlreadyExistsException e) {
374 throw DbException.get(ErrorCode.FILE_CREATION_FAILED_1, name + " (a file with this name already exists)");
375 } catch (IOException e) {
376 IOException cause = e;
377 for (int i = 0; i < SysProperties.MAX_FILE_RETRY; i++) {
378 if (Files.isDirectory(dir)) {
379 return;
380 }
381 try {
382 Files.createDirectory(dir);
383 } catch (FileAlreadyExistsException ex) {
384 throw DbException.get(ErrorCode.FILE_CREATION_FAILED_1,
385 name + " (a file with this name already exists)");
386 } catch (IOException ex) {
387 cause = ex;
388 }
389 wait(i);
390 }
391 throw DbException.get(ErrorCode.FILE_CREATION_FAILED_1, cause, name);
392 }
393 }
394
395 @Override
396 public OutputStream newOutputStream(boolean append) throws IOException {
397 Path file = Paths.get(name);
398 OpenOption[] options = append //
399 ? new OpenOption[] { StandardOpenOption.CREATE, StandardOpenOption.APPEND }
400 : new OpenOption[0];
401 try {
402 Path parent = file.getParent();
403 if (parent != null) {
404 Files.createDirectories(parent);
405 }
406 OutputStream out = Files.newOutputStream(file, options);
407 IOUtils.trace("openFileOutputStream", name, out);
408 return out;
409 } catch (IOException e) {
410 freeMemoryAndFinalize();
411 return Files.newOutputStream(file, options);
412 }
413 }
414
415 @Override
416 public InputStream newInputStream() throws IOException {
417 if (name.matches("[a-zA-Z]{2,19}:.*")) {
418 // if the ':' is in position 1, a windows file access is assumed:
419 // C:.. or D:, and if the ':' is not at the beginning, assume its a
420 // file name with a colon
421 if (name.startsWith(CLASSPATH_PREFIX)) {
422 String fileName = name.substring(CLASSPATH_PREFIX.length());
423 // Force absolute resolution in Class.getResourceAsStream
424 if (!fileName.startsWith("/")) {
425 fileName = "/" + fileName;
426 }
427 InputStream in = getClass().getResourceAsStream(fileName);
428 if (in == null) {
429 // ClassLoader.getResourceAsStream doesn't need leading "/"
430 in = Thread.currentThread().getContextClassLoader().
431 getResourceAsStream(fileName.substring(1));
432 }
433 if (in == null) {
434 throw new FileNotFoundException("resource " + fileName);
435 }
436 return in;
437 }
438 // otherwise a URL is assumed
439 URL url = new URL(name);
440 return url.openStream();
441 }
442 InputStream in = Files.newInputStream(Paths.get(name));
443 IOUtils.trace("openFileInputStream", name, in);
444 return in;
445 }
446
447 /**
448 * Call the garbage collection and run finalization. This close all files
449 * that were not closed, and are no longer referenced.
450 */
451 static void freeMemoryAndFinalize() {
452 IOUtils.trace("freeMemoryAndFinalize", null, null);
453 Runtime rt = Runtime.getRuntime();
454 long mem = rt.freeMemory();
455 for (int i = 0; i < 16; i++) {
456 rt.gc();
457 long now = rt.freeMemory();
458 rt.runFinalization();
459 if (now == mem) {
460 break;
461 }
462 mem = now;
463 }
464 }
465
466 @Override
467 public FileChannel open(String mode) throws IOException {
468 FileChannel f = FileChannel.open(Paths.get(name), FileUtils.modeToOptions(mode), FileUtils.NO_ATTRIBUTES);
469 IOUtils.trace("open", name, f);
470 return f;
471 }
472
473 @Override
474 public String getScheme() {
475 return "file";
476 }
477
478 @Override
479 public FilePath createTempFile(String suffix, boolean inTempDir) throws IOException {
480 Path file = Paths.get(name + '.').toAbsolutePath();
481 String prefix = file.getFileName().toString();
482 if (inTempDir) {
483 final Path tempDir = Paths.get(System.getProperty("java.io.tmpdir", "."));
484 if (!Files.isDirectory(tempDir)) {
485 Files.createDirectories(tempDir);
486 }
487 file = Files.createTempFile(prefix, suffix);
488 } else {
489 Path dir = file.getParent();
490 Files.createDirectories(dir);
491 file = Files.createTempFile(dir, prefix, suffix);
492 }
493 return get(file.toString());
494 }
495
496 }