open a stream load a script locally or in the classpath @param scriptPath the path of the script @return a stream (it is the responsibility of the caller to close it) @throws IllegalStateException if we could not open a stream
(String scriptPath)
| 125 | * @throws IllegalStateException if we could not open a stream |
| 126 | */ |
| 127 | public static InputStream getScriptAsStream(String scriptPath) { |
| 128 | //protected static InputStream getScriptAsStream(String scriptPath) { |
| 129 | InputStream is = null; |
| 130 | File file = new File(scriptPath); |
| 131 | // In the frontend give preference to the local file. |
| 132 | // In the backend, try the jar first |
| 133 | if (UDFContext.getUDFContext().isFrontend() && file.exists()) { |
| 134 | try { |
| 135 | is = new FileInputStream(file); |
| 136 | } catch (FileNotFoundException e) { |
| 137 | throw new IllegalStateException("could not find existing file "+scriptPath, e); |
| 138 | } |
| 139 | } else { |
| 140 | if (Shell.WINDOWS && scriptPath.charAt(1)==':') { |
| 141 | scriptPath = scriptPath.charAt(0) + scriptPath.substring(2); |
| 142 | } |
| 143 | // Try system, current and context classloader. |
| 144 | is = ScriptEngine.class.getResourceAsStream(scriptPath); |
| 145 | if (is == null) { |
| 146 | is = getResourceUsingClassLoader(scriptPath, ScriptEngine.class.getClassLoader()); |
| 147 | } |
| 148 | if (is == null) { |
| 149 | is = getResourceUsingClassLoader(scriptPath, Thread.currentThread().getContextClassLoader()); |
| 150 | } |
| 151 | if (is == null && !file.isAbsolute()) { |
| 152 | String path = "/" + scriptPath; |
| 153 | is = ScriptEngine.class.getResourceAsStream(path); |
| 154 | if (is == null) { |
| 155 | is = getResourceUsingClassLoader(path, ScriptEngine.class.getClassLoader()); |
| 156 | } |
| 157 | if (is == null) { |
| 158 | is = getResourceUsingClassLoader(path, Thread.currentThread().getContextClassLoader()); |
| 159 | } |
| 160 | } |
| 161 | } |
| 162 | if (is == null && file.exists()) { |
| 163 | try { |
| 164 | is = new FileInputStream(file); |
| 165 | } catch (FileNotFoundException e) { |
| 166 | throw new IllegalStateException("could not find existing file "+scriptPath, e); |
| 167 | } |
| 168 | } |
| 169 | |
| 170 | // TODO: discuss if we want to add logic here to load a script from HDFS |
| 171 | |
| 172 | if (is == null) { |
| 173 | throw new IllegalStateException( |
| 174 | "Could not initialize interpreter (from file system or classpath) with " + scriptPath); |
| 175 | } |
| 176 | return is; |
| 177 | } |
| 178 | |
| 179 | private static InputStream getResourceUsingClassLoader(String fullFilename, ClassLoader loader) { |
| 180 | if (loader != null) { |
no test coverage detected