List of usage examples for java.lang Process getOutputStream
public abstract OutputStream getOutputStream();
From source file:com.att.android.arodatacollector.main.AROCollectorService.java
/** * This method creates a SU enabled shell Sets the execute permission for * tcpdump and key.db Starts the tcpdump on Completion or abnormal * termination of tcpdump Shell is destroyed * /*from w w w .jav a 2s . c o m*/ * @throws IOException * @throws InterruptedException */ private void startTcpDump() throws IOException, InterruptedException { Log.d(TAG, "inside startTcpDump at timestamp " + System.currentTimeMillis()); Process sh = null; DataOutputStream os = null; int shExitValue = 0; try { startCalTime = Calendar.getInstance(); if (!AROCollectorUtils.isTcpDumpRunning()) { //only start tcpdump if it's not already running, to handle the case where the background //service was stopped and now restarting Log.i(TAG, "tcpdump is not running. Starting tcpdump in the shell now"); sh = Runtime.getRuntime().exec("su"); os = new DataOutputStream(sh.getOutputStream()); String Command = "chmod 777 " + ARODataCollector.INTERNAL_DATA_PATH + TCPDUMPFILENAME + "\n"; os.writeBytes(Command); Command = "chmod 777 " + ARODataCollector.INTERNAL_DATA_PATH + "key.db" + "\n"; os.writeBytes(Command); //flurry timed event duration mApp.writeToFlurryAndLogEvent(flurryTimedEvent, "Flurry trace start", startCalTime.getTime().toString(), "Trace Duration", true); /*Command = "." + ARODataCollector.INTERNAL_DATA_PATH + TCPDUMPFILENAME + " -w " + TRACE_FOLDERNAME + "\n";*/ Command = "." + ARODataCollector.INTERNAL_DATA_PATH + TCPDUMPFILENAME + " -i any -w " + TRACE_FOLDERNAME + "\n"; os.writeBytes(Command); Command = "exit\n"; os.writeBytes(Command); os.flush(); StreamClearer stdoutClearer = new StreamClearer(sh.getInputStream(), "stdout", true); new Thread(stdoutClearer).start(); StreamClearer stderrClearer = new StreamClearer(sh.getErrorStream(), "stderr", true); new Thread(stderrClearer).start(); shExitValue = sh.waitFor(); if (DEBUG) { Log.i(TAG, "tcpdump waitFor returns exit value: " + shExitValue + " at " + System.currentTimeMillis()); } } else { Log.i(TAG, "timestamp " + System.currentTimeMillis() + ": tcpdump is already running"); } //We will continue and block the thread untill we see valid instance of tcpdump running in shell //waitFor() does not seems to be working on ICS firmware while (AROCollectorUtils.isTcpDumpRunning()) { continue; } if (DEBUG) { Log.d(TAG, "tcpdump process exit value: " + shExitValue); Log.i(TAG, "Coming out of startTcpDump at " + System.currentTimeMillis()); logTcpdumpPid(); } // Stopping the Video capture right after tcpdump coming out of // shell new Thread(new Runnable() { @Override public void run() { if (mVideoRecording && mApp.getAROVideoCaptureRunningFlag()) { stopScreenVideoCapture(); stopDmesg(); } } }).start(); final Calendar endCalTime = Calendar.getInstance(); FlurryAgent.endTimedEvent("Trace Duration"); mApp.writeToFlurry(flurryTimedEvent, "Flurry trace end", endCalTime.getTime().toString(), "flurryTimedEvent", AROCollectorUtils.NOT_APPLICABLE, AROCollectorUtils.EMPTY_STRING); mApp.writeToFlurry(flurryTimedEvent, "calculated Flurry trace duration", getUpTime(endCalTime), "flurryTimedEvent", AROCollectorUtils.NOT_APPLICABLE, AROCollectorUtils.EMPTY_STRING); logFlurryEvents(); DataCollectorTraceStop(); } finally { try { mApp.setTcpDumpStartFlag(false); if (os != null) { os.close(); } if (sh != null) { sh.destroy(); } } catch (Exception e) { Log.e(TAG, "exception in startTcpDump DataOutputStream close", e); } } }
From source file:com.att.android.arodatacollector.main.AROCollectorService.java
/** * Stops the Screen video capture/*w w w. j av a 2s. co m*/ */ private void stopScreenVideoCapture() { Log.i(TAG, "enter stopScreenVideoCapture at " + System.currentTimeMillis()); Process sh = null; DataOutputStream os = null; int pid = 0, exitValue = -1; try { pid = mAroUtils.getProcessID("ffmpeg"); } catch (IOException e1) { Log.e(TAG, "IOException in stopScreenVideoCapture", e1); } catch (InterruptedException e1) { Log.e(TAG, "exception in stopScreenVideoCapture", e1); } if (DEBUG) { Log.i(TAG, "stopScreenVideoCapture=" + pid); } if (pid != 0) { try { sh = Runtime.getRuntime().exec("su"); os = new DataOutputStream(sh.getOutputStream()); String command = "kill -15 " + pid + "\n"; os.writeBytes(command); command = "exit\n"; os.writeBytes(command); os.flush(); //clear the streams so that it doesnt block the process //sh.inputStream is actually the output from the process StreamClearer stdoutClearer = new StreamClearer(sh.getInputStream(), "stdout", false); new Thread(stdoutClearer).start(); StreamClearer stderrClearer = new StreamClearer(sh.getErrorStream(), "stderr", true); new Thread(stderrClearer).start(); exitValue = sh.waitFor(); if (exitValue == 0) { mVideoRecording = false; } if (DEBUG) { Log.i(TAG, "successfully returned from kill -15; exitValue= " + exitValue); } } catch (IOException e) { Log.e(TAG, "exception in stopScreenVideoCapture", e); } catch (InterruptedException e) { Log.e(TAG, "exception in stopScreenVideoCapture", e); } finally { try { kill9Ffmpeg(); if (os != null) { os.close(); } if (sh != null) { sh.destroy(); } } catch (Exception e) { Log.e(TAG, "exception in stopScreenVideoCapture finally block", e); } if (DEBUG) { Log.i(TAG, "Stopped Video Capture in stopScreenVideoCapture()"); } } } if (DEBUG) { Log.i(TAG, "exit stopScreenVideoCapture"); } }
From source file:org.kepler.ssh.LocalExec.java
public int executeCmd(String command, OutputStream streamOut, OutputStream streamErr, String thirdPartyTarget) throws ExecException { _commandArr[_commandCount] = command; Runtime rt = Runtime.getRuntime(); Process proc; // get the pwd/passphrase to the third party (and perform authentication // if not yet done) String pwd = SshSession.getPwdToThirdParty(thirdPartyTarget); try {//from www . j a v a 2s . c o m proc = rt.exec(_commandArr); } catch (Exception ex) { //ex.printStackTrace(); throw new ExecException("Cannot execute cmd ** : " + _commandArr[_commandCount] + ex); } // System.out.println("%%% Process started"); // the streams from the process: stdout and stderr BufferedReader out_in = new BufferedReader(new InputStreamReader(proc.getInputStream())); // stdout BufferedReader err_in = new BufferedReader(new InputStreamReader(proc.getErrorStream())); // stderr // the streams towards the caller: stdout and stderr BufferedWriter out_out = new BufferedWriter(new OutputStreamWriter(streamOut)); BufferedWriter err_out = new BufferedWriter(new OutputStreamWriter(streamErr)); BufferedWriter proc_in = new BufferedWriter(new OutputStreamWriter(proc.getOutputStream())); // stdin String line; // Temp for each line of output. int exitVal = -32766; boolean readOut = true; boolean readErr = true; boolean finished = false; boolean checkForPwd = (pwd != null); char c[] = new char[256]; int charsRead; // variables for the timeout checking long start = System.currentTimeMillis(); long current = 0; long maxtime = timeout * 1000L; while (!finished) { // will stop when the process terminates or after // timeout // check the status of the process try { exitVal = proc.exitValue(); finished = true; // process terminated so exit this loop after // reading the buffers } catch (IllegalThreadStateException ex) { // process not yet terminated so we go further } // read stdout if (readOut) { try { while (out_in.ready()) { charsRead = out_in.read(c, 0, 256); out_out.write(c, 0, charsRead); // System.out.println("%%% "+ new String(c, 0, // charsRead)); /* * try { proc_in.write("Anyadat\n", 0, 8); // send the * password proc_in.flush(); } catch (Exception ex) { * System.out.println("### "+ex); * * } */ if (checkForPwd && containsPasswordRequest(c, 0, charsRead)) { // System.out.println("%%% Found password request"); out_out.flush(); // so you may see the request on // stdout already proc_in.write(pwd + "\n", 0, pwd.length() + 1); // send // the // password proc_in.flush(); log.info("Sent password to third party."); checkForPwd = false; // even if it's wrong, do not // do it again } if (timeoutRestartOnStdout) start = System.currentTimeMillis(); // restart // timeout timer } } catch (IOException ioe) { log.error("<IOException> when reading the stdout: " + ioe + "</IOException>"); readOut = false; } } // read stderr if (readErr) { try { while (err_in.ready()) { charsRead = err_in.read(c, 0, 256); err_out.write(c, 0, charsRead); System.out.println("### " + new String(c, 0, charsRead)); if (checkForPwd && containsPasswordRequest(c, 0, charsRead)) { System.out.println("### Found password request"); out_out.flush(); // so you may see the request on // stdout already proc_in.write(pwd + "\n", 0, pwd.length() + 1); // send // the // password proc_in.flush(); log.info("Sent password to third party."); checkForPwd = false; // even if it's wrong, do not // do it again } if (timeoutRestartOnStderr) start = System.currentTimeMillis(); // restart // timeout timer } } catch (IOException ioe) { log.error("<IOException> when reading the stderr: " + ioe + "</IOException>"); readErr = false; } } // sleep a bit to not overload the system if (!finished) try { java.lang.Thread.sleep(100); } catch (InterruptedException ex) { } // check timeout current = System.currentTimeMillis(); if (timeout > 0 && maxtime < current - start) { log.error("Timeout: " + timeout + "s elapsed for command " + command); proc.destroy(); throw new ExecTimeoutException(command); // exitVal = timeoutErrorCode; // finished = true; } } try { // flush to caller out_out.flush(); err_out.flush(); // close streams from/to child process out_in.close(); err_in.close(); proc_in.close(); } catch (IOException ex) { log.error("Could not flush output streams: " + ex); } // System.out.println("ExitValue: " + exitVal); return exitVal; }
From source file:ch.kostceco.tools.siardexcerpt.excerption.moduleexcerpt.impl.ExcerptCGrepModuleImpl.java
@Override public boolean validate(File siardDatei, File outFile, String excerptString) throws ExcerptCGrepException { // Ausgabe -> Ersichtlich das SIARDexcerpt arbeitet int onWork = 41; boolean isValid = true; File fGrepExe = new File("resources" + File.separator + "grep" + File.separator + "grep.exe"); String pathToGrepExe = fGrepExe.getAbsolutePath(); if (!fGrepExe.exists()) { // grep.exe existiert nicht --> Abbruch getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C) + getTextResourceService().getText(ERROR_XML_C_MISSINGFILE, fGrepExe.getAbsolutePath())); return false; } else {/*from w ww. j a v a2 s .c om*/ File fMsys10dll = new File("resources" + File.separator + "grep" + File.separator + "msys-1.0.dll"); if (!fMsys10dll.exists()) { // msys-1.0.dll existiert nicht --> Abbruch getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C) + getTextResourceService().getText(ERROR_XML_C_MISSINGFILE, fMsys10dll.getAbsolutePath())); return false; } } File tempOutFile = new File(outFile.getAbsolutePath() + ".tmp"); String content = ""; // Record aus Maintable herausholen try { if (tempOutFile.exists()) { Util.deleteDir(tempOutFile); } /* Nicht vergessen in "src/main/resources/config/applicationContext-services.xml" beim * entsprechenden Modul die property anzugeben: <property name="configurationService" * ref="configurationService" /> */ String name = getConfigurationService().getMaintableName(); String folder = getConfigurationService().getMaintableFolder(); String cell = getConfigurationService().getMaintablePrimarykeyCell(); File fMaintable = new File(siardDatei.getAbsolutePath() + File.separator + "content" + File.separator + "schema0" + File.separator + folder + File.separator + folder + ".xml"); try { // grep "<c11>7561234567890</c11>" table13.xml >> output.txt String command = "cmd /c \"" + pathToGrepExe + " \"<" + cell + ">" + excerptString + "</" + cell + ">\" " + fMaintable.getAbsolutePath() + " >> " + tempOutFile.getAbsolutePath() + "\""; /* Das redirect Zeichen verunmglicht eine direkte eingabe. mit dem geschachtellten Befehl * gehts: cmd /c\"urspruenlicher Befehl\" */ // System.out.println( command ); Process proc = null; Runtime rt = null; getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_ELEMENT_OPEN, name)); try { Util.switchOffConsole(); rt = Runtime.getRuntime(); proc = rt.exec(command.toString().split(" ")); // .split(" ") ist notwendig wenn in einem Pfad ein Doppelleerschlag vorhanden ist! // Fehleroutput holen StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR"); // Output holen StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT"); // Threads starten errorGobbler.start(); outputGobbler.start(); // Warte, bis wget fertig ist proc.waitFor(); Util.switchOnConsole(); } catch (Exception e) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C) + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage())); return false; } finally { if (proc != null) { closeQuietly(proc.getOutputStream()); closeQuietly(proc.getInputStream()); closeQuietly(proc.getErrorStream()); } } Scanner scanner = new Scanner(tempOutFile); content = ""; try { content = scanner.useDelimiter("\\Z").next(); } catch (Exception e) { // Grep ergab kein treffer Content Null content = ""; } scanner.close(); getMessageService() .logError(getTextResourceService().getText(MESSAGE_XML_ELEMENT_CONTENT, content)); getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_ELEMENT_CLOSE, name)); if (tempOutFile.exists()) { Util.deleteDir(tempOutFile); } content = ""; // Ende Grep } catch (Exception e) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C) + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage())); return false; } } catch (Exception e) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C) + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage())); return false; } // Ende MainTable // grep der SubTables try { String name = null; String folder = null; String cell = null; InputStream fin = new FileInputStream( new File("configuration" + File.separator + "SIARDexcerpt.conf.xml")); SAXBuilder builder = new SAXBuilder(); Document document = builder.build(fin); fin.close(); /* read the document and for each subTable */ Namespace ns = Namespace.getNamespace(""); // select schema elements and loop List<Element> subtables = document.getRootElement().getChild("subtables", ns).getChildren("subtable", ns); for (Element subtable : subtables) { name = subtable.getChild("name", ns).getText(); folder = subtable.getChild("folder", ns).getText(); cell = subtable.getChild("foreignkeycell", ns).getText(); // System.out.println( name + " - " + folder + " - " + cell ); File fSubtable = new File(siardDatei.getAbsolutePath() + File.separator + "content" + File.separator + "schema0" + File.separator + folder + File.separator + folder + ".xml"); try { // grep "<c11>7561234567890</c11>" table13.xml >> output.txt String command = "cmd /c \"" + pathToGrepExe + " \"<" + cell + ">" + excerptString + "</" + cell + ">\" " + fSubtable.getAbsolutePath() + " >> " + tempOutFile.getAbsolutePath() + "\""; /* Das redirect Zeichen verunmglicht eine direkte eingabe. mit dem geschachtellten Befehl * gehts: cmd /c\"urspruenlicher Befehl\" */ // System.out.println( command ); Process proc = null; Runtime rt = null; getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_ELEMENT_OPEN, name)); try { Util.switchOffConsole(); rt = Runtime.getRuntime(); proc = rt.exec(command.toString().split(" ")); // .split(" ") ist notwendig wenn in einem Pfad ein Doppelleerschlag vorhanden ist! // Fehleroutput holen StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR"); // Output holen StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT"); // Threads starten errorGobbler.start(); outputGobbler.start(); // Warte, bis wget fertig ist proc.waitFor(); Util.switchOnConsole(); } catch (Exception e) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C) + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage())); return false; } finally { if (proc != null) { closeQuietly(proc.getOutputStream()); closeQuietly(proc.getInputStream()); closeQuietly(proc.getErrorStream()); } } Scanner scanner = new Scanner(tempOutFile); content = ""; try { content = scanner.useDelimiter("\\Z").next(); } catch (Exception e) { // Grep ergab kein treffer Content Null content = ""; } scanner.close(); getMessageService() .logError(getTextResourceService().getText(MESSAGE_XML_ELEMENT_CONTENT, content)); getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_ELEMENT_CLOSE, name)); if (tempOutFile.exists()) { Util.deleteDir(tempOutFile); } content = ""; // Ende Grep } catch (Exception e) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C) + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage())); return false; } // Ende SubTables if (onWork == 41) { onWork = 2; System.out.print("- "); System.out.print("\r"); } else if (onWork == 11) { onWork = 12; System.out.print("\\ "); System.out.print("\r"); } else if (onWork == 21) { onWork = 22; System.out.print("| "); System.out.print("\r"); } else if (onWork == 31) { onWork = 32; System.out.print("/ "); System.out.print("\r"); } else { onWork = onWork + 1; } } System.out.print(" "); System.out.print("\r"); } catch (Exception e) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C) + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage())); return false; } return isValid; }
From source file:com.att.android.arodatacollector.main.AROCollectorService.java
/** * Stops collecting kernel log/*from ww w.j a v a2 s. c om*/ * * Requires root permission. * * pre: there is only one "cat" process running */ private void stopDmesg() { Process sh = null; DataOutputStream os = null; int pid = 0; try { pid = mAroUtils.getProcessID("cat"); } catch (IOException e1) { Log.e(TAG, "IOException in stopDmesg", e1); } catch (IndexOutOfBoundsException e1) { Log.e(TAG, "IndexOutOfBoundsException in stopDmesg", e1); } catch (InterruptedException e1) { Log.e(TAG, "exception in stopDmesg", e1); } if (DEBUG) { Log.d(TAG, "stopDmesg=" + pid); } if (pid != 0) { try { sh = Runtime.getRuntime().exec("su"); os = new DataOutputStream(sh.getOutputStream()); final String Command = "kill -15 " + pid + "\n"; os.writeBytes(Command); os.flush(); sh.waitFor(); } catch (IOException e) { Log.e(TAG, "exception in stopDmesg", e); } catch (InterruptedException e) { Log.e(TAG, "exception in stopDmesg", e); } finally { try { os.close(); } catch (IOException e) { Log.e(TAG, "exception in stopDmesg DataOutputStream close", e); } if (DEBUG) { Log.d(TAG, "Stopped stopDmesg"); } sh.destroy(); } } }
From source file:org.pshdl.model.simulation.codegenerator.CCodeGenerator.java
public IHDLInterpreterFactory<NativeRunner> createInterpreter(final File tempDir) { try {//from w w w .ja va 2s . com final File testCFile = new File(tempDir, "test.c"); String _generateMainCode = this.generateMainCode(); Files.write(_generateMainCode, testCFile, StandardCharsets.UTF_8); final File testRunner = new File(tempDir, "runner.c"); final InputStream runnerStream = CCodeGenerator.class .getResourceAsStream("/org/pshdl/model/simulation/includes/runner.c"); final FileOutputStream fos = new FileOutputStream(testRunner); try { ByteStreams.copy(runnerStream, fos); } finally { runnerStream.close(); fos.close(); } final File executable = new File(tempDir, "testExec"); this.writeAuxiliaryContents(tempDir); String _absolutePath = tempDir.getAbsolutePath(); String _absolutePath_1 = testCFile.getAbsolutePath(); String _absolutePath_2 = testRunner.getAbsolutePath(); String _absolutePath_3 = executable.getAbsolutePath(); final ProcessBuilder builder = new ProcessBuilder(CCodeGenerator.COMPILER, "-I", _absolutePath, "-O3", _absolutePath_1, _absolutePath_2, "-o", _absolutePath_3); ProcessBuilder _directory = builder.directory(tempDir); ProcessBuilder _inheritIO = _directory.inheritIO(); final Process process = _inheritIO.start(); process.waitFor(); int _exitValue = process.exitValue(); boolean _notEquals = (_exitValue != 0); if (_notEquals) { throw new RuntimeException("Process did not terminate with 0"); } return new IHDLInterpreterFactory<NativeRunner>() { public NativeRunner newInstance() { try { String _absolutePath = executable.getAbsolutePath(); final ProcessBuilder execBuilder = new ProcessBuilder(_absolutePath); ProcessBuilder _directory = execBuilder.directory(tempDir); ProcessBuilder _redirectErrorStream = _directory.redirectErrorStream(true); final Process testExec = _redirectErrorStream.start(); InputStream _inputStream = testExec.getInputStream(); OutputStream _outputStream = testExec.getOutputStream(); String _absolutePath_1 = executable.getAbsolutePath(); return new NativeRunner(_inputStream, _outputStream, CCodeGenerator.this.em, testExec, 5, _absolutePath_1); } catch (Throwable _e) { throw Exceptions.sneakyThrow(_e); } } }; } catch (Throwable _e) { throw Exceptions.sneakyThrow(_e); } }
From source file:Install.java
private void printExecutionOutput(Process p, boolean showCmdOutput, boolean showError, boolean showUIOutput) throws IOException { try {/*from w w w . j a v a 2 s . c o m*/ BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream())); BufferedReader sin = new BufferedReader(new InputStreamReader(p.getErrorStream())); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(p.getOutputStream())); String line; // note for future modification: // handling stdout and stderr this way might block...this should // be handled with separate threads to process stdout and stderr while ((line = in.readLine()) != null) { if (showCmdOutput) { System.out.println(line); } else if (showUIOutput) { fireActionEvent(line); } } // print out all the stderr that happened while ((line = sin.readLine()) != null) { if (showError) { System.out.println(line); } } in.close(); sin.close(); out.close(); } catch (IOException e) { System.out.println("Error executing system command."); throw e; } }
From source file:org.openbi.kettle.plugins.refreshtableauextract.RefreshTableauExtract.java
public Result execute(Result previousResult, int nr) throws KettleException { Result result = previousResult; result.setResult(validate());//from www.j a v a 2 s . c o m if (!result.getResult()) { return result; } String[] commands; String tableauCommand = getRealValue(getTableauClient()).trim(); if (tableauCommand.toLowerCase().endsWith(".exe")) { tableauCommand = tableauCommand.substring(0, tableauCommand.length() - 4); } tableauCommand = "\"" + tableauCommand + "\""; if (getRefreshType() == 0 || getRefreshType() == 1) { tableauCommand += " refreshextract"; } else if (getRefreshType() == 2) { tableauCommand += " addfiletoextract"; } else { logError(BaseMessages.getString(PKG, "RefreshTableauExtract.Error.InvalidRefreshType")); result.setResult(false); return result; } tableauCommand += " --server " + protocolList[getProtocol()] + "://" + getRealValue(getServer()); if (getRealValue(getServerPort()) != null && !getRealValue(getServerPort()).isEmpty()) { tableauCommand += ":" + getRealValue(getServerPort()); } tableauCommand += " --username " + getRealValue(getServerUser()); tableauCommand += " --password " + getRealValue(getServerPassword()); tableauCommand += " --datasource \"" + getRealValue(getDataSource()) + "\""; if (getRealValue(getSiteName()) != null && !getRealValue(getSiteName()).isEmpty()) { tableauCommand += " --site \"" + getRealValue(getSiteName()) + "\""; } if (getRealValue(getProject()) != null && !getRealValue(getProject()).isEmpty()) { tableauCommand += " --project \"" + getRealValue(getProject()) + "\""; } if (getRealValue(getProxyUser()) != null && !getRealValue(getProxyUser()).isEmpty()) { tableauCommand += " --proxy-username " + getRealValue(getProxyUser()); } if (getRealValue(getProxyPassword()) != null && !getRealValue(getProxyPassword()).isEmpty()) { tableauCommand += " --proxy-password " + getRealValue(getProxyPassword()); } if (getRefreshType() == 0) { commands = new String[1]; tableauCommand += " --original-file \"" + getRealValue(getExtractFile()) + "\""; commands[0] = new String(tableauCommand); } else if (getRefreshType() == 1) { commands = new String[1]; if (getFullRefresh()) { tableauCommand += " --force-full-refresh"; } if (getRealValue(getSourceUser()) != null && !getRealValue(getSourceUser()).isEmpty()) { tableauCommand += " --source-username " + getRealValue(getSourceUser()); } if (getRealValue(getSourcePassword()) != null & !getRealValue(getSourcePassword()).isEmpty()) { tableauCommand += " --source-password " + getRealValue(getSourcePassword()); } commands[0] = new String(tableauCommand); } else { String[] fileStrings = null; if (processResultFiles) { if (result != null && previousResult.getResultFiles().size() > 0) { int size = previousResult.getResultFiles().size(); if (log.isBasic()) { logBasic(BaseMessages.getString(PKG, "RefreshTableauExtract.FilesFound", "" + size)); } try { List<ResultFile> resultFiles = previousResult.getResultFilesList(); List<String> files = new ArrayList<String>(); Iterator<ResultFile> it = resultFiles.iterator(); while (it.hasNext()) { ResultFile f = it.next(); FileObject o = f.getFile(); if (o.getType().equals(FileType.FILE)) { if (o.exists()) { files.add(o.getName().toString().startsWith("file:///") ? o.getName().toString().substring(8) : o.getName().toString()); } else { logBasic(BaseMessages.getString(PKG, "RefreshTableauExtract.FileNotExist", "" + o.getName())); } } else { logBasic(BaseMessages.getString(PKG, "RefreshTableauExtract.ResultNotFile", "" + o.getName())); } } if (files.size() > 0) { Iterator<String> ite = files.iterator(); fileStrings = new String[files.size()]; int i = 0; while (ite.hasNext()) { fileStrings[i] = ite.next(); i++; } } else { logBasic(BaseMessages.getString(PKG, "RefreshTableauExtract.NoFilesOnResult")); result.setResult(true); return result; } } catch (Exception ex) { logError(ex.toString()); result.setResult(false); return result; } } else { logBasic(BaseMessages.getString(PKG, "RefreshTableauExtract.NoFilesOnResult")); result.setResult(true); return result; } } else { // Get source and destination files, also wildcard String[] vFilePaths = filePaths; String[] vWildcards = wildcards; boolean[] includeSubfolders = new boolean[vFilePaths.length]; String[] fileRequired = new String[vFilePaths.length]; for (int i = 0; i < includeSubfolders.length; i++) { includeSubfolders[i] = false; } FileInputList files = FileInputList.createFileList(this, vFilePaths, vWildcards, fileRequired, includeSubfolders); fileStrings = new String[files.getFileStrings().length]; fileStrings = files.getFileStrings(); } commands = new String[fileStrings.length]; for (int i = 0; i < fileStrings.length; i++) { commands[i] = new String(tableauCommand + " --file \"" + fileStrings[i] + "\""); } } FileObject fileObject = null; String realScript = ""; FileObject tempFile = null; for (int i = 0; i < commands.length; i++) { // realScript+="echo Running: "+commands[i]+"\n"; realScript += commands[i] + "\n"; if (log.isDetailed()) { logDetailed(BaseMessages.getString(PKG, "RefreshTableauExtract.Commands", commands[i])); } } try { // What's the exact command? String[] command; if (log.isBasic()) { logBasic(BaseMessages.getString(PKG, "RefreshTableuaExtract.RunningOn", Const.getOS())); } if (Const.getOS().equals("Windows 95")) { //base = new String[] { "command.com", "/C" }; tempFile = KettleVFS.createTempFile("kettle", "shell.bat", null, this); fileObject = createTemporaryShellFile(tempFile, realScript); command = new String[] { "command.com", "/C", "\"" + Const.optionallyQuoteStringByOS(KettleVFS.getFilename(fileObject)) + "\"" }; } else if (Const.getOS().startsWith("Windows")) { //base = new String[] { "cmd.exe", "/C" }; tempFile = KettleVFS.createTempFile("kettle", "shell.bat", null, this); fileObject = createTemporaryShellFile(tempFile, realScript); command = new String[] { "cmd.exe", "/C", "\"" + Const.optionallyQuoteStringByOS(KettleVFS.getFilename(fileObject)) + "\"" }; } else { tempFile = KettleVFS.createTempFile("kettle", "shell", null, this); fileObject = createTemporaryShellFile(tempFile, realScript); command = new String[] { Const.optionallyQuoteStringByOS(KettleVFS.getFilename(fileObject)) }; } ProcessBuilder pb = new ProcessBuilder(command); Map<String, String> env = pb.environment(); String[] variables = listVariables(); for (int i = 0; i < variables.length; i++) { env.put(variables[i], getVariable(variables[i])); } if (getWorkingDirectory() != null && !Const.isEmpty(Const.rtrim(getRealValue(getWorkingDirectory())))) { String vfsFilename = environmentSubstitute(getRealValue(getWorkingDirectory())); File file = new File(KettleVFS.getFilename(KettleVFS.getFileObject(vfsFilename, this))); pb.directory(file); } if (log.isDetailed()) { logDetailed(BaseMessages.getString(PKG, "RefreshTableauExtract.CommandStarted")); } Process proc = pb.start(); // any error message? StreamLogger errorLogger = new StreamLogger(log, proc.getErrorStream(), "(stderr)"); // any output? StreamLogger outputLogger = new StreamLogger(log, proc.getInputStream(), "(stdout)"); // kick them off new Thread(errorLogger).start(); new Thread(outputLogger).start(); proc.waitFor(); if (log.isDetailed()) { logDetailed(BaseMessages.getString(PKG, "RefreshTableauExtract.CommandFinished")); } // What's the exit status? result.setExitStatus(proc.exitValue()); if (result.getExitStatus() != 0) { logError(BaseMessages.getString(PKG, "RefreshTableauExtract.ExitStatus", "" + result.getExitStatus())); result.setResult(false); } // close the streams // otherwise you get "Too many open files, java.io.IOException" after a lot of iterations proc.getErrorStream().close(); proc.getOutputStream().close(); } catch (Exception ex) { logError(ex.toString()); result.setResult(false); } finally { // If we created a temporary file, remove it... // if (tempFile != null) { try { tempFile.delete(); } catch (Exception e) { BaseMessages.getString(PKG, "RefreshTableauExtract.UnexpectedError", tempFile.toString(), e.toString()); } } } return result; }
From source file:org.pentaho.di.job.entries.shell.JobEntryShell.java
private void executeShell(Result result, List<RowMetaAndData> cmdRows, String[] args) { FileObject fileObject = null; String realScript = null;/*from w w w . j a va2s. c o m*/ FileObject tempFile = null; try { // What's the exact command? String[] base = null; List<String> cmds = new ArrayList<String>(); if (log.isBasic()) { logBasic(BaseMessages.getString(PKG, "JobShell.RunningOn", Const.getOS())); } if (insertScript) { realScript = environmentSubstitute(script); } else { String realFilename = environmentSubstitute(getFilename()); fileObject = KettleVFS.getFileObject(realFilename, this); } if (Const.getOS().equals("Windows 95")) { base = new String[] { "command.com", "/C" }; if (insertScript) { tempFile = KettleVFS.createTempFile("kettle", "shell.bat", environmentSubstitute(workDirectory), this); fileObject = createTemporaryShellFile(tempFile, realScript); } } else if (Const.getOS().startsWith("Windows")) { base = new String[] { "cmd.exe", "/C" }; if (insertScript) { tempFile = KettleVFS.createTempFile("kettle", "shell.bat", environmentSubstitute(workDirectory), this); fileObject = createTemporaryShellFile(tempFile, realScript); } } else { if (insertScript) { tempFile = KettleVFS.createTempFile("kettle", "shell", environmentSubstitute(workDirectory), this); fileObject = createTemporaryShellFile(tempFile, realScript); } base = new String[] { KettleVFS.getFilename(fileObject) }; } // Construct the arguments... if (argFromPrevious && cmdRows != null) { // Add the base command... for (int i = 0; i < base.length; i++) { cmds.add(base[i]); } if (Const.getOS().equals("Windows 95") || Const.getOS().startsWith("Windows")) { // for windows all arguments including the command itself // need to be // included in 1 argument to cmd/command. StringBuffer cmdline = new StringBuffer(300); cmdline.append('"'); cmdline.append(Const.optionallyQuoteStringByOS(KettleVFS.getFilename(fileObject))); // Add the arguments from previous results... for (int i = 0; i < cmdRows.size(); i++) { // Normally just one row, but once in a while to remain compatible we have multiple. RowMetaAndData r = cmdRows.get(i); for (int j = 0; j < r.size(); j++) { cmdline.append(' '); cmdline.append(Const.optionallyQuoteStringByOS(r.getString(j, null))); } } cmdline.append('"'); cmds.add(cmdline.toString()); } else { // Add the arguments from previous results... for (int i = 0; i < cmdRows.size(); i++) { // Normally just one row, but once in a while to remain compatible we have multiple. RowMetaAndData r = cmdRows.get(i); for (int j = 0; j < r.size(); j++) { cmds.add(Const.optionallyQuoteStringByOS(r.getString(j, null))); } } } } else if (args != null) { // Add the base command... for (int i = 0; i < base.length; i++) { cmds.add(base[i]); } if (Const.getOS().equals("Windows 95") || Const.getOS().startsWith("Windows")) { // for windows all arguments including the command itself // need to be // included in 1 argument to cmd/command. StringBuffer cmdline = new StringBuffer(300); cmdline.append('"'); cmdline.append(Const.optionallyQuoteStringByOS(KettleVFS.getFilename(fileObject))); for (int i = 0; i < args.length; i++) { cmdline.append(' '); cmdline.append(Const.optionallyQuoteStringByOS(args[i])); } cmdline.append('"'); cmds.add(cmdline.toString()); } else { for (int i = 0; i < args.length; i++) { cmds.add(args[i]); } } } StringBuffer command = new StringBuffer(); Iterator<String> it = cmds.iterator(); boolean first = true; while (it.hasNext()) { if (!first) { command.append(' '); } else { first = false; } command.append(it.next()); } if (log.isBasic()) { logBasic(BaseMessages.getString(PKG, "JobShell.ExecCommand", command.toString())); } // Build the environment variable list... ProcessBuilder procBuilder = new ProcessBuilder(cmds); Map<String, String> env = procBuilder.environment(); String[] variables = listVariables(); for (int i = 0; i < variables.length; i++) { env.put(variables[i], getVariable(variables[i])); } if (getWorkDirectory() != null && !Const.isEmpty(Const.rtrim(getWorkDirectory()))) { String vfsFilename = environmentSubstitute(getWorkDirectory()); File file = new File(KettleVFS.getFilename(KettleVFS.getFileObject(vfsFilename, this))); procBuilder.directory(file); } Process proc = procBuilder.start(); // any error message? StreamLogger errorLogger = new StreamLogger(log, proc.getErrorStream(), "(stderr)", true); // any output? StreamLogger outputLogger = new StreamLogger(log, proc.getInputStream(), "(stdout)"); // kick them off Thread errorLoggerThread = new Thread(errorLogger); errorLoggerThread.start(); Thread outputLoggerThread = new Thread(outputLogger); outputLoggerThread.start(); proc.waitFor(); if (log.isDetailed()) { logDetailed(BaseMessages.getString(PKG, "JobShell.CommandFinished", command.toString())); } // What's the exit status? result.setExitStatus(proc.exitValue()); if (result.getExitStatus() != 0) { if (log.isDetailed()) { logDetailed(BaseMessages.getString(PKG, "JobShell.ExitStatus", environmentSubstitute(getFilename()), "" + result.getExitStatus())); } result.setNrErrors(1); } // wait until loggers read all data from stdout and stderr errorLoggerThread.join(); outputLoggerThread.join(); // close the streams // otherwise you get "Too many open files, java.io.IOException" after a lot of iterations proc.getErrorStream().close(); proc.getOutputStream().close(); } catch (IOException ioe) { logError(BaseMessages.getString(PKG, "JobShell.ErrorRunningShell", environmentSubstitute(getFilename()), ioe.toString()), ioe); result.setNrErrors(1); } catch (InterruptedException ie) { logError(BaseMessages.getString(PKG, "JobShell.Shellinterupted", environmentSubstitute(getFilename()), ie.toString()), ie); result.setNrErrors(1); } catch (Exception e) { logError(BaseMessages.getString(PKG, "JobShell.UnexpectedError", environmentSubstitute(getFilename()), e.toString()), e); result.setNrErrors(1); } finally { // If we created a temporary file, remove it... // if (tempFile != null) { try { tempFile.delete(); } catch (Exception e) { BaseMessages.getString(PKG, "JobShell.UnexpectedError", tempFile.toString(), e.toString()); } } } if (result.getNrErrors() > 0) { result.setResult(false); } else { result.setResult(true); } }
From source file:com.flexive.shared.FxSharedUtils.java
/** * Execute a command on the operating system * * @param command name of the command/* w ww .ja va 2 s.co m*/ * @param arguments arguments to pass to the command (one argument per String!) * @return result */ public static ProcessResult executeCommand(String command, String... arguments) { Runtime r = Runtime.getRuntime(); String[] cmd = new String[arguments.length + (WINDOWS ? 3 : 1)]; if (WINDOWS) { //have to run a shell on windows cmd[0] = "cmd"; cmd[1] = "/c"; } cmd[WINDOWS ? 2 : 0] = command; System.arraycopy(arguments, 0, cmd, (WINDOWS ? 3 : 1), arguments.length); StringBuilder cmdline = new StringBuilder(200); cmdline.append(command); for (String argument : arguments) cmdline.append(" ").append(argument); Process p = null; AsyncStreamBuffer out = null; AsyncStreamBuffer err = null; try { p = r.exec(cmd); // p = r.exec(cmdline); out = new AsyncStreamBuffer(p.getInputStream()); err = new AsyncStreamBuffer(p.getErrorStream()); out.start(); err.start(); p.waitFor(); while (out.isAlive()) Thread.sleep(10); while (err.isAlive()) Thread.sleep(10); } catch (Exception e) { String error = e.getMessage(); if (err != null && err.getResult() != null && err.getResult().trim().length() > 0) error = error + "(" + err.getResult() + ")"; return new ProcessResult(cmdline.toString(), (p == null ? -1 : p.exitValue()), (out == null ? "" : out.getResult()), error); } finally { if (p != null) { try { p.getInputStream().close(); } catch (Exception e1) { //bad luck } try { p.getErrorStream().close(); } catch (Exception e1) { //bad luck } try { p.getOutputStream().close(); } catch (Exception e1) { //bad luck } } } return new ProcessResult(cmdline.toString(), p.exitValue(), out.getResult(), err.getResult()); }