1   
2   
3   
4   
5   
6   
7   
8   
9   
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  package org.apache.maven.index.reader;
20  
21  import java.io.BufferedInputStream;
22  import java.io.BufferedOutputStream;
23  import java.io.IOException;
24  import java.io.InputStream;
25  import java.io.OutputStream;
26  import java.nio.file.Files;
27  import java.nio.file.NoSuchFileException;
28  import java.nio.file.Path;
29  
30  
31  
32  
33  
34  public class DirectoryResourceHandler implements WritableResourceHandler {
35      private final Path rootDirectory;
36  
37      public DirectoryResourceHandler(final Path rootDirectory) {
38          if (rootDirectory == null) {
39              throw new NullPointerException("null rootDirectory");
40          }
41          if (!Files.isDirectory(rootDirectory)) {
42              throw new IllegalArgumentException("rootDirectory exists and is not a directory");
43          }
44          this.rootDirectory = rootDirectory;
45      }
46  
47      public Path getRootDirectory() {
48          return rootDirectory;
49      }
50  
51      @Override
52      public WritableResource locate(final String name) {
53          return new PathResource(rootDirectory.resolve(name));
54      }
55  
56      private static class PathResource implements WritableResource {
57          private final Path file;
58  
59          private PathResource(final Path file) {
60              this.file = file;
61          }
62  
63          @Override
64          public InputStream read() throws IOException {
65              try {
66                  return new BufferedInputStream(Files.newInputStream(file));
67              } catch (NoSuchFileException e) {
68                  return null;
69              }
70          }
71  
72          @Override
73          public OutputStream write() throws IOException {
74              return new BufferedOutputStream(Files.newOutputStream(file));
75          }
76      }
77  }