View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
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   * A trivial {@link Path} directory handler that does not perform any locking or extra bits, and just serves up files
32   * by name from specified existing directory.
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  }