1 package org.apache.velocity.tools.config;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 import java.io.InputStream;
23 import java.io.IOException;
24 import java.net.URL;
25 import org.apache.velocity.exception.ResourceNotFoundException;
26 import org.apache.velocity.runtime.log.Log;
27 import org.apache.velocity.tools.ConversionUtils;
28
29
30
31
32
33
34
35
36 public abstract class FileFactoryConfiguration extends FactoryConfiguration
37 {
38 protected FileFactoryConfiguration(Class clazz, String id)
39 {
40 super(clazz, id);
41 }
42
43
44
45
46
47
48 public abstract void read(InputStream input) throws IOException;
49
50
51
52
53
54
55
56
57 public void read(String path)
58 {
59 read(path, true);
60 }
61
62 public void read(URL url)
63 {
64 read(url, true);
65 }
66
67 public void read(String path, boolean required)
68 {
69 read(path, required, null);
70 }
71
72 public void read(URL url, boolean required)
73 {
74 read(url, required, null);
75 }
76
77 public void read(String path, boolean required, Log log)
78 {
79 if (path == null)
80 {
81 throw new NullPointerException("Path value cannot be null");
82 }
83 if (log != null && log.isTraceEnabled())
84 {
85 log.trace("Attempting to read configuration file at: "+path);
86 }
87
88 URL url = findURL(path);
89 if (url != null)
90 {
91 read(url, required, log);
92 }
93 else
94 {
95 String msg = "Could not find configuration file at: "+path;
96 if (log != null)
97 {
98 log.debug(msg);
99 }
100 if (required)
101 {
102 throw new ResourceNotFoundException(msg);
103 }
104 }
105 }
106
107 protected URL findURL(String path)
108 {
109 return ConversionUtils.toURL(path, this);
110 }
111
112 protected void read(URL url, boolean required, Log log)
113 {
114 try
115 {
116 read(url, url.openStream(), required, log);
117
118 addSource(" .read("+url.toString()+")");
119 }
120 catch (IOException ioe)
121 {
122 String msg = "Could not open stream from: "+url;
123 if (log != null)
124 {
125 log.debug(msg, ioe);
126 }
127 if (required)
128 {
129 throw new RuntimeException(msg, ioe);
130 }
131 }
132 }
133
134
135 protected void read(Object source, InputStream inputStream,
136 boolean required, Log log)
137 {
138 try
139 {
140 read(inputStream);
141 }
142 catch (IOException ioe)
143 {
144 String msg = "InputStream could not be read from: "+source;
145 if (log != null)
146 {
147 log.debug(msg, ioe);
148 }
149 if (required)
150 {
151 throw new RuntimeException(msg, ioe);
152 }
153 }
154 finally
155 {
156 try
157 {
158 if (inputStream != null)
159 {
160 inputStream.close();
161 }
162 }
163 catch (IOException ioe)
164 {
165 if (log != null)
166 {
167 log.error("Failed to close input stream for "+source, ioe);
168 }
169 }
170 }
171 }
172
173 }