ScriptingFunctions.java revision 953:221a84ef44c0
1/* 2 * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26package jdk.nashorn.internal.runtime; 27 28import static jdk.nashorn.internal.lookup.Lookup.MH; 29import static jdk.nashorn.internal.runtime.ECMAErrors.typeError; 30import static jdk.nashorn.internal.runtime.ScriptRuntime.UNDEFINED; 31 32import java.io.BufferedReader; 33import java.io.File; 34import java.io.IOException; 35import java.io.InputStreamReader; 36import java.io.OutputStreamWriter; 37import java.lang.invoke.MethodHandle; 38import java.lang.invoke.MethodHandles; 39import java.util.Map; 40import java.util.StringTokenizer; 41 42/** 43 * Global functions supported only in scripting mode. 44 */ 45public final class ScriptingFunctions { 46 47 /** Handle to implementation of {@link ScriptingFunctions#readLine} - Nashorn extension */ 48 public static final MethodHandle READLINE = findOwnMH("readLine", Object.class, Object.class, Object.class); 49 50 /** Handle to implementation of {@link ScriptingFunctions#readFully} - Nashorn extension */ 51 public static final MethodHandle READFULLY = findOwnMH("readFully", Object.class, Object.class, Object.class); 52 53 /** Handle to implementation of {@link ScriptingFunctions#exec} - Nashorn extension */ 54 public static final MethodHandle EXEC = findOwnMH("exec", Object.class, Object.class, Object.class, Object.class); 55 56 /** EXEC name - special property used by $EXEC API. */ 57 public static final String EXEC_NAME = "$EXEC"; 58 59 /** OUT name - special property used by $EXEC API. */ 60 public static final String OUT_NAME = "$OUT"; 61 62 /** ERR name - special property used by $EXEC API. */ 63 public static final String ERR_NAME = "$ERR"; 64 65 /** EXIT name - special property used by $EXEC API. */ 66 public static final String EXIT_NAME = "$EXIT"; 67 68 /** Names of special properties used by $ENV API. */ 69 public static final String ENV_NAME = "$ENV"; 70 71 private static final String PWD_NAME = "PWD"; 72 73 private ScriptingFunctions() { 74 } 75 76 /** 77 * Nashorn extension: global.readLine (scripting-mode-only) 78 * Read one line of input from the standard input. 79 * 80 * @param self self reference 81 * @param prompt String used as input prompt 82 * 83 * @return line that was read 84 * 85 * @throws IOException if an exception occurs 86 */ 87 public static Object readLine(final Object self, final Object prompt) throws IOException { 88 if (prompt != UNDEFINED) { 89 System.out.print(JSType.toString(prompt)); 90 } 91 final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); 92 return reader.readLine(); 93 } 94 95 /** 96 * Nashorn extension: Read the entire contents of a text file and return as String. 97 * 98 * @param self self reference 99 * @param file The input file whose content is read. 100 * 101 * @return String content of the input file. 102 * 103 * @throws IOException if an exception occurs 104 */ 105 public static Object readFully(final Object self, final Object file) throws IOException { 106 File f = null; 107 108 if (file instanceof File) { 109 f = (File)file; 110 } else if (file instanceof String || file instanceof ConsString) { 111 f = new java.io.File(((CharSequence)file).toString()); 112 } 113 114 if (f == null || !f.isFile()) { 115 throw typeError("not.a.file", ScriptRuntime.safeToString(file)); 116 } 117 118 return new String(Source.readFully(f)); 119 } 120 121 /** 122 * Nashorn extension: exec a string in a separate process. 123 * 124 * @param self self reference 125 * @param string string to execute 126 * @param input input 127 * 128 * @return output string from the request 129 * @throws IOException if any stream access fails 130 * @throws InterruptedException if execution is interrupted 131 */ 132 public static Object exec(final Object self, final Object string, final Object input) throws IOException, InterruptedException { 133 // Current global is need to fetch additional inputs and for additional results. 134 final ScriptObject global = Context.getGlobal(); 135 136 // Break exec string into tokens. 137 final StringTokenizer tokenizer = new StringTokenizer(JSType.toString(string)); 138 final String[] cmdArray = new String[tokenizer.countTokens()]; 139 for (int i = 0; tokenizer.hasMoreTokens(); i++) { 140 cmdArray[i] = tokenizer.nextToken(); 141 } 142 143 // Set up initial process. 144 final ProcessBuilder processBuilder = new ProcessBuilder(cmdArray); 145 146 // Current ENV property state. 147 final Object env = global.get(ENV_NAME); 148 if (env instanceof ScriptObject) { 149 final ScriptObject envProperties = (ScriptObject)env; 150 151 // If a working directory is present, use it. 152 final Object pwd = envProperties.get(PWD_NAME); 153 if (pwd != UNDEFINED) { 154 processBuilder.directory(new File(JSType.toString(pwd))); 155 } 156 157 // Set up ENV variables. 158 final Map<String, String> environment = processBuilder.environment(); 159 environment.clear(); 160 for (final Map.Entry<Object, Object> entry : envProperties.entrySet()) { 161 environment.put(JSType.toString(entry.getKey()), JSType.toString(entry.getValue())); 162 } 163 } 164 165 // Start the process. 166 final Process process = processBuilder.start(); 167 final IOException exception[] = new IOException[2]; 168 169 // Collect output. 170 final StringBuilder outBuffer = new StringBuilder(); 171 final Thread outThread = new Thread(new Runnable() { 172 @Override 173 public void run() { 174 final char buffer[] = new char[1024]; 175 try (final InputStreamReader inputStream = new InputStreamReader(process.getInputStream())) { 176 for (int length; (length = inputStream.read(buffer, 0, buffer.length)) != -1; ) { 177 outBuffer.append(buffer, 0, length); 178 } 179 } catch (final IOException ex) { 180 exception[0] = ex; 181 } 182 } 183 }, "$EXEC output"); 184 185 // Collect errors. 186 final StringBuilder errBuffer = new StringBuilder(); 187 final Thread errThread = new Thread(new Runnable() { 188 @Override 189 public void run() { 190 final char buffer[] = new char[1024]; 191 try (final InputStreamReader inputStream = new InputStreamReader(process.getErrorStream())) { 192 for (int length; (length = inputStream.read(buffer, 0, buffer.length)) != -1; ) { 193 errBuffer.append(buffer, 0, length); 194 } 195 } catch (final IOException ex) { 196 exception[1] = ex; 197 } 198 } 199 }, "$EXEC error"); 200 201 // Start gathering output. 202 outThread.start(); 203 errThread.start(); 204 205 // If input is present, pass on to process. 206 try (OutputStreamWriter outputStream = new OutputStreamWriter(process.getOutputStream())) { 207 if (input != UNDEFINED) { 208 final String in = JSType.toString(input); 209 outputStream.write(in, 0, in.length()); 210 } 211 } catch (final IOException ex) { 212 // Process was not expecting input. May be normal state of affairs. 213 } 214 215 // Wait for the process to complete. 216 final int exit = process.waitFor(); 217 outThread.join(); 218 errThread.join(); 219 220 final String out = outBuffer.toString(); 221 final String err = errBuffer.toString(); 222 223 // Set globals for secondary results. 224 global.set(OUT_NAME, out, false); 225 global.set(ERR_NAME, err, false); 226 global.set(EXIT_NAME, exit, false); 227 228 // Propagate exception if present. 229 for (final IOException element : exception) { 230 if (element != null) { 231 throw element; 232 } 233 } 234 235 // Return the result from stdout. 236 return out; 237 } 238 239 private static MethodHandle findOwnMH(final String name, final Class<?> rtype, final Class<?>... types) { 240 return MH.findStatic(MethodHandles.lookup(), ScriptingFunctions.class, name, MH.type(rtype, types)); 241 } 242} 243