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.creadur.whisker.app.load;
20  
21  import java.io.IOException;
22  import java.io.InputStream;
23  
24  import org.apache.creadur.whisker.app.StreamableResource;
25  
26  /**
27   * Streams, on demand, the contents of a resource located on the class path.
28   */
29  public final class StreamableClassPathResource extends StreamableResource {
30  
31      /**
32       * The full name <strong>including path</strong>
33       * of a resource on the class path.
34       */
35      private final String name;
36  
37      /**
38       * Constructs an instance that streams the given class path resource
39       * on demand.
40       * @param name full name <strong>including path</strong> of
41       * a resource on the class path,
42       * not null
43       */
44      public StreamableClassPathResource(final String name) {
45          super();
46          this.name = name;
47      }
48  
49  
50      /**
51       * Gets the location on the class path of the resource to be streamed.
52       * @return not null
53       */
54      public String getName() {
55          return name;
56      }
57  
58      /**
59       * Is this resource found on the classpath?
60       * @return true when the resource is found on the classpath,
61       * null otherwise
62       */
63      public boolean exists()  {
64          try {
65              return open() != null;
66          } catch (IOException e) {
67              return false;
68          }
69      }
70  
71      /**
72       * Opens a resource on the classpath.
73       * @return not null
74       * @see StreamableResource#open()
75       * @throws IOException when resource cannot be open
76       */
77      @Override
78      public InputStream open() throws IOException {
79          return getClass().getClassLoader().getResourceAsStream(name);
80      }
81  
82      /**
83       * Suitable for logging.
84       * @return a description
85       */
86      @Override
87      public String toString() {
88          return "StreamableClassPathResource [name=" + name + "]";
89      }
90  }