MCPcopy Create free account
hub / github.com/apache/calcite / FileSource

Class FileSource

core/src/main/java/org/apache/calcite/util/Sources.java:169–363  ·  view source on GitHub ↗

Implementation of Source on the top of a File or URL.

Source from the content-addressed store, hash-verified

167 /** Implementation of {@link Source} on the top of a {@link File} or
168 * {@link URL}. */
169 private static class FileSource implements Source {
170 private final @Nullable File file;
171 private final URL url;
172
173 /**
174 * A flag indicating if the url is deduced from the file object.
175 */
176 private final boolean urlGenerated;
177
178 private FileSource(URL url) {
179 this.url = requireNonNull(url, "url");
180 this.file = urlToFile(url);
181 this.urlGenerated = false;
182 }
183
184 private FileSource(File file) {
185 this.file = requireNonNull(file, "file");
186 this.url = fileToUrl(file);
187 this.urlGenerated = true;
188 }
189
190 private File fileNonNull() {
191 return requireNonNull(file, "file");
192 }
193
194 private static @Nullable File urlToFile(URL url) {
195 if (!"file".equals(url.getProtocol())) {
196 return null;
197 }
198 URI uri;
199 try {
200 uri = url.toURI();
201 } catch (URISyntaxException e) {
202 throw new IllegalArgumentException("Unable to convert URL " + url + " to URI", e);
203 }
204 if (uri.isOpaque()) {
205 // It is like file:test%20file.c++
206 // getSchemeSpecificPart would return "test file.c++"
207 return new File(uri.getSchemeSpecificPart());
208 }
209 // See https://stackoverflow.com/a/17870390/1261287
210 return Paths.get(uri).toFile();
211 }
212
213 private static URL fileToUrl(File file) {
214 String filePath = file.getPath();
215 if (!file.isAbsolute()) {
216 // convert relative file paths
217 filePath = filePath.replace(File.separatorChar, '/');
218 if (file.isDirectory() && !filePath.endsWith("/")) {
219 filePath += "/";
220 }
221 try {
222 // We need to encode path. For instance, " " should become "%20"
223 // That is why java.net.URLEncoder.encode(java.lang.String, java.lang.String) is not
224 // suitable because it replaces " " with "+".
225 String encodedPath = new URI(null, null, filePath, null).getRawPath();
226 return URI.create("file:" + encodedPath).toURL();

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected