@Before public void setUp() { processManager = new ProcessManager() { @Override Process startProcess(ProcessBuilder processBuilder, String msgCommandInfo) { return processStartedByManager; } }; processStartedByManager = mock(Process.class); when(processStartedByManager.getInputStream()).thenReturn(mock(InputStream.class)); when(processStartedByManager.getErrorStream()).thenReturn(mock(InputStream.class)); when(processStartedByManager.getOutputStream()).thenReturn(mock(OutputStream.class)); processOne = mock(Process.class); processTwo = mock(Process.class); when(processOne.getInputStream()).thenReturn(mock(InputStream.class)); when(processOne.getErrorStream()).thenReturn(mock(InputStream.class)); when(processOne.getOutputStream()).thenReturn(mock(OutputStream.class)); when(processOne.exitValue()).thenThrow(new IllegalStateException()); when(processTwo.exitValue()).thenThrow(new IllegalStateException()); when(processTwo.getInputStream()).thenReturn(mock(InputStream.class)); when(processTwo.getErrorStream()).thenReturn(mock(InputStream.class)); when(processTwo.getOutputStream()).thenReturn(mock(OutputStream.class)); ConcurrentMap<Process, ProcessWrapper> processMap = processManager.getProcessMap(); wrapperForProcessOne = new ProcessWrapper(processOne, "tag1", null, inMemoryConsumer(), null, "ERROR: "); processMap.put(processOne, wrapperForProcessOne); wrapperForProcessTwo = new ProcessWrapper(processTwo, "tag2", null, inMemoryConsumer(), null, "ERROR: "); processMap.put(processTwo, wrapperForProcessTwo); }
private static void processInput(final InputSource stdinInput, final Process process) { if (log.isLoggable(Level.FINER)) { log.finer(stdinInput.toLogString("stdin")); } try { if (stdinInput.isEmpty()) { return; } stdinInput.copyTo(process.getOutputStream()); } catch (IOException ioe) { // Note: this is not an error! Perhaps the command just isn't hungry for // our input and exited with success. Process.waitFor (later) will tell // us. // // (Unlike out/err streams, which are read asynchronously, the input stream is written // synchronously, in its entirety, before processInput returns. If the input is // infinite, and is passed through e.g. "cat" subprocess and back into the // ByteArrayOutputStream, that will eventually run out of memory, causing the output stream // to be closed, "cat" to terminate with SIGPIPE, and processInput to receive an IOException. } finally { // if this statement is ever deleted, the process's outputStream // must be closed elsewhere -- it is not closed automatically Command.silentClose(process.getOutputStream()); } }
private IdedProtos.Response processRequest(IdedProtos.Request request) { try { request.writeDelimitedTo(process.getOutputStream()); process.getOutputStream().flush(); lock.lock(); try { for (; ; ) { if (error != null) { throw new RuntimeException(error); } if (response != null) { IdedProtos.Response response = this.response; this.response = null; return response; } condition.await(); } } finally { lock.unlock(); } } catch (InterruptedException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } }
/** * System command. Execute a command and insert the result. * * @param args * @param help * @param patterns * @param low * @param high */ public String system_internal(boolean allowFail, String args[]) throws Exception { verifyCommand( args, "${" + (allowFail ? "system-allow-fail" : "system") + ";<command>[;<in>]}, execute a system command", null, 2, 3); String command = args[1]; String input = null; if (args.length > 2) { input = args[2]; } Process process = Runtime.getRuntime().exec(command, null, domain.getBase()); if (input != null) { process.getOutputStream().write(input.getBytes("UTF-8")); } process.getOutputStream().close(); String s = IO.collect(process.getInputStream(), "UTF-8"); int exitValue = process.waitFor(); if (exitValue != 0) return exitValue + ""; if (!allowFail && (exitValue != 0)) { domain.error("System command " + command + " failed with " + exitValue); } return s.trim(); }
/** * Convert image formats which are not supported by Word (eg EPS, PDF), into ones which are. This * requires ImageMagick to be on your system's path; for EPS and PDF images, Ghostscript is also * required. * * @param is * @param os * @param density PixelsPerInch * @throws IOException * @throws InterruptedException */ public static void convertToPNG(InputStream is, OutputStream os, int density) throws IOException, InterruptedException { /* * See http://www.eichberger.de/2006/05/imagemagick-in-servlets.html * * "Calling 'convert - png:-' as an external command and feeding it the * source image as standard input and reading the converted image * (in this case png) as standard output" * */ log.info("Start ImageMagick..."); Process p = Runtime.getRuntime() .exec("imconvert -density " + density + " -units PixelsPerInch - png:-"); // GraphicsMagick is a little quicker than ImageMagick, // but v1.3.3 (of Dec 2008) still has the now fixed in GM bug // whereby the right most ~10% of the resulting image is chopped off // Process p = Runtime.getRuntime().exec("gm convert -density " + density + " -units // PixelsPerInch - png:-"); /* On Windows, if this results in "Invalid Parameter", * then either ImageMagick is not installed, * or exec is finding the wrong convert * program. See http://studio.imagemagick.org/pipermail/magick-users/2005-October/016464.html * and http://www.imagemagick.org/discourse-server/viewtopic.php?f=1&t=8324&start=0 * * Rather than use full path, rename convert to imconvert (which Alfresco and others do) * */ // initialize Gobblers StreamGobbler inGobbler = new StreamGobbler(p.getInputStream(), os); StreamGobbler errGobbler = new StreamGobbler(p.getErrorStream(), System.err); // start them inGobbler.start(); errGobbler.start(); // p.getOutputStream() is the _output stream_ of the subprocess, so // this copies is into the standard input stream of the process try { copy2(is, new BufferedOutputStream(p.getOutputStream())); p.getOutputStream().close(); log.debug("Image copied..."); } catch (IOException ioe) { ioe.printStackTrace(); // debug copy2(p.getErrorStream(), System.err); } if (p.waitFor() != 0) { log.error("Error"); } log.debug("End Process..."); }
void removeEntry(String entry, boolean first) { String[] params = entry.split(","); entry = params[0] + " " + params[1]; List<String> hosts = new ArrayList<String>(); try { Process proc = Runtime.getRuntime().exec("cat /etc/hosts"); BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream())); String line = null; while ((line = reader.readLine()) != null) { if (!line.equals("") && line != null) { if (line.contains(entry) && first) { first = false; } else if (line.contains(entry) && !first) { hosts.add(line); } else if (!line.contains(entry)) { hosts.add(line); } } } } catch (Exception e) { } if (hosts.size() > 0) { try { Process proc = Runtime.getRuntime().exec("su"); DataOutputStream os = new DataOutputStream(proc.getOutputStream()); os.writeBytes("mount -o rw,remount -t " + fs + " " + block + " /system\n"); os.writeBytes("echo '' > /etc/hosts\n"); for (String s : hosts) { os.writeBytes("echo '" + s + "' >> /etc/hosts\n"); } os.writeBytes("mount -o ro,remount -t " + fs + " " + block + " /system\n"); os.writeBytes("exit\n"); os.flush(); os.close(); proc.waitFor(); } catch (Exception e) { } } else { try { Process proc = Runtime.getRuntime().exec("su"); DataOutputStream os = new DataOutputStream(proc.getOutputStream()); os.writeBytes("mount -o rw,remount -t " + fs + " " + block + " /system\n"); os.writeBytes("echo '' > /etc/hosts\n"); os.writeBytes("mount -o ro,remount -t " + fs + " " + block + " /system\n"); os.writeBytes("exit\n"); os.flush(); os.close(); proc.waitFor(); } catch (Exception e) { } } }
private void exec( final HttpServletRequest req, final HttpServletResponse rsp, final ProjectControl project) throws IOException { final Process proc = Runtime.getRuntime() .exec( new String[] {gitwebCgi.toAbsolutePath().toString()}, makeEnv(req, project), gitwebCgi.toAbsolutePath().getParent().toFile()); copyStderrToLog(proc.getErrorStream()); if (0 < req.getContentLength()) { copyContentToCGI(req, proc.getOutputStream()); } else { proc.getOutputStream().close(); } try (InputStream in = new BufferedInputStream(proc.getInputStream(), bufferSize)) { readCgiHeaders(rsp, in); try (OutputStream out = rsp.getOutputStream()) { final byte[] buf = new byte[bufferSize]; int n; while ((n = in.read(buf)) > 0) { out.write(buf, 0, n); } } } catch (IOException e) { // The browser has probably closed its input stream. We don't // want to continue executing this request. // proc.destroy(); return; } try { proc.waitFor(); final int status = proc.exitValue(); if (0 != status) { log.error("Non-zero exit status (" + status + ") from " + gitwebCgi); if (!rsp.isCommitted()) { rsp.sendError(500); } } } catch (InterruptedException ie) { log.debug("CGI: interrupted waiting for CGI to terminate"); } }
public static TByteArrayList transformByExternalCommand( final String command, final InputStream input) throws IOException { final Process process = Runtime.getRuntime().exec(command); final InputStream in = process.getInputStream(); final OutputStream out = process.getOutputStream(); final TByteArrayList bytes = new TByteArrayList(100500); final byte[] buffer = new byte[1024 * 1024]; try { int read; while ((read = input.read(buffer)) > 0) { out.write(buffer, 0, read); if (in.available() > 0) { read = in.read(buffer); bytes.add(buffer, 0, read); } } out.close(); while ((read = in.read(buffer)) > 0) { bytes.add(buffer, 0, read); } in.close(); } catch (IOException ioe) { System.err.println(readByteStream(process.getErrorStream())); LOG.error(ioe); throw ioe; } return bytes; }
public String execSu(String cmd) { Log.d(TAG, "^ Executing as SU '" + cmd + "'"); try { Process process = Runtime.getRuntime().exec("su"); DataInputStream is = new DataInputStream(process.getInputStream()); DataOutputStream os = new DataOutputStream(process.getOutputStream()); os.writeBytes(cmd + "\n"); os.writeBytes("exit\n"); os.flush(); os.close(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); try { String fullOutput = ""; String line; while ((line = reader.readLine()) != null) { fullOutput = fullOutput + line + "\n"; } return fullOutput; } catch (IOException e) { // It seems IOException is thrown when it reaches EOF. e.printStackTrace(); Log.e(TAG, "^ execSU, IOException 1"); } process.waitFor(); } catch (IOException e) { e.printStackTrace(); Log.e(TAG, "^ execSU, IOException 2"); } catch (InterruptedException e) { e.printStackTrace(); Log.e(TAG, "^ execSU, InterruptedException"); } return ""; }
/** * Close the streams belonging to the given Process. In the original implementation all exceptions * were dropped which is probably not a good thing. On the other hand the signature allows * throwing an IOException so the curent implementation might be quite okay. * * @param process the <CODE>Process</CODE>. * @throws IOException closing one of the three streams failed */ private void closeStreams(final Process process) throws IOException { IOException caught = null; try { process.getInputStream().close(); } catch (IOException e) { caught = e; } try { process.getOutputStream().close(); } catch (IOException e) { caught = e; } try { process.getErrorStream().close(); } catch (IOException e) { caught = e; } if (caught != null) { throw caught; } }
private boolean makeFbReadable() { Log.d(TAG, "makeFbReadable: ......"); boolean success = false; Process process = null; DataOutputStream os = null; int exitValue = 0; try { if (isRooted()) { process = Runtime.getRuntime().exec("su"); os = new DataOutputStream(process.getOutputStream()); os.writeBytes("chmod 666 /dev/graphics/fb0 \n"); os.writeBytes("exit\n"); os.flush(); exitValue = process.waitFor(); Log.d(TAG, "@@@@@@@@@@@@@@@@@@@@ exitValue::" + exitValue); if (exitValue == 0) { success = true; } } } catch (Exception e) { } finally { // mIsRoot = true; } return success; }
/** * 变成一个系统的app * * @param context * @param name */ public static void toSystemApp(Context context, String name) { String packageName = context.getPackageName(); String[] commands = { "busybox mount -o remount,rw /system", "busybox cp /data/data/" + packageName + "/files/" + name + " /system/app/" + name, "busybox rm /data/data/" + packageName + "/files/" + name }; Process process = null; DataOutputStream dataOutputStream = null; try { process = Runtime.getRuntime().exec("su"); dataOutputStream = new DataOutputStream(process.getOutputStream()); int length = commands.length; for (int i = 0; i < length; i++) { dataOutputStream.writeBytes(commands[i] + "\n"); } dataOutputStream.writeBytes("exit\n"); dataOutputStream.flush(); process.waitFor(); } catch (Exception e) { } finally { try { if (dataOutputStream != null) { dataOutputStream.close(); } process.destroy(); } catch (Exception e) { } } }
public static void executeInTerminalCommandAndExit(String command) throws IOException, InterruptedException { String line = null; logger.info("Entering method executeCommand"); PrintWriter out = new PrintWriter( new OutputStreamWriter(new BufferedOutputStream(prcs.getOutputStream())), true); logger.info("Command to be executed = " + command); out.println(command); out.println("exit"); BufferedReader stdError = new BufferedReader(new InputStreamReader(prcs.getErrorStream())); logger.info("ERROR in the process - (if any)"); while ((line = stdError.readLine()) != null) { logger.info(line); } logger.info("End of error"); BufferedReader stdInput = new BufferedReader(new InputStreamReader(prcs.getInputStream())); logger.info("Output of the process - (if any)"); while ((line = stdInput.readLine()) != null) { logger.info(line); } logger.info("End of output"); int exitVal = prcs.waitFor(); logger.info("Process exitValue: " + exitVal); prcs.destroy(); }
public String executeCommand(String command) { System.out.println("$ " + command); StringBuffer output = new StringBuffer(); Process p = null; try { p = execute(command); p.waitFor(); String line = ""; BufferedReader reader = new BufferedReader(new InputStreamReader(p.getErrorStream())); while ((line = reader.readLine()) != null) { output.append(line + "\n"); } reader.close(); reader = new BufferedReader(new InputStreamReader(p.getInputStream())); while ((line = reader.readLine()) != null) { output.append(line + "\n"); } } catch (Exception e) { e.printStackTrace(); } finally { try { p.getInputStream().close(); p.getOutputStream().close(); p.getErrorStream().close(); } catch (IOException e) { e.printStackTrace(); } } System.out.println(output.toString()); return output.toString(); }
public static void signalStop(Process process) throws IOException { if (isRunning(process)) { OutputStream processOutputStream = process.getOutputStream(); processOutputStream.write(TERM_TOKEN.concat("\n").getBytes()); processOutputStream.flush(); } }
public void run() { if (this.pid == null) { return; } try { Process process = new ProcessBuilder().command("su").redirectErrorStream(true).start(); InputStream stdout = process.getInputStream(); OutputStream stdin = process.getOutputStream(); SUKillerOutputThread stdoutThread = new SUKillerOutputThread(); stdoutThread.setInputStream(stdout); stdoutThread.start(); String kill = "kill -9 " + this.pid + "\n"; stdin.write(kill.getBytes(), 0, kill.length()); stdin.write("exit\n".getBytes(), 0, "exit\n".length()); stdin.flush(); process.waitFor(); stdoutThread.interrupt(); try { process.destroy(); } catch (Exception e) { } Message msg = Message.obtain(ExecActivity.handler, 3); ExecActivity.handler.sendMessage(msg); } catch (Exception e) { e.printStackTrace(); } }
public static boolean upgradeRootPermission(String pkgCodePath) { Process process = null; DataOutputStream os = null; try { String cmd = "chmod 755 " + pkgCodePath; process = Runtime.getRuntime().exec("su"); os = new DataOutputStream(process.getOutputStream()); os.writeBytes(cmd + "\n"); os.writeBytes("exit\n"); os.flush(); process.waitFor(); } catch (Exception e) { return false; } finally { try { if (os != null) { os.close(); } assert process != null; process.destroy(); } catch (Exception ignored) { } } return true; }
@Override public void run() { logUpdate = new LogUpdate(); try { File dir = new File(NativeHelper.app_opt, "bin"); Process sh = Runtime.getRuntime().exec("/system/bin/sh", NativeHelper.envp, dir); OutputStream os = sh.getOutputStream(); DebugStreamThread it = new DebugStreamThread(sh.getInputStream(), logUpdate); DebugStreamThread et = new DebugStreamThread(sh.getErrorStream(), logUpdate); it.start(); et.start(); Log.i(TAG, command); writeCommand(os, command); writeCommand(os, "exit"); sh.waitFor(); Log.i(TAG, "Done!"); } catch (Exception e) { Log.e(TAG, "Error!!!", e); } finally { synchronized (DebugLogActivity.this) { commandThread = null; } sendBroadcast(new Intent(COMMAND_FINISHED)); } }
private static void checkIsAvailableAndGetVersion() { ProcessBuilder pb = new ProcessBuilder(COMMAND, "--version"); pb.redirectErrorStream(true); Process p = null; try { p = pb.start(); p.waitFor(); perconaToolkitVersion = StreamUtil.getStreamContents(p.getInputStream()); if (perconaToolkitVersion != null) { perconaToolkitVersion = perconaToolkitVersion.replaceAll("\n|\r", ""); } available = true; log.info("Using percona toolkit: " + perconaToolkitVersion); } catch (IOException e) { available = false; } catch (InterruptedException e) { available = false; } finally { if (p != null) { StreamUtil.closeQuietly(p.getErrorStream()); StreamUtil.closeQuietly(p.getInputStream()); StreamUtil.closeQuietly(p.getOutputStream()); p.destroy(); } } }
public void makeTemp() { Process process = null; DataOutputStream os = null; try { process = Runtime.getRuntime().exec("su"); os = new DataOutputStream(process.getOutputStream()); os.writeBytes("mount -o remount,rw /system\n"); os.writeBytes( "cp -f /system/build.prop " + Environment.getExternalStorageDirectory().getAbsolutePath() + "/buildprop.tmp\n"); os.writeBytes( "chmod 777 " + Environment.getExternalStorageDirectory().getAbsolutePath() + "/buildprop.tmp\n"); os.writeBytes("mount -o remount,ro /system\n"); os.writeBytes("exit\n"); os.flush(); process.waitFor(); } catch (Exception e) { log("Error in making temp file: " + e.getMessage()); } finally { try { if (os != null) { os.close(); } process.destroy(); } catch (Exception e) { log("Error in closing temp process: " + e.getMessage()); } } tempFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/buildprop.tmp"; }
/** * Creates a transcoded input stream by executing the given command. If <code>in</code> is not * null, data from it is copied to the command. * * @param command The command to execute. * @param in Data to feed to the command. May be <code>null</code>. * @throws IOException If an I/O error occurs. */ public TranscodeInputStream(String[] command, final InputStream in) throws IOException { StringBuffer buf = new StringBuffer("Starting transcoder: "); for (String s : command) { buf.append('[').append(s).append("] "); } LOG.debug(buf); process = Runtime.getRuntime().exec(command); processOutputStream = process.getOutputStream(); processInputStream = process.getInputStream(); // Must read stderr from the process, otherwise it may block. final String name = command[0]; new InputStreamReaderThread(process.getErrorStream(), name, true).start(); // Copy data in a separate thread if (in != null) { new Thread(name + " TranscodedInputStream copy thread") { public void run() { try { IOUtils.copy(in, processOutputStream); } catch (IOException x) { // Intentionally ignored. Will happen if the remote player closes the stream. } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(processOutputStream); } } }.start(); } }
public void backup() { Process process = null; DataOutputStream os = null; try { process = Runtime.getRuntime().exec("su"); os = new DataOutputStream(process.getOutputStream()); os.writeBytes("mount -o remount,rw /system\n"); os.writeBytes( "cp -f /system/build.prop " + Environment.getExternalStorageDirectory().getAbsolutePath() + "/build.prop.bak\n"); os.writeBytes("mount -o remount,ro /system\n"); os.writeBytes("exit\n"); os.flush(); process.waitFor(); } catch (Exception e) { log("Error in backup: " + e.getMessage()); } finally { try { if (os != null) { os.close(); } process.destroy(); } catch (Exception e) { log("Error in closing backup process: " + e.getMessage()); } } log( "build.prop Backup at " + Environment.getExternalStorageDirectory().getAbsolutePath() + "/build.prop.bak"); }
public boolean executeFilter(@NotNull Editor editor, @NotNull TextRange range, String command) throws IOException { if (logger.isDebugEnabled()) logger.debug("command=" + command); CharSequence chars = editor.getDocument().getCharsSequence(); StringReader car = new StringReader( chars.subSequence(range.getStartOffset(), range.getEndOffset()).toString()); StringWriter sw = new StringWriter(); logger.debug("about to create filter"); Process filter = Runtime.getRuntime().exec(command); logger.debug("filter created"); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(filter.getOutputStream())); logger.debug("sending text"); copy(car, writer); writer.close(); logger.debug("sent"); BufferedReader reader = new BufferedReader(new InputStreamReader(filter.getInputStream())); logger.debug("getting result"); copy(reader, sw); sw.close(); logger.debug("received"); editor.getDocument().replaceString(range.getStartOffset(), range.getEndOffset(), sw.toString()); lastCommand = command; return true; }
@Override protected boolean composeNative(String to, String subject, String body, File... attachments) throws IOException, InterruptedException { final DesktopEnvironment de = DesktopEnvironment.getDE(); final File vbs = FileUtils.getFile(EmailClient.class.getResource("OutlookEmail.vbs")); final List<String> l = new ArrayList<String>(6); l.add("cscript"); l.add(de.quoteParamForExec(vbs.getAbsolutePath())); if (to != null) l.add(createVBParam("to", to)); if (subject != null) l.add(createVBParam("subject", subject)); // at least set a parameter otherwise the usage get displayed l.add(createVBParam("unicodeStdIn", "1")); for (File attachment : attachments) { l.add(de.quoteParamForExec(attachment.getAbsolutePath())); } final Process process = new ProcessBuilder(l).start(); // VBScript only knows ASCII and UTF-16 final Writer writer = new BufferedWriter( new OutputStreamWriter(process.getOutputStream(), StringUtils.UTF16)); writer.write(body); writer.close(); final int returnCode = process.waitFor(); if (returnCode != 0) throw new IllegalStateException("Non zero return code: " + returnCode); return true; }
public void speak(String txt) { try { Runtime rtime = Runtime.getRuntime(); // start unix shell Process child = rtime.exec("/bin/sh"); // or "/bin/sh set -t" to auto-exit after 1 command BufferedWriter outCommand = new BufferedWriter(new OutputStreamWriter(child.getOutputStream())); // run a command outCommand.write("echo '" + txt + "' | festival --tts\n"); outCommand.flush(); // exit the unix shell outCommand.write("exit" + "\n"); outCommand.flush(); int wait = child.waitFor(); System.out.println("exit code: " + wait); } catch (Exception e) { e.printStackTrace(); } }
@Override protected boolean composeNative(String to, String subject, String body, File... attachments) throws IOException, InterruptedException { final Process process = Runtime.getRuntime().exec(new String[] {"osascript"}); final PrintStream w = new PrintStream(new BufferedOutputStream(process.getOutputStream())); // use ID to handle application renaming (always a slight delay after a rename for // this to work, though) w.println("tell application id \"" + AppleMailBundleID + "\""); w.println( " set theMessage to make new outgoing message with properties {" + getAppleMailParam(subject, body) + "}"); if (to != null) w.println( " tell theMessage to make new to recipient with properties {address:" + StringUtils.doubleQuote(to) + "}"); for (File attachment : attachments) { w.println( " tell content of theMessage to make new attachment with properties {file name:" + StringUtils.doubleQuote(attachment.getAbsolutePath()) + "} at after last paragraph"); } w.println("end tell"); w.close(); if (w.checkError()) throw new IOException(); final int returnCode = process.waitFor(); if (returnCode != 0) throw new IllegalStateException("Non zero return code: " + returnCode); return true; }
public SerialPort(File device, int baudrate, int flags) throws SecurityException, IOException { /* Check access permission */ if (!device.canRead() || !device.canWrite()) { try { /* Missing read/write permission, trying to chmod the file */ Process su; su = Runtime.getRuntime().exec("/system/bin/su"); String cmd = "chmod 666 " + device.getAbsolutePath() + "\n" + "exit\n"; su.getOutputStream().write(cmd.getBytes()); if ((su.waitFor() != 0) || !device.canRead() || !device.canWrite()) { throw new SecurityException(); } } catch (Exception e) { e.printStackTrace(); throw new SecurityException(); } } mFd = open(device.getAbsolutePath(), baudrate, flags); if (mFd == null) { Log.e(TAG, "native open returns null"); throw new IOException(); } mFileInputStream = new FileInputStream(mFd); mFileOutputStream = new FileOutputStream(mFd); mDevPath = device.getAbsolutePath(); }
public void open(VariableSpace space, Process sqlldrProcess) throws KettleException { String loadMethod = meta.getLoadMethod(); try { OutputStream os = null; if (OraBulkLoaderMeta.METHOD_AUTO_CONCURRENT.equals(loadMethod)) { os = sqlldrProcess.getOutputStream(); } else { // Else open the data file filled in. String dataFile = meta.getDataFile(); dataFile = space.environmentSubstitute(dataFile); os = new FileOutputStream(dataFile, false); } String encoding = meta.getEncoding(); if (Const.isEmpty(encoding)) { // Use the default encoding. output = new BufferedWriter(new OutputStreamWriter(os)); } else { // Use the specified encoding output = new BufferedWriter(new OutputStreamWriter(os, encoding)); } } catch (IOException e) { throw new KettleException("IO exception occured: " + e.getMessage(), e); } }
private void serve(InputStream sis, OutputStream sos) throws IOException { // kills the process if client closes the stream; // closes the stream if process is terminated/ended output. // therefore we need the interruption mechanism. Process process = Runtime.getRuntime().exec("bash"); InputStream pis = process.getInputStream(); InputStream pes = process.getErrorStream(); OutputStream pos = process.getOutputStream(); try { threads.add(new CopyThread(pis, sos)); threads.add(new CopyThread(pes, sos)); threads.add(new CopyThread(sis, pos)); threads.add( new InterruptibleThread() { protected void run0() throws InterruptedException { process.waitFor(); } }); Util.startJoin(threads); } finally { process.destroy(); } }
private String exec(final String... cmd) throws IOException, InterruptedException { assert cmd != null; ByteArrayOutputStream bout = new ByteArrayOutputStream(); Log.trace("Running: ", cmd); Process p = Runtime.getRuntime().exec(cmd); InputStream in = null; InputStream err = null; OutputStream out = null; try { int c; in = p.getInputStream(); while ((c = in.read()) != -1) { bout.write(c); } err = p.getErrorStream(); while ((c = err.read()) != -1) { bout.write(c); } out = p.getOutputStream(); p.waitFor(); } finally { close(in, out, err); } String result = bout.toString(); Log.trace("Result: ", result); return result; }