List of usage examples for java.lang Process destroy
public abstract void destroy();
From source file:com.rapidminer.tools.Tools.java
/** * Waits for process to die and writes log messages. Terminates if exit value is not 0. *//*from w w w .ja va2 s.c o m*/ public static void waitForProcess(final Operator operator, final Process process, final String name) throws OperatorException { int exitValue = -1; try { // if operator was provided, start an observer thread // that check if the operator was stopped if (operator != null) { Thread observerThread = new Thread(operator.getName() + "-stop-observer") { @Override public void run() { Integer exitValue = null; while (exitValue == null) { try { Thread.sleep(500); exitValue = process.exitValue(); } catch (IllegalThreadStateException | InterruptedException e) { try { operator.checkForStop(); } catch (ProcessStoppedException e1) { LogService.getRoot().log(Level.INFO, "com.rapidminer.tools.Tools.terminating_process", name); process.destroy(); try { exitValue = process.waitFor(); } catch (InterruptedException e2) { // in case of another interrupt, set exit value to error exitValue = -1; } } } } } }; observerThread.setDaemon(true); observerThread.start(); } LogService.getRoot().log(Level.ALL, "com.rapidminer.tools.Tools.waiting_for_process", name); exitValue = process.waitFor(); } catch (InterruptedException e) { // if process was stopped because user aborted it, re-throw exception if (operator != null) { operator.checkForStop(); } // if process was stopped because of an error, set exit value to -1 exitValue = -1; } if (exitValue == 0) { LogService.getRoot().log(Level.FINE, "com.rapidminer.tools.Tools.process_terminated_successfully", name); } else { throw new UserError(operator, 306, new Object[] { name, exitValue }); } }
From source file:com.stratio.qa.specs.CommonG.java
/** * Runs a command locally/* ww w . j a v a 2 s . c om*/ * * @param command command used to be run locally */ public void runLocalCommand(String command) throws Exception { String result = ""; String line; Process p; try { p = Runtime.getRuntime().exec(new String[] { "/bin/sh", "-c", command }); p.waitFor(); } catch (java.io.IOException e) { this.commandExitStatus = 1; this.commandResult = "Error"; return; } BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream())); while ((line = input.readLine()) != null) { result += line; } input.close(); this.commandResult = result; this.commandExitStatus = p.exitValue(); p.destroy(); if (p.isAlive()) { p.destroyForcibly(); } }
From source file:org.wso2.carbon.integration.tests.carbontools.RunBuildXMLTestCase.java
@Test(groups = { "carbon.core" }, description = "Run the ant localize command and verifying the languageBundle") public void testBuildXMLGenerateLanguageBundle() throws Exception { boolean isJarCreated = false; Process process = null; try {//from w w w . j a v a 2 s. c o m File sourceFile = new File( TestConfigurationProvider.getResourceLocation() + File.separator + "artifacts" + File.separator + "CARBON" + File.separator + "carbontools" + File.separator + "resources"); File targetFile = new File(carbonHome + File.separator + "resources"); super.copyFolder(sourceFile, targetFile); String cmdArray[]; if ((CarbonCommandToolsUtil.getCurrentOperatingSystem() .contains(OperatingSystems.WINDOWS.name().toLowerCase()))) { cmdArray = new String[] { "cmd.exe", "/c", "start", "ant", "localize" }; } else { cmdArray = new String[] { "ant", "localize" }; } process = CarbonCommandToolsUtil.runScript(carbonHome + File.separator + "bin", cmdArray); File folder = new File(carbonHome + File.separator + "repository" + File.separator + "components" + File.separator + "dropins"); long startTime = System.currentTimeMillis(); while (!isJarCreated && (System.currentTimeMillis() - startTime) < CarbonIntegrationConstants.DEFAULT_WAIT_MS) { if (folder.exists() && folder.isDirectory()) { File[] listOfFiles = folder.listFiles(); if (listOfFiles != null) { for (File file : listOfFiles) {//Check repository lib as well if (file.getName() .contains("org.wso2.carbon.identity.oauth.ui.languageBundle_1.0.jar")) { log.info("LanguageBundle jar copied successfully"); isJarCreated = true; break; } } } } else { log.info("LanguageBundle not created yet time " + (System.currentTimeMillis() - startTime) + " milliseconds"); Thread.sleep(1000);// Sleeping 1 second } } } finally { if (process != null) { process.destroy(); } } assertTrue(isJarCreated, "Jar not copied successfully"); }
From source file:org.apache.qpid.test.utils.QpidBrokerTestCase.java
public void startBroker(int port, TestBrokerConfiguration testConfiguration, XMLConfiguration virtualHosts, boolean managementMode) throws Exception { port = getPort(port);/*from www.j a va2 s . com*/ String testConfig = saveTestConfiguration(port, testConfiguration); String virtualHostsConfig = saveTestVirtualhosts(port, virtualHosts); if(_brokers.get(port) != null) { throw new IllegalStateException("There is already an existing broker running on port " + port); } Set<Integer> portsUsedByBroker = guessAllPortsUsedByBroker(port); if (_brokerType.equals(BrokerType.INTERNAL) && !existingInternalBroker()) { _logger.info("Set test.virtualhosts property to: " + virtualHostsConfig); setSystemProperty(TEST_VIRTUALHOSTS, virtualHostsConfig); setSystemProperty(BrokerProperties.PROPERTY_USE_CUSTOM_RMI_SOCKET_FACTORY, "false"); BrokerOptions options = new BrokerOptions(); options.setConfigurationStoreType(_brokerStoreType); options.setConfigurationStoreLocation(testConfig); options.setManagementMode(managementMode); //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(_logConfigFile.getAbsolutePath()); Broker broker = new Broker(); _logger.info("Starting internal broker (same JVM)"); broker.startup(options); _brokers.put(port, new InternalBrokerHolder(broker, System.getProperty("QPID_WORK"), portsUsedByBroker)); } else if (!_brokerType.equals(BrokerType.EXTERNAL)) { // Add the port to QPID_WORK to ensure unique working dirs for multi broker tests final String qpidWork = getQpidWork(_brokerType, port); String[] cmd = _brokerCommandHelper.getBrokerCommand(port, testConfig, _brokerStoreType, _logConfigFile); if (managementMode) { String[] newCmd = new String[cmd.length + 1]; System.arraycopy(cmd, 0, newCmd, 0, cmd.length); newCmd[cmd.length] = "-mm"; cmd = newCmd; } _logger.info("Starting spawn broker using command: " + StringUtils.join(cmd, ' ')); ProcessBuilder pb = new ProcessBuilder(cmd); pb.redirectErrorStream(true); Map<String, String> processEnv = pb.environment(); String qpidHome = System.getProperty(QPID_HOME); processEnv.put(QPID_HOME, qpidHome); //Augment Path with bin directory in QPID_HOME. processEnv.put("PATH", processEnv.get("PATH").concat(File.pathSeparator + qpidHome + "/bin")); //Add the test name to the broker run. // DON'T change PNAME, qpid.stop needs this value. processEnv.put("QPID_PNAME", "-DPNAME=QPBRKR -DTNAME=\"" + getTestName() + "\""); processEnv.put("QPID_WORK", qpidWork); // 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()) { processEnv.put(entry.getKey(), entry.getValue()); } } String qpidOpts = ""; // a synchronized hack to avoid adding into QPID_OPTS the values // of JVM properties "test.virtualhosts" and "test.config" set by a concurrent startup process synchronized (_propertiesSetForBroker) { // 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. setSystemProperty("amqj.protocol.logging.level"); setSystemProperty("root.logging.level"); setSystemProperty(BrokerProperties.PROPERTY_BROKER_DEFAULT_AMQP_PROTOCOL_EXCLUDES); setSystemProperty(BrokerProperties.PROPERTY_BROKER_DEFAULT_AMQP_PROTOCOL_INCLUDES); setSystemProperty(TEST_VIRTUALHOSTS, virtualHostsConfig); // Add all the specified system properties to QPID_OPTS if (!_propertiesSetForBroker.isEmpty()) { for (String key : _propertiesSetForBroker.keySet()) { qpidOpts += " -D" + key + "=" + _propertiesSetForBroker.get(key); } } } if (processEnv.containsKey("QPID_OPTS")) { qpidOpts = processEnv.get("QPID_OPTS") + qpidOpts; } processEnv.put("QPID_OPTS", qpidOpts); // cpp broker requires that the work directory is created createBrokerWork(qpidWork); Process process = pb.start(); Piper p = new Piper(process.getInputStream(), _testcaseOutputStream, System.getProperty(BROKER_READY), System.getProperty(BROKER_STOPPED), _interleaveBrokerLog ? _brokerLogPrefix : null); p.start(); SpawnedBrokerHolder holder = new SpawnedBrokerHolder(process, qpidWork, portsUsedByBroker); if (!p.await(30, TimeUnit.SECONDS)) { _logger.info("broker failed to become ready (" + p.getReady() + "):" + p.getStopLine()); String threadDump = holder.dumpThreads(); if (!threadDump.isEmpty()) { _logger.info("the result of a try to capture thread dump:" + threadDump); } //Ensure broker has stopped process.destroy(); cleanBrokerWork(qpidWork); 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); cleanBrokerWork(qpidWork); throw new RuntimeException("broker aborted: " + exit); } catch (IllegalThreadStateException e) { // this is expect if the broker started successfully } _brokers.put(port, holder); } }
From source file:com.netease.qa.emmagee.service.EmmageeService.java
public void getlog() { new Thread(new Runnable() { @Override/*from w w w .ja v a 2 s .c o m*/ public void run() { try { Process process = null; DataOutputStream os = null; String logcatCommand; if (packageName.contains("elong")) { logcatCommand = "logcat -v time |grep --line-buffered -E \"GreenDaoHelper_insert_e|Displayed\" | grep -v -E \"show|logs|back|info\""; } else { logcatCommand = "logcat -v time |grep --line-buffered -E \"Displayed\""; } Runtime.getRuntime().exec("logcat -c"); process = Runtime.getRuntime().exec(isRoot ? COMMAND_SU : COMMAND_SH); os = new DataOutputStream(process.getOutputStream()); os.write(logcatCommand.getBytes()); os.writeBytes(COMMAND_LINE_END); os.flush(); bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream())); bufferedWriter = new BufferedWriter(new FileWriter(new File("/sdcard/logcat.log"))); String line = null; while (!isServiceStop) { while ((line = bufferedReader.readLine()) != null) { bufferedWriter.write(line + Constants.LINE_END); } try { Thread.currentThread().sleep(Settings.SLEEP_TIME); } catch (InterruptedException e) { e.printStackTrace(); } } os.close(); bufferedWriter.flush(); bufferedReader.close(); process.destroy(); } catch (IOException e) { e.printStackTrace(); } finally { } } }).start(); }
From source file:com.bugvm.maven.surefire.BugVMSurefireProvider.java
@Override public RunResult invoke(Object forkTestSet) throws TestSetFailedException, ReporterException { if (testsToRun == null) { if (forkTestSet instanceof TestsToRun) { testsToRun = (TestsToRun) forkTestSet; } else if (forkTestSet instanceof Class) { testsToRun = TestsToRun.fromClass((Class<?>) forkTestSet); } else {// w w w . j av a 2s .c o m testsToRun = scanClassPath(); } } final ReporterFactory reporterFactory = providerParameters.getReporterFactory(); final RunListener reporter = reporterFactory.createReporter(); ConsoleOutputCapture.startCapture((ConsoleOutputReceiver) reporter); final JUnit4RunListener jUnit4TestSetReporter = new JUnit4RunListener(reporter); Result result = new Result(); final RunNotifier runNotifier = getRunNotifier(jUnit4TestSetReporter, result, customRunListeners); TestClient testClient = new TestClient(); testClient.setRunListener(new org.junit.runner.notification.RunListener() { public void testRunStarted(Description description) throws Exception { runNotifier.fireTestRunStarted(description); } public void testRunFinished(Result result) throws Exception { runNotifier.fireTestRunFinished(result); } public void testStarted(Description description) throws Exception { runNotifier.fireTestStarted(description); } public void testFinished(Description description) throws Exception { runNotifier.fireTestFinished(description); } public void testFailure(Failure failure) throws Exception { runNotifier.fireTestFailure(failure); } public void testAssumptionFailure(Failure failure) { runNotifier.fireTestAssumptionFailed(failure); } public void testIgnored(Description description) throws Exception { runNotifier.fireTestIgnored(description); } }); String runArgs = System.getProperty(PROP_RUN_ARGS, ""); if (!runArgs.isEmpty()) { testClient .setRunArgs(new ArrayList<>(Arrays.asList(CommandLine.parse("cmd " + runArgs).getArguments()))); } Process process = null; try { Config config = testClient.configure(createConfig(), isIOS()).build(); config.getLogger().info("Building BugVM tests for: %s (%s)", config.getOs(), config.getArch()); config.getLogger().info("This could take a while, especially the first time round"); AppCompiler appCompiler = new AppCompiler(config); appCompiler.build(); LaunchParameters launchParameters = config.getTarget().createLaunchParameters(); if (Boolean.getBoolean(PROP_SERVER_DEBUG)) { launchParameters.getArguments().add("-rvm:Dbugvm.debug=true"); } if (System.getProperty(PROP_IOS_SIMULATOR_NAME) != null && launchParameters instanceof IOSSimulatorLaunchParameters) { DeviceType type = DeviceType.getDeviceType(System.getProperty(PROP_IOS_SIMULATOR_NAME)); ((IOSSimulatorLaunchParameters) launchParameters).setDeviceType(type); } else if (launchParameters instanceof IOSSimulatorLaunchParameters) { if (config.getArch() == Arch.x86_64) { ((IOSSimulatorLaunchParameters) launchParameters) .setDeviceType(DeviceType.getBestDeviceType(config.getArch(), null, null, null)); } } process = appCompiler.launchAsync(launchParameters); runNotifier.fireTestRunStarted(null); for (Class<?> clazz : testsToRun) { executeTestSet(testClient, clazz, reporter, runNotifier); } testClient.terminate(); process.waitFor(); runNotifier.fireTestRunFinished(result); JUnit4RunListener.rethrowAnyTestMechanismFailures(result); } catch (Throwable t) { throw new RuntimeException("BugVM test run failed", t); } finally { if (process != null) { process.destroy(); } } return reporterFactory.close(); }
From source file:gov.nist.appvet.tool.sigverifier.Service.java
private static boolean execute(String command, StringBuffer output) { List<String> commandArgs = Arrays.asList(command.split("\\s+")); ProcessBuilder pb = new ProcessBuilder(commandArgs); Process process = null; IOThreadHandler outputHandler = null; IOThreadHandler errorHandler = null; int exitValue = -1; try {/*from w w w .j a v a2 s.c om*/ if (command == null || command.isEmpty()) { log.error("Command is null or empty"); return false; } log.debug("Executing " + command); process = pb.start(); outputHandler = new IOThreadHandler(process.getInputStream()); outputHandler.start(); errorHandler = new IOThreadHandler(process.getErrorStream()); errorHandler.start(); if (process.waitFor(Properties.commandTimeout, TimeUnit.MILLISECONDS)) { // Process has waited and exited within the timeout exitValue = process.exitValue(); if (exitValue == 0) { log.debug("Command terminated normally: \n" + outputHandler.getOutput() + "\nErrors: " + errorHandler.getOutput()); StringBuffer resultOut = outputHandler.getOutput(); output.append(resultOut); return true; } else { log.error("Command terminated abnormally: \n" + outputHandler.getOutput() + "\nErrors: " + errorHandler.getOutput()); StringBuffer resultError = errorHandler.getOutput(); output.append(resultError); return false; } } else { // Process exceed timeout or was interrupted log.error("Command timed-out or was interrupted: \n" + outputHandler.getOutput() + "\nErrors: " + errorHandler.getOutput()); StringBuffer resultOutput = outputHandler.getOutput(); StringBuffer resultError = errorHandler.getOutput(); if (resultOutput != null) { output.append(resultOutput); return false; } else if (resultError != null) { output.append(resultError); } else { output.append(Properties.toolName + " timed-out"); } return false; } } catch (IOException e) { e.printStackTrace(); return false; } catch (InterruptedException e) { e.printStackTrace(); return false; } finally { if (outputHandler.isAlive()) { try { outputHandler.inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } if (errorHandler.isAlive()) { try { errorHandler.inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } if (process.isAlive()) { process.destroy(); } } }
From source file:org.jajuk.util.UtilSystem.java
/** * Convert a full regular Windows path to 8.3 DOS format * //from ww w. jav a2 s . c om * @param longname the regular absolute path * * @return the shortname absolute path */ public static String getShortPathNameW(String longname) { // Find the shortname .bat converter, create it if it doesn't yet exist String shortname = null; try { File fileConverter = SessionService.getConfFileByPath(Const.FILE_FILENAME_CONVERTER); if (!fileConverter.exists() // Test that the converter version has not been updated // IMPORTANT ! Don't forget to update the CONVERTER_FILE_SIZE constant if you change the // script ! || (fileConverter.exists() && fileConverter.length() != CONVERTER_FILE_SIZE)) { FileWriter fw = new FileWriter(fileConverter); fw.write("@echo off\n"); fw.write("dir /x \"%~s1\""); fw.flush(); fw.close(); } // these two quotes are required in the case where both directory and file are non-ascii ProcessBuilder pc = new ProcessBuilder(fileConverter.getAbsolutePath(), "\"" + longname + "\""); Process process = pc.start(); /* * dir /x parsing : Sample output (in French but should work with any language): * * Le volume dans le lecteur D s'appelle Donnes * * Le numro de srie du volume est C880-0321 * * Rpertoire de D:\MESDOC~1\MAMUSI~1\FILES_~1\1F19~1 * * 07/06/2010 21:49 <REP> . * * 07/06/2010 21:49 <REP> .. * * 07/06/2010 14:41 20108 -(_)~1.MP3 ? - (?+?).mp3 */ BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream())); String line = ""; String lineDirectory = null; while ((line = br.readLine()) != null) { String ext = UtilSystem.getExtension(new File(longname)); if (StringUtils.isNotBlank(line)) { // Index of the file extension in short name int indexExtension = line.indexOf(longname.substring(0, 3).toUpperCase()); if (line.endsWith(ext)) { int indexEnd = line.indexOf(ext.toUpperCase()); int indexBegin = indexEnd; // Find the previous space while (line.charAt(indexBegin) != ' ') { indexBegin--; } shortname = line.substring(indexBegin, indexEnd + 4).trim(); break; } else if (indexExtension != -1) { // We get parent directory full path in shortname thanks the %~s1 in the script lineDirectory = line.substring(indexExtension, line.length()).trim(); } } } shortname = lineDirectory + "\\" + shortname; process.destroy(); } catch (Exception e) { throw new JajukRuntimeException("Cannot convert the filename to 8.3 format", e); } return shortname; }
From source file:org.apache.accumulo.test.functional.MonitorLoggingIT.java
@Test public void logToMonitor() throws Exception { // Start the monitor. log.debug("Starting Monitor"); Process monitor = cluster.exec(Monitor.class); // Get monitor location to ensure it is running. String monitorLocation = null; for (int i = 0; i < NUM_LOCATION_PASSES; i++) { Thread.sleep(LOCATION_DELAY_SECS * 1000); try {/*from w w w . j a v a 2s . co m*/ monitorLocation = getMonitor(); break; } catch (KeeperException e) { log.debug("Monitor not up yet, trying again in " + LOCATION_DELAY_SECS + " secs"); } } assertNotNull("Monitor failed to start within " + (LOCATION_DELAY_SECS * NUM_LOCATION_PASSES) + " secs", monitorLocation); log.debug("Monitor running at " + monitorLocation); // The tserver has to observe that the log-forwarding address // changed in ZooKeeper. If we cause the error before the tserver // updates, we'll never see the error on the monitor. Thread.sleep(10000); // Attempt a scan with an invalid iterator to force a log message in the monitor. try { Connector c = getConnector(); Scanner s = c.createScanner("accumulo.root", new Authorizations()); IteratorSetting cfg = new IteratorSetting(100, "incorrect", "java.lang.String"); s.addScanIterator(cfg); s.iterator().next(); } catch (RuntimeException e) { // expected, the iterator was bad } String result = ""; while (true) { Thread.sleep(LOCATION_DELAY_SECS * 1000); // extra precaution to ensure monitor has opportunity to log // Verify messages were received at the monitor. URL url = new URL("http://" + monitorLocation + "/log"); log.debug("Fetching web page " + url); result = FunctionalTestUtils.readAll(url.openStream()); if (result.contains("<pre class='logevent'>")) { break; } log.debug("No messages found, waiting a little longer..."); } assertTrue("No log messages found", result.contains("<pre class='logevent'>")); // Shutdown cleanly. log.debug("Stopping mini accumulo cluster"); Process shutdown = cluster.exec(Admin.class, "stopAll"); shutdown.waitFor(); assertTrue(shutdown.exitValue() == 0); log.debug("success!"); monitor.destroy(); }