List of usage examples for java.lang Process getOutputStream
public abstract OutputStream getOutputStream();
From source file:org.wso2.emm.system.service.EMMSystemService.java
/** * Executing shell commands as super user. *///from ww w.j a v a 2s . c om private void executeShellCommand(String command) { Process process; try { process = Runtime.getRuntime().exec("sh"); DataOutputStream dataOutputStream = new DataOutputStream(process.getOutputStream()); dataOutputStream.writeBytes("am start " + command + "\\n"); dataOutputStream.writeBytes("exit\n"); dataOutputStream.flush(); } catch (IOException e) { Log.e(TAG, "Shell command execution failed." + e); } }
From source file:org.springframework.shell.commands.OsOperationsImpl.java
public void executeCommand(final String command) throws IOException { final File root = new File("."); final Process p = Runtime.getRuntime().exec(command, null, root); Reader input = new InputStreamReader(p.getInputStream()); Reader errors = new InputStreamReader(p.getErrorStream()); for (String line : IOUtils.readLines(input)) { if (line.startsWith("[ERROR]")) { LOGGER.severe(line);/*from w w w .jav a2 s . c om*/ } else if (line.startsWith("[WARNING]")) { LOGGER.warning(line); } else { LOGGER.info(line); } } for (String line : IOUtils.readLines(errors)) { if (line.startsWith("[ERROR]")) { LOGGER.severe(line); } else if (line.startsWith("[WARNING]")) { LOGGER.warning(line); } else { LOGGER.info(line); } } p.getOutputStream().close(); try { if (p.waitFor() != 0) { LOGGER.warning("The command '" + command + "' did not complete successfully"); } } catch (final InterruptedException e) { throw new IllegalStateException(e); } }
From source file:org.apache.tajo.cli.ExecExternalShellCommand.java
@Override public void invoke(String[] command) throws Exception { StringBuilder shellCommand = new StringBuilder(); String prefix = ""; for (int i = 1; i < command.length; i++) { shellCommand.append(prefix).append(command[i]); prefix = " "; }//from ww w.j a v a2 s.c o m String builtCommand = shellCommand.toString(); if (command.length < 2) { throw new IOException("ERROR: '" + builtCommand + "' is an invalid command."); } String[] execCommand = new String[3]; execCommand[0] = "/bin/bash"; execCommand[1] = "-c"; execCommand[2] = builtCommand; PrintWriter sout = context.getOutput(); CountDownLatch latch = new CountDownLatch(2); Process process = Runtime.getRuntime().exec(execCommand); try { InputStreamConsoleWriter inWriter = new InputStreamConsoleWriter(process.getInputStream(), sout, "", latch); InputStreamConsoleWriter errWriter = new InputStreamConsoleWriter(process.getErrorStream(), sout, "ERROR: ", latch); inWriter.start(); errWriter.start(); int processResult = process.waitFor(); latch.await(); if (processResult != 0) { throw new IOException("ERROR: Failed with exit code = " + processResult); } } finally { org.apache.commons.io.IOUtils.closeQuietly(process.getInputStream()); org.apache.commons.io.IOUtils.closeQuietly(process.getOutputStream()); org.apache.commons.io.IOUtils.closeQuietly(process.getErrorStream()); } }
From source file:org.apache.tajo.cli.tsql.commands.ExecExternalShellCommand.java
@Override public void invoke(String[] command) throws Exception { StringBuilder shellCommand = new StringBuilder(); String prefix = ""; for (int i = 1; i < command.length; i++) { shellCommand.append(prefix).append(command[i]); prefix = " "; }/*from w w w . j a v a2s. c om*/ String builtCommand = shellCommand.toString(); if (command.length < 2) { throw new IOException("ERROR: '" + builtCommand + "' is an invalid command."); } String[] execCommand = new String[3]; execCommand[0] = "/bin/bash"; execCommand[1] = "-c"; execCommand[2] = builtCommand; PrintWriter sout = context.getOutput(); PrintWriter serr = context.getError(); CountDownLatch latch = new CountDownLatch(2); Process process = Runtime.getRuntime().exec(execCommand); try { InputStreamConsoleWriter inWriter = new InputStreamConsoleWriter(process.getInputStream(), sout, "", latch); InputStreamConsoleWriter errWriter = new InputStreamConsoleWriter(process.getErrorStream(), serr, "ERROR: ", latch); inWriter.start(); errWriter.start(); int processResult = process.waitFor(); latch.await(); if (processResult != 0) { throw new IOException("ERROR: Failed with exit code = " + processResult); } } finally { org.apache.commons.io.IOUtils.closeQuietly(process.getInputStream()); org.apache.commons.io.IOUtils.closeQuietly(process.getOutputStream()); org.apache.commons.io.IOUtils.closeQuietly(process.getErrorStream()); } }
From source file:org.zeroturnaround.exec.ProcessExecutor.java
private WaitForProcess startInternal(Process process, ExecuteStreamHandler streams, ByteArrayOutputStream out) throws IOException { if (streams != null) { try {/*w w w . j a va2s. c o m*/ streams.setProcessInputStream(process.getOutputStream()); streams.setProcessOutputStream(process.getInputStream()); if (!builder.redirectErrorStream()) streams.setProcessErrorStream(process.getErrorStream()); } catch (IOException e) { process.destroy(); throw e; } streams.start(); } Set<Integer> exitValues = allowedExitValues == null ? null : new HashSet<Integer>(allowedExitValues); WaitForProcess result = new WaitForProcess(process, exitValues, streams, out, listeners.clone()); // Invoke listeners - changing this executor does not affect the started process any more listeners.afterStart(process, this); return result; }
From source file:org.sonatype.nexus.testsuite.obr.ObrITSupport.java
protected void deployUsingObrIntoFelix(final String repoId) throws Exception { final File felixHome = util.resolveFile("target/org.apache.felix.main.distribution-3.2.2"); final File felixRepo = util.resolveFile("target/felix-local-repository"); final File felixConfig = testData().resolveFile("felix.properties"); // ensure we have an obr.xml final Content content = content(); final Location obrLocation = new Location(repoId, ".meta/obr.xml"); content.download(obrLocation, new File(testIndex().getDirectory("downloads"), repoId + "-obr.xml")); FileUtils.deleteDirectory(new File(felixHome, "felix-cache")); FileUtils.deleteDirectory(new File(felixRepo, ".meta")); final ProcessBuilder pb = new ProcessBuilder("java", "-Dfelix.felix.properties=" + felixConfig.toURI(), "-jar", "bin/felix.jar"); pb.directory(felixHome);/*from w ww. ja va 2 s .com*/ pb.redirectErrorStream(true); final Process p = pb.start(); final Object lock = new Object(); final Thread t = new Thread(new Runnable() { public void run() { // just a safeguard, if felix get stuck kill everything try { synchronized (lock) { lock.wait(5 * 1000 * 60); } } catch (final InterruptedException e) { // ignore } p.destroy(); } }); t.setDaemon(true); t.start(); synchronized (lock) { final InputStream input = p.getInputStream(); final OutputStream output = p.getOutputStream(); waitFor(input, "g!"); output.write(("obr:repos add " + nexus().getUrl() + "content/" + obrLocation.toContentPath() + "\r\n") .getBytes()); output.flush(); waitFor(input, "g!"); output.write(("obr:repos remove http://felix.apache.org/obr/releases.xml\r\n").getBytes()); output.flush(); waitFor(input, "g!"); output.write(("obr:repos list\r\n").getBytes()); output.flush(); waitFor(input, "g!"); output.write("obr:deploy -s org.apache.felix.webconsole\r\n".getBytes()); output.flush(); waitFor(input, "done."); p.destroy(); lock.notifyAll(); } }
From source file:edu.stanford.epad.epadws.processing.pipeline.task.DicomHeadersTask.java
@Override public void run() { Thread.currentThread().setPriority(Thread.MIN_PRIORITY); // Let interactive thread run sooner FileWriter tagFileWriter = null; InputStream is = null;/* www. j a v a 2 s . c o m*/ InputStreamReader isr = null; BufferedReader br = null; Process process = null; try { String[] command = { "./dcm2txt", "-w", "250", "-l", "250", dicomInputFile.getAbsolutePath() }; ProcessBuilder processBuilder = new ProcessBuilder(command); String dicomBinDir = EPADConfig.getEPADWebServerDICOMScriptsDir() + "bin/"; File script = new File(dicomBinDir, "dcm2txt"); if (!script.exists()) dicomBinDir = EPADConfig.getEPADWebServerDICOMBinDir(); script = new File(dicomBinDir, "dcm2txt"); // Java 6 - Runtime.getRuntime().exec("chmod u+x "+script.getAbsolutePath()); script.setExecutable(true); processBuilder.directory(new File(dicomBinDir)); process = processBuilder.start(); process.getOutputStream(); is = process.getInputStream(); isr = new InputStreamReader(is); br = new BufferedReader(isr); String line; StringBuilder sb = new StringBuilder(); StringBuilder log = new StringBuilder(); while ((line = br.readLine()) != null) { sb.append(line).append("\n"); log.append("./dcm2txt: " + line).append("\n"); } try { process.waitFor(); } catch (InterruptedException e) { logger.info(log.toString()); logger.warning("Couldn't get tags for series " + seriesUID + "; dicom=" + dicomInputFile.getAbsolutePath() + " tagFile:" + outputFile.getAbsolutePath(), e); } EPADFileUtils.createDirsAndFile(outputFile); File tagFile = outputFile; tagFileWriter = new FileWriter(tagFile); tagFileWriter.write(sb.toString()); } catch (Exception e) { logger.warning("DicomHeadersTask failed to create DICOM tags for series " + seriesUID + " dicom FIle:" + dicomInputFile.getAbsolutePath() + " : " + outputFile.getAbsolutePath(), e); } catch (OutOfMemoryError oome) { logger.warning("DicomHeadersTask for series " + seriesUID + " out of memory: ", oome); } finally { IOUtils.closeQuietly(tagFileWriter); IOUtils.closeQuietly(br); if (process != null) process.destroy(); } }
From source file:org.moyrax.javascript.shell.Global.java
/** * If any of in, out, err is null, the corresponding process stream will be * closed immediately, otherwise it will be closed as soon as all data will be * read from/written to process//from w w w .jav a 2 s . c om */ private static int runProcess(String[] cmd, String[] environment, InputStream in, OutputStream out, OutputStream err) throws IOException { Process p; if (environment == null) { p = Runtime.getRuntime().exec(cmd); } else { p = Runtime.getRuntime().exec(cmd, environment); } PipeThread inThread = null, errThread = null; try { InputStream errProcess = null; try { if (err != null) { errProcess = p.getErrorStream(); } else { p.getErrorStream().close(); } InputStream outProcess = null; try { if (out != null) { outProcess = p.getInputStream(); } else { p.getInputStream().close(); } OutputStream inProcess = null; try { if (in != null) { inProcess = p.getOutputStream(); } else { p.getOutputStream().close(); } if (out != null) { // Read process output on this thread if (err != null) { errThread = new PipeThread(true, errProcess, err); errThread.start(); } if (in != null) { inThread = new PipeThread(false, in, inProcess); inThread.start(); } pipe(true, outProcess, out); } else if (in != null) { // No output, read process input on this thread if (err != null) { errThread = new PipeThread(true, errProcess, err); errThread.start(); } pipe(false, in, inProcess); in.close(); } else if (err != null) { // No output or input, read process err // on this thread pipe(true, errProcess, err); errProcess.close(); errProcess = null; } // wait for process completion for (;;) { try { p.waitFor(); break; } catch (InterruptedException ex) { } } return p.exitValue(); } finally { // pipe will close stream as well, but for reliability // duplicate it in any case if (inProcess != null) { inProcess.close(); } } } finally { if (outProcess != null) { outProcess.close(); } } } finally { if (errProcess != null) { errProcess.close(); } } } finally { p.destroy(); if (inThread != null) { for (;;) { try { inThread.join(); break; } catch (InterruptedException ex) { } } } if (errThread != null) { for (;;) { try { errThread.join(); break; } catch (InterruptedException ex) { } } } } }
From source file:org.openiam.spml2.spi.example.ShellConnectorImpl.java
public ResponseType delete(DeleteRequestType reqType) { System.out.println("Delete called.."); String userName = null;/*from ww w. ja va2s . c o m*/ String requestID = reqType.getRequestID(); /* PSO - Provisioning Service Object - * - ID must uniquely specify an object on the target or in the target's namespace * - Try to make the PSO ID immutable so that there is consistency across changes. */ PSOIdentifierType psoID = reqType.getPsoID(); userName = psoID.getID(); /* targetID - */ String targetID = psoID.getTargetID(); /* ContainerID - May specify the container in which this object should be created * ie. ou=Development, org=Example */ PSOIdentifierType containerID = psoID.getContainerID(); /* A) Use the targetID to look up the connection information under managed systems */ ManagedSys managedSys = managedSysService.getManagedSys(targetID); String host; String hostlogin; String hostpassword; host = managedSys.getHostUrl(); hostlogin = managedSys.getUserId(); hostpassword = managedSys.getDecryptPassword(); //powershell.exe -command "& C:\appserver\apache-tomcat-6.0.26\powershell\delete.ps1 principalName" StringBuffer strBuf = new StringBuffer(); strBuf.append("cmd /c powershell.exe -command \"& C:\\powershell\\ad\\Del-AdUser.ps1 "); strBuf.append("'" + host + "' "); strBuf.append("'" + userName + "' \" "); System.out.println("**Command line string= " + strBuf.toString()); try { //Runtime.getRuntime().exec(cmdarray); //exec(strBuf.toString()); Process p = Runtime.getRuntime().exec(strBuf.toString()); System.out.println("Process =" + p); OutputStream stream = p.getOutputStream(); System.out.println("stream=" + stream.toString()); } catch (Exception e) { e.printStackTrace(); } ResponseType respType = new ResponseType(); respType.setStatus(StatusCodeType.SUCCESS); return respType; }
From source file:org.openiam.spml2.spi.example.ShellConnectorImpl.java
public ResponseType setPassword(SetPasswordRequestType reqType) { log.debug("setPassword request called.."); String userName;/* w w w . j ava 2s .c o m*/ String requestID = reqType.getRequestID(); /* PSO - Provisioning Service Object - * - ID must uniquely specify an object on the target or in the target's namespace * - Try to make the PSO ID immutable so that there is consistency across changes. */ PSOIdentifierType psoID = reqType.getPsoID(); userName = psoID.getID(); /* targetID - */ String targetID = psoID.getTargetID(); /* ContainerID - May specify the container in which this object should be created * ie. ou=Development, org=Example */ PSOIdentifierType containerID = psoID.getContainerID(); /* A) Use the targetID to look up the connection information under managed systems */ ManagedSys managedSys = managedSysService.getManagedSys(targetID); String host; String hostlogin; String hostpassword; host = managedSys.getHostUrl(); hostlogin = managedSys.getUserId(); hostpassword = managedSys.getDecryptPassword(); StringBuffer strBuf = new StringBuffer(); strBuf.append("cmd /c powershell.exe -command \"& C:\\powershell\\ad\\SetPassword-UserActiveDir.ps1 "); strBuf.append("'" + host + "' "); strBuf.append("'" + hostlogin + "' "); strBuf.append("'" + hostpassword + "' "); strBuf.append("'" + userName + "' "); strBuf.append("'" + reqType.getPassword() + "' \" "); System.out.println("Command line string= " + strBuf.toString()); String[] cmdarray = { "cmd", strBuf.toString() }; try { //Runtime.getRuntime().exec(cmdarray); //exec(strBuf.toString()); Process p = Runtime.getRuntime().exec(strBuf.toString()); System.out.println("Process =" + p); OutputStream stream = p.getOutputStream(); System.out.println("stream=" + stream.toString()); } catch (Exception e) { e.printStackTrace(); } ResponseType respType = new ResponseType(); respType.setStatus(StatusCodeType.SUCCESS); return respType; }