List of usage examples for java.lang Process destroy
public abstract void destroy();
From source file:org.wso2.andes.test.utils.QpidBrokerTestCase.java
public void startBroker(int port) throws Exception { port = getPort(port);//from w ww . j a v a 2s . c o m // Save any configuration changes that have been made saveTestConfiguration(); saveTestVirtualhosts(); if(_brokers.get(port) != null) { throw new IllegalStateException("There is already an existing broker running on port " + port); } if (_brokerType.equals(BrokerType.INTERNAL) && !existingInternalBroker()) { setConfigurationProperty(ServerConfiguration.MGMT_CUSTOM_REGISTRY_SOCKET, String.valueOf(false)); saveTestConfiguration(); BrokerOptions options = new BrokerOptions(); options.setConfigFile(_configFile.getAbsolutePath()); options.addPort(port); addExcludedPorts(port, options); options.setJmxPort(getManagementPort(port)); //Set the log config file, relying on the log4j.configuration system property //set on the JVM by the JUnit runner task in module.xml. options.setLogConfigFile(new URL(System.getProperty("log4j.configuration")).getFile()); Broker broker = new Broker(); _logger.info("starting internal broker (same JVM)"); broker.startup(options); _brokers.put(port, new InternalBrokerHolder(broker)); } else if (!_brokerType.equals(BrokerType.EXTERNAL)) { String cmd = getBrokerCommand(port); _logger.info("starting external broker: " + cmd); ProcessBuilder pb = new ProcessBuilder(cmd.split("\\s+")); pb.redirectErrorStream(true); Map<String, String> env = pb.environment(); String qpidHome = System.getProperty(QPID_HOME); env.put(QPID_HOME, qpidHome); //Augment Path with bin directory in QPID_HOME. env.put("PATH", env.get("PATH").concat(File.pathSeparator + qpidHome + "/bin")); //Add the test name to the broker run. // DON'T change PNAME, qpid.stop needs this value. env.put("QPID_PNAME", "-DPNAME=QPBRKR -DTNAME=\"" + _testName + "\""); // Add the port to QPID_WORK to ensure unique working dirs for multi broker tests env.put("QPID_WORK", getQpidWork(_brokerType, port)); // Use the environment variable to set amqj.logging.level for the broker // The value used is a 'server' value in the test configuration to // allow a differentiation between the client and broker logging levels. if (System.getProperty("amqj.server.logging.level") != null) { setBrokerEnvironment("AMQJ_LOGGING_LEVEL", System.getProperty("amqj.server.logging.level")); } // Add all the environment settings the test requested if (!_env.isEmpty()) { for (Map.Entry<String, String> entry : _env.entrySet()) { env.put(entry.getKey(), entry.getValue()); } } // Add default test logging levels that are used by the log4j-test // Use the convenience methods to push the current logging setting // in to the external broker's QPID_OPTS string. if (System.getProperty("amqj.protocol.logging.level") != null) { setSystemProperty("amqj.protocol.logging.level"); } if (System.getProperty("root.logging.level") != null) { setSystemProperty("root.logging.level"); } String QPID_OPTS = " "; // Add all the specified system properties to QPID_OPTS if (!_propertiesSetForBroker.isEmpty()) { for (String key : _propertiesSetForBroker.keySet()) { QPID_OPTS += "-D" + key + "=" + _propertiesSetForBroker.get(key) + " "; } if (env.containsKey("QPID_OPTS")) { env.put("QPID_OPTS", env.get("QPID_OPTS") + QPID_OPTS); } else { env.put("QPID_OPTS", QPID_OPTS); } } Process process = pb.start();; Piper p = new Piper(process.getInputStream(), _brokerOutputStream, System.getProperty(BROKER_READY), System.getProperty(BROKER_STOPPED)); p.start(); if (!p.await(30, TimeUnit.SECONDS)) { _logger.info("broker failed to become ready (" + p.ready + "):" + p.getStopLine()); //Ensure broker has stopped process.destroy(); cleanBroker(); throw new RuntimeException("broker failed to become ready:" + p.getStopLine()); } try { //test that the broker is still running and hasn't exited unexpectedly int exit = process.exitValue(); _logger.info("broker aborted: " + exit); cleanBroker(); throw new RuntimeException("broker aborted: " + exit); } catch (IllegalThreadStateException e) { // this is expect if the broker started successfully } _brokers.put(port, new SpawnedBrokerHolder(process)); } }
From source file:org.jwebsocket.plugins.tts.SpeakAloudProvider.java
@Override public byte[] generateAudioFromString(String aText, String aGender, String aSpeaker, String aFormat) { synchronized (this) { byte[] lResult = null; Process lProcess = null; try {/* ww w . jav a2 s .c o m*/ String lUUID = "speak"; // UUID.randomUUID().toString(); String lTextFN = mTextPath + lUUID + ".txt"; mLog.debug("Executing '" + mExePath + " " + lTextFN + "'..."); // write text from client into text file of server harddisk File lTextFile = new File(lTextFN); FileUtils.writeStringToFile(lTextFile, aText, "Cp1252"); // call conversion tool with appropriate arguments Runtime lRT = Runtime.getRuntime(); // pass the text file to be converted. String[] lCmd = { mExePath, lTextFN }; lProcess = lRT.exec(lCmd); InputStream lIS = lProcess.getInputStream(); InputStreamReader lISR = new InputStreamReader(lIS); BufferedReader lBR = new BufferedReader(lISR); String lLine; while ((lLine = lBR.readLine()) != null) { // System.out.println(lLine); } // wait until process has performed completely if (lProcess.waitFor() != 0) { mLog.error("Converter exited with value " + lProcess.exitValue()); } else { mLog.info("Audiostream successfully generated!"); } String lAudioFN = mTextPath + lUUID + ".MP3"; File lAudioFile = new File(lAudioFN); lResult = FileUtils.readFileToByteArray(lAudioFile); FileUtils.deleteQuietly(lTextFile); FileUtils.deleteQuietly(lAudioFile); } catch (Exception lEx) { mLog.error(Logging.getSimpleExceptionMessage(lEx, "performing TTS conversion")); } finally { if (null != lProcess) { lProcess.destroy(); } } return lResult; } }
From source file:com.flipzu.PostProcThread.java
private void ffmpegCleanUp(Broadcast bcast) { debug.logPostProc("PostProcThread, ffmpegCleanUp for " + bcast.getFilename()); Process ffmpeg = null; String outputCodec = Config.getInstance().getOutputCodec(); String inputFilename = bcast.getFilename(); Integer outputBitrate = bcast.getBitrate(); String outputFilename = Config.getInstance().getFileWriterDestDir() + "/" + bcast.getId() + "-postproc" + Config.getInstance().getFileWriterExtension(); String ffmpegCmd = Config.getInstance().getFfmpegCommand(); String inputFileFlag = Config.getInstance().getInputFileFlag(); String outputBitrateFlag = Config.getInstance().getOutputBitrateFlag(); String outputCodecFlag = Config.getInstance().getOutputCodecFlag(); String outputFileFlag = Config.getInstance().getOutputFileFlag(); try {/*from w ww . j ava 2s.co m*/ ffmpeg = new ProcessBuilder(ffmpegCmd, inputFileFlag, inputFilename, outputBitrateFlag, outputBitrate.toString(), outputCodecFlag, outputCodec, "-y", outputFileFlag, outputFilename) .start(); } catch (IOException e) { Debug.getInstance().logError("ffmpegClenup exception", e); } int retcode = -1; try { retcode = ffmpeg.waitFor(); } catch (InterruptedException e) { Debug.getInstance().logError("ffmpegClenup exception", e); } if (retcode == 0) { File f = new File(inputFilename); debug.logPostProc("ffmpegCleanup, deleting " + inputFilename); f.delete(); bcast.setFilename(outputFilename); } ffmpeg.destroy(); }
From source file:org.apache.hive.spark.client.SparkSubmitSparkClient.java
@Override protected Future<Void> launchDriver(String isTesting, RpcServer rpcServer, String clientId) throws IOException { Callable<Void> runnable; String cmd = Joiner.on(" ").join(argv); LOG.info("Running client driver with argv: {}", cmd); ProcessBuilder pb = new ProcessBuilder("sh", "-c", cmd); // Prevent hive configurations from being visible in Spark. pb.environment().remove("HIVE_HOME"); pb.environment().remove("HIVE_CONF_DIR"); // Add credential provider password to the child process's environment // In case of Spark the credential provider location is provided in the jobConf when the job is submitted String password = getSparkJobCredentialProviderPassword(); if (password != null) { pb.environment().put(Constants.HADOOP_CREDENTIAL_PASSWORD_ENVVAR, password); }/*from www .j a v a 2 s . c o m*/ if (isTesting != null) { pb.environment().put("SPARK_TESTING", isTesting); } final Process child = pb.start(); String threadName = Thread.currentThread().getName(); final List<String> childErrorLog = Collections.synchronizedList(new ArrayList<String>()); final LogRedirector.LogSourceCallback callback = () -> isAlive; LogRedirector.redirect("spark-submit-stdout-redir-" + threadName, new LogRedirector(child.getInputStream(), LOG, callback)); LogRedirector.redirect("spark-submit-stderr-redir-" + threadName, new LogRedirector(child.getErrorStream(), LOG, childErrorLog, callback)); runnable = () -> { try { int exitCode = child.waitFor(); if (exitCode != 0) { List<String> errorMessages = new ArrayList<>(); synchronized (childErrorLog) { for (String line : childErrorLog) { if (StringUtils.containsIgnoreCase(line, "Error")) { errorMessages.add("\"" + line + "\""); } } } String errStr = errorMessages.isEmpty() ? "?" : Joiner.on(',').join(errorMessages); rpcServer.cancelClient(clientId, new RuntimeException("spark-submit process failed " + "with exit code " + exitCode + " and error " + errStr)); } } catch (InterruptedException ie) { LOG.warn( "Thread waiting on the child process (spark-submit) is interrupted, killing the child process."); rpcServer.cancelClient(clientId, "Thread waiting on the child process (spark-submit) is interrupted"); Thread.interrupted(); child.destroy(); } catch (Exception e) { String errMsg = "Exception while waiting for child process (spark-submit)"; LOG.warn(errMsg, e); rpcServer.cancelClient(clientId, errMsg); } return null; }; FutureTask<Void> futureTask = new FutureTask<>(runnable); Thread driverThread = new Thread(futureTask); driverThread.setDaemon(true); driverThread.setName("SparkSubmitMonitor"); driverThread.start(); return futureTask; }
From source file:org.apache.ambari.server.api.services.stackadvisor.StackAdvisorRunner.java
/** * Runs stack_advisor.py script in the specified {@code actionDirectory}. * * @param script stack advisor script/*from w ww . j a va 2s .co m*/ * @param saCommandType {@link StackAdvisorCommandType} to run. * @param actionDirectory directory for the action */ public void runScript(String script, StackAdvisorCommandType saCommandType, File actionDirectory) throws StackAdvisorException { LOG.info( String.format("Script=%s, actionDirectory=%s, command=%s", script, actionDirectory, saCommandType)); String outputFile = actionDirectory + File.separator + "stackadvisor.out"; String errorFile = actionDirectory + File.separator + "stackadvisor.err"; ProcessBuilder builder = prepareShellCommand(script, saCommandType, actionDirectory, outputFile, errorFile); try { Process process = builder.start(); try { LOG.info("Stack-advisor output={}, error={}", outputFile, errorFile); int exitCode = process.waitFor(); String outMessage; String errMessage = null; try { outMessage = FileUtils.readFileToString(new File(outputFile)).trim(); errMessage = FileUtils.readFileToString(new File(errorFile)).trim(); LOG.info("Stack advisor output files"); LOG.info(" advisor script stdout: {}", outMessage); LOG.info(" advisor script stderr: {}", errMessage); } catch (IOException io) { LOG.error("Error in reading script log files", io); } if (exitCode > 0) { String errorMessage; if (errMessage != null) { // We want to get the last line. int index = errMessage.lastIndexOf("\n"); if (index > 0 && index == (errMessage.length() - 1)) { index = errMessage.lastIndexOf("\n", index - 1); // sentence ended with newline } if (index > -1) { errMessage = errMessage.substring(index + 1).trim(); } errorMessage = errMessage; } else { errorMessage = "Error occurred during stack advisor execution"; } switch (exitCode) { case 1: throw new StackAdvisorRequestException(errorMessage); case 2: throw new StackAdvisorException(errorMessage); } } } finally { process.destroy(); } } catch (StackAdvisorException ex) { throw ex; } catch (Exception ioe) { String message = "Error executing stack advisor: "; LOG.error(message, ioe); throw new StackAdvisorException(message + ioe.getMessage()); } }
From source file:egovframework.com.utl.sys.fsm.service.FileSystemUtils.java
/** * Performs the os command./*from w w w. ja v a 2 s. c o m*/ * * @param cmdAttribs the command line parameters * @param max The maximum limit for the lines returned * @return the parsed data * @throws IOException if an error occurs */ List performCommand(String[] cmdAttribs, int max) throws IOException { // this method does what it can to avoid the 'Too many open files' error // based on trial and error and these links: // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4784692 // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4801027 // http://forum.java.sun.com/thread.jspa?threadID=533029&messageID=2572018 // however, its still not perfect as the JDK support is so poor // (see commond-exec or ant for a better multi-threaded multi-os solution) List lines = new ArrayList(20); Process proc = null; InputStream in = null; OutputStream out = null; InputStream err = null; BufferedReader inr = null; try { proc = openProcess(cmdAttribs); in = proc.getInputStream(); out = proc.getOutputStream(); err = proc.getErrorStream(); inr = new BufferedReader(new InputStreamReader(in)); String line = inr.readLine(); while (line != null && lines.size() < max) { line = line.toLowerCase().trim(); lines.add(line); line = inr.readLine(); } proc.waitFor(); if (proc.exitValue() != 0) { // os command problem, throw exception throw new IOException("Command line returned OS error code '" + proc.exitValue() + "' for command " + Arrays.asList(cmdAttribs)); } if (lines.size() == 0) { // unknown problem, throw exception throw new IOException( "Command line did not return any info " + "for command " + Arrays.asList(cmdAttribs)); } return lines; } catch (InterruptedException ex) { throw new IOException("Command line threw an InterruptedException '" + ex.getMessage() + "' for command " + Arrays.asList(cmdAttribs)); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); IOUtils.closeQuietly(err); IOUtils.closeQuietly(inr); if (proc != null) { proc.destroy(); } } }
From source file:org.kalypso.optimize.SceJob.java
private void startSCEOptimization(final SceIOHandler sceIO, final ISimulationMonitor monitor) throws SimulationException { InputStreamReader inStream = null; InputStreamReader errStream = null; // FIXME: too much copy/paste from ProcessHelper; we can probably use process helper instead! ProcessControlThread procCtrlThread = null; try {//w w w . ja v a 2s .com final String[] commands = new String[] { m_sceExe.getAbsolutePath() }; final Process process = Runtime.getRuntime().exec(commands, null, m_sceDir); final long lTimeOut = 1000l * 60l * 15l;// 15 minutes procCtrlThread = new ProcessControlThread(process, lTimeOut); procCtrlThread.start(); final StringBuffer outBuffer = new StringBuffer(); final StringBuffer errBuffer = new StringBuffer(); final Writer inputWriter = new PrintWriter(process.getOutputStream(), false); inStream = new InputStreamReader(process.getInputStream()); errStream = new InputStreamReader(process.getErrorStream()); final int stepMax = m_autoCalibration.getOptParameter().getMaxN(); while (true) { final int step = sceIO.getStep(); monitor.setProgress(100 * step / (stepMax + 1)); if (step > stepMax) { final String monitorMsg = String.format( "Optimierungsrechnung abgeschlossen, Ergebnisauswertung", step + 1, stepMax + 1); monitor.setMessage(monitorMsg); } else { final String monitorMsg = String.format("Optimierungsrechnung %d von %d", step + 1, stepMax + 1); monitor.setMessage(monitorMsg); } if (inStream.ready()) { final char buffer[] = new char[100]; final int bufferC = inStream.read(buffer); outBuffer.append(buffer, 0, bufferC); } if (errStream.ready()) { final char buffer[] = new char[100]; final int bufferC = errStream.read(buffer); errBuffer.append(buffer, 0, bufferC); } if (monitor.isCanceled()) { process.destroy(); procCtrlThread.endProcessControl(); return; } try { process.exitValue(); break; } catch (final IllegalThreadStateException e) { final OptimizeMonitor subMonitor = new OptimizeMonitor(monitor); sceIO.handleStreams(outBuffer, errBuffer, inputWriter, subMonitor); } Thread.sleep(100); } procCtrlThread.endProcessControl(); } catch (final IOException e) { e.printStackTrace(); throw new SimulationException("Fehler beim Ausfuehren", e); } catch (final InterruptedException e) { e.printStackTrace(); throw new SimulationException("beim Ausfuehren unterbrochen", e); } finally { IOUtils.closeQuietly(inStream); IOUtils.closeQuietly(errStream); if (procCtrlThread != null && procCtrlThread.procDestroyed()) { throw new SimulationException("beim Ausfuehren unterbrochen", new ProcessTimeoutException("Timeout bei der Abarbeitung der Optimierung")); } } }
From source file:com.fanniemae.ezpie.actions.HighlightScan.java
private void changeOracleExtractExtension(File castExtractionFile) { ProcessBuilder pb = new ProcessBuilder("java", "-jar", _dbDeliveryToolPath); Process process = null; Robot robot = null;//ww w .ja v a 2 s . c o m try { process = pb.start(); robot = new Robot(); } catch (IOException | AWTException e) { throw new PieException("Could not start Oracle extract.", e); } sleep(15000); // navigating to input text for (int i = 0; i < 3; i++) { keyPressRelease(KeyEvent.VK_TAB, 200); sleep(200); } // select populated target folder path keyPressReleaseControlA(500); // entering target folder path Keyboard keyboard = new Keyboard(robot); keyboard.type(castExtractionFile.getParent() + "\\deliveryResults"); // navigate to options keyPressReleaseShiftTab(200); keyPressRelease(KeyEvent.VK_RIGHT, 500); for (int i = 0; i < 2; i++) { keyPressRelease(KeyEvent.VK_TAB, 200); sleep(200); } // select populated extraction file path keyPressReleaseControlA(500); // entering target folder path that contains .castextraction file keyboard.type(castExtractionFile.getPath()); sleep(500); keyPressRelease(KeyEvent.VK_TAB, 200); sleep(500); // navigate to menu bar to select Application/Run Application since tabbing to 'Run Application' button // and pressing enter does not execute run keyPressRelease(KeyEvent.VK_ALT, 500); sleep(500); for (int i = 0; i < 2; i++) { keyPressRelease(KeyEvent.VK_RIGHT, 200); } keyPressRelease(KeyEvent.VK_ENTER, 200); keyPressRelease(KeyEvent.VK_DOWN, 500); keyPressRelease(KeyEvent.VK_ENTER, 200); sleep(5000); process.destroy(); }
From source file:com.hellblazer.process.impl.AbstractManagedProcess.java
/** * The actual execution process. Control will not return until the command * list execution has finished./*w ww . ja v a2s. c om*/ * * @param commands * - the command list to execute * * @throws IOException * - if anything goes wrong during the execution. */ protected void primitiveExecute(List<String> commands) throws IOException { ProcessBuilder builder = new ProcessBuilder(); builder.directory(directory); if (environment != null) { builder.environment().putAll(environment); } builder.command(commands); builder.redirectErrorStream(true); // combine OUT and ERR into one // stream Process p = builder.start(); final BufferedReader shellReader = new BufferedReader(new InputStreamReader(p.getInputStream())); Runnable reader = new Runnable() { @Override public void run() { String line; try { line = shellReader.readLine(); } catch (IOException e) { if (!"Stream closed".equals(e.getMessage()) && !e.getMessage().contains("Bad file descriptor")) { log.log(Level.SEVERE, "Failed reading process output", e); } return; } while (line != null) { if (log.isLoggable(Level.FINE) && line != null) { log.fine("[" + id + "] " + line); } try { line = shellReader.readLine(); } catch (IOException e) { if (!"Stream closed".equals(e.getMessage())) { log.log(Level.SEVERE, "Failed reading process output", e); } return; } } } }; Thread readerThread = new Thread(reader, "Process reader for: " + getCommand()); readerThread.setDaemon(true); readerThread.start(); try { p.waitFor(); } catch (InterruptedException e) { return; } finally { readerThread.interrupt(); p.destroy(); } }
From source file:no.sintef.jarfter.Jarfter.java
/** * Encapsulates the use of ProccessBuilder * @param command//from ww w . ja v a 2 s .c om * @param arguments * @throws IOException * @throws InterruptedException */ private void runCommand(String command, String... arguments) throws JarfterException { log("runCommand - Starting " + command + "...\n"); List<String> commandList = new ArrayList<String>(); commandList.add(command); for (String argument : arguments) { commandList.add(argument); } ProcessBuilder procBuilder = new ProcessBuilder(commandList); Process detachedProc = null; try { detachedProc = procBuilder.start(); } catch (IOException ioe) { log("runCommand - Could not start the detachedProc..."); error(ioe); throw new JarfterException(); } String line; String stdout = ""; String stderr = ""; try { // Reading output BufferedReader outputReader = new BufferedReader(new InputStreamReader(detachedProc.getInputStream())); while ((line = outputReader.readLine()) != null) { stdout += line; } outputReader.close(); // Reading error BufferedReader errorReader = new BufferedReader(new InputStreamReader(detachedProc.getErrorStream())); while ((line = errorReader.readLine()) != null) { stderr += line; } errorReader.close(); } catch (IOException ioe) { log("runCommand - caught exception while reading stdout and stderr..."); error(ioe); throw new JarfterException(JarfterException.Error.IO_PROCESS_OUTPUT); } log("runCommand - stdout:\n" + stdout); log("runCommand - stderr:\n" + stderr); try { detachedProc.waitFor(); } catch (InterruptedException interruption) { log("runCommand - caught InterruptedException from detachedProc.waitFor()..."); error(interruption); throw new JarfterException(interruption.getClass().getName(), interruption.getLocalizedMessage()); } detachedProc.destroy(); if (!stderr.equals("")) { runCommandAnalyzeStderr(command, stderr); } }