List of usage examples for java.lang ProcessBuilder redirectErrorStream
boolean redirectErrorStream
To view the source code for java.lang ProcessBuilder redirectErrorStream.
Click Source Link
From source file:com.lenovo.tensorhusky.common.utils.Shell.java
/** * Run a command// w w w .j av a2s .c o m */ private void runCommand() throws IOException { ProcessBuilder builder = new ProcessBuilder(getExecString()); Timer timeOutTimer = null; ShellTimeoutTimerTask timeoutTimerTask = null; timedOut = new AtomicBoolean(false); completed = new AtomicBoolean(false); if (environment != null) { builder.environment().putAll(this.environment); } if (dir != null) { builder.directory(this.dir); } builder.redirectErrorStream(redirectErrorStream); if (Shell.WINDOWS) { synchronized (WindowsProcessLaunchLock) { // To workaround the race condition issue with child processes // inheriting unintended handles during process launch that can // lead to hangs on reading output and error streams, we // serialize process creation. More info available at: // http://support.microsoft.com/kb/315939 process = builder.start(); } } else { process = builder.start(); } if (timeOutInterval > 0) { timeOutTimer = new Timer("Shell command timeout"); timeoutTimerTask = new ShellTimeoutTimerTask(this); // One time scheduling. timeOutTimer.schedule(timeoutTimerTask, timeOutInterval); } final BufferedReader errReader = new BufferedReader( new InputStreamReader(process.getErrorStream(), Charset.defaultCharset())); final BufferedReader inReader = new BufferedReader( new InputStreamReader(process.getInputStream(), Charset.defaultCharset())); final StringBuffer errMsg = new StringBuffer(); // read error and input streams as this would free up the buffers // free the error stream buffer Thread errThread = new Thread() { @Override public void run() { try { String line = errReader.readLine(); while ((line != null) && !isInterrupted()) { errMsg.append(line); errMsg.append(System.getProperty("line.separator")); line = errReader.readLine(); } } catch (IOException ioe) { LOG.warn("Error reading the error stream", ioe); } } }; try { errThread.start(); } catch (IllegalStateException ise) { } catch (OutOfMemoryError oe) { LOG.error("Caught " + oe + ". One possible reason is that ulimit" + " setting of 'max user processes' is too low. If so, do" + " 'ulimit -u <largerNum>' and try again."); throw oe; } try { parseExecResult(inReader); // parse the output // clear the input stream buffer String line = inReader.readLine(); while (line != null) { line = inReader.readLine(); } // wait for the process to finish and check the exit code exitCode = process.waitFor(); // make sure that the error thread exits joinThread(errThread); completed.set(true); // the timeout thread handling // taken care in finally block if (exitCode != 0) { throw new ExitCodeException(exitCode, errMsg.toString()); } } catch (InterruptedException ie) { throw new IOException(ie.toString()); } finally { if (timeOutTimer != null) { timeOutTimer.cancel(); } // close the input stream try { // JDK 7 tries to automatically drain the input streams for us // when the process exits, but since close is not synchronized, // it creates a race if we close the stream first and the same // fd is recycled. the stream draining thread will attempt to // drain that fd!! it may block, OOM, or cause bizarre behavior // see: https://bugs.openjdk.java.net/browse/JDK-8024521 // issue is fixed in build 7u60 InputStream stdout = process.getInputStream(); synchronized (stdout) { inReader.close(); } } catch (IOException ioe) { LOG.warn("Error while closing the input stream", ioe); } if (!completed.get()) { errThread.interrupt(); joinThread(errThread); } try { InputStream stderr = process.getErrorStream(); synchronized (stderr) { errReader.close(); } } catch (IOException ioe) { LOG.warn("Error while closing the error stream", ioe); } process.destroy(); lastTime = Time.monotonicNow(); } }
From source file:cn.org.once.cstack.service.impl.ScriptingServiceImpl.java
public void execute(String scriptContent, String login, String password) throws ServiceException { logger.info(scriptContent);// w w w . jav a 2s .c om File tmpFile = null; FileWriter fileWriter = null; BufferedWriter writer = null; ProcessBuilder processBuilder = null; try { tmpFile = File.createTempFile(login, ".cmdFile"); fileWriter = new FileWriter(tmpFile); writer = new BufferedWriter(fileWriter); String commandConnect = CONNECT_CMD.replace("#USER", login).replace("#PASSWORD", password) .replace("#HOST", host); logger.debug(commandConnect); writer.append(commandConnect); writer.newLine(); writer.append(scriptContent); writer.newLine(); writer.append(DISCONNECT_CMD); writer.flush(); logger.debug(writer.toString()); File fileCLI = new File(pathCLI); if (!fileCLI.exists()) { System.out.println("Error ! "); StringBuilder msgError = new StringBuilder(512); msgError.append( "\nPlease run manually (1) : mkdir -p " + pathCLI.substring(0, pathCLI.lastIndexOf("/"))); msgError.append( "\nPlease run manually (2) : wget https://github.com/Treeptik/cloudunit/releases/download/1.0/CloudUnitCLI.jar -O " + pathCLI); throw new ServiceException(msgError.toString()); } processBuilder = new ProcessBuilder("java", "-jar", pathCLI, "--cmdfile", tmpFile.getAbsolutePath()); processBuilder.redirectErrorStream(true); Process process = processBuilder.start(); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line = ""; try { while ((line = reader.readLine()) != null) { logger.info(line); if (line.contains("not found")) throw new ServiceException("Syntax error : " + line); if (line.contains("Invalid or corrupt jarfile")) throw new ServiceException("Invalid or corrupt jarfile"); } } finally { reader.close(); } } catch (IOException e) { StringBuilder msgError = new StringBuilder(512); msgError.append("login=").append(login); msgError.append(", password=").append(password); msgError.append(", scriptContent=").append(scriptContent); logger.error(msgError.toString(), e); } finally { try { fileWriter.close(); } catch (Exception ignore) { } try { writer.close(); } catch (Exception ignore) { } } }
From source file:org.esa.s2tbx.dataio.s2.S2TileOpImage.java
protected void decompressTile(final File outputFile, int jp2TileX, int jp2TileY) throws IOException { final int tileIndex = tileLayout.numXTiles * jp2TileY + jp2TileX; ProcessBuilder builder; if (S2Config.OPJ_DECOMPRESSOR_EXE != null) { if (org.apache.commons.lang.SystemUtils.IS_OS_WINDOWS) { String inputFileName = Utils.GetIterativeShortPathName(imageFile.getPath()); String outputFileName = outputFile.getPath(); if (inputFileName.length() == 0) { inputFileName = imageFile.getPath(); }//from w w w . j av a 2 s .co m Guardian.assertTrue("Image file exists", new File(inputFileName).exists()); builder = new ProcessBuilder(S2Config.OPJ_DECOMPRESSOR_EXE, "-i", inputFileName, "-o", outputFileName, "-r", getLevel() + "", "-t", tileIndex + ""); } else { SystemUtils.LOG.fine("Writing to " + outputFile.getPath()); Guardian.assertTrue("Image file exists", imageFile.exists()); builder = new ProcessBuilder(S2Config.OPJ_DECOMPRESSOR_EXE, "-i", imageFile.getPath(), "-o", outputFile.getPath(), "-r", getLevel() + "", "-t", tileIndex + ""); } } else { throw new UnexpectedException("OpenJpeg decompressor is not set"); } builder = builder.directory(cacheDir); try { builder.redirectErrorStream(true); CommandOutput result = OpenJpegUtils.runProcess(builder); final int exitCode = result.getErrorCode(); if (exitCode != 0) { SystemUtils.LOG.severe(String.format( "Failed to uncompress tile: %s, exitCode = %d, command = [%s], command stdoutput = [%s], command stderr = [%s]", imageFile.getPath(), exitCode, builder.command().toString(), result.getTextOutput(), result.getErrorOutput())); } } catch (InterruptedException e) { SystemUtils.LOG.severe("Process was interrupted, InterruptedException: " + e.getMessage()); } }
From source file:se.sics.kompics.p2p.experiment.dsl.SimulationScenario.java
/** * Launch simulation.//from www.j a va 2s . c o m * * @param main * the main * @param args * the args */ private void launchSimulation(Class<? extends ComponentDefinition> main, String... args) { LinkedList<String> arguments = new LinkedList<String>(); String java = System.getProperty("java.home"); String sep = System.getProperty("file.separator"); String pathSep = System.getProperty("path.separator"); java += sep + "bin" + sep + "java"; if (System.getProperty("os.name").startsWith("Windows")) { arguments.add("\"" + java + "\""); } else { arguments.add(java); } arguments.add("-Xbootclasspath:" + directory + bootString() + pathSep + directory + "application"); arguments.add("-classpath"); arguments.add(directory + "application"); arguments.addAll(getJvmArgs(args)); arguments.add("-Dscenario=" + System.getProperty("scenario")); // add configuration properties for (Object key : System.getProperties().keySet()) { if (((String) key).contains("configuration")) arguments.add("-D" + key + "=" + System.getProperty((String) key)); } arguments.add(main.getName()); arguments.addAll(getApplicationArgs(args)); ProcessBuilder pb = new ProcessBuilder(arguments); pb.redirectErrorStream(true); saveSimulationCommandLine(arguments); try { Process process = pb.start(); BufferedReader out = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; do { line = out.readLine(); if (line != null) { System.out.println(line); } } while (line != null); } catch (IOException e) { throw new RuntimeException("Cannot start simulation process", e); } }
From source file:org.jumpmind.symmetric.service.impl.DataService.java
private void insertCreateSchemaScriptPriorToReload(Node targetNode, String nodeIdRecord, long loadId, String createBy, boolean transactional, ISqlTransaction transaction) { String dumpCommand = parameterService.getString(ParameterConstants.INITIAL_LOAD_SCHEMA_DUMP_COMMAND); String loadCommand = parameterService.getString(ParameterConstants.INITIAL_LOAD_SCHEMA_LOAD_COMMAND); if (isNotBlank(dumpCommand) && isNotBlank(loadCommand)) { try {/* ww w .j a v a2s . c om*/ log.info("Dumping schema using the following dump command: " + dumpCommand); ProcessBuilder pb = new ProcessBuilder(FormatUtils.splitOnSpacePreserveQuotedStrings(dumpCommand)); pb.redirectErrorStream(true); Process process = pb.start(); java.io.InputStream is = process.getInputStream(); java.io.StringWriter ow = new java.io.StringWriter(); IOUtils.copy(is, ow); String output = ow.toString(); output = StringEscapeUtils.escapeJavaScript(output); String script = IOUtils.toString(getClass().getResourceAsStream("/load-schema-at-target.bsh")); script = script.replace("${data}", output); script = script.replace("${commands}", formatCommandForScript(loadCommand)); if (process.waitFor() != 0) { throw new IoException(output.toString()); } log.info("Inserting script to load dump at client"); engine.getDataService().insertScriptEvent(transaction, Constants.CHANNEL_RELOAD, targetNode, script, true, loadId, "reload listener"); } catch (Exception e) { throw new IoException(e); } } }
From source file:org.codehaus.enunciate.modules.amf.AMFDeploymentModule.java
/** * Invokes the flex compiler on the apps specified in the configuration file. *///from w w w. j av a 2 s . c o m protected void doFlexCompile() throws EnunciateException, IOException { File swcFile = null; File asSources = null; Enunciate enunciate = getEnunciate(); if (isSwcDownloadable() || !flexApps.isEmpty()) { if (this.flexHome == null) { throw new EnunciateException( "To compile a flex app you must specify the Flex SDK home directory, either in configuration, by setting the FLEX_HOME environment variable, or setting the 'flex.home' system property."); } File flexHomeDir = new File(this.flexHome); if (!flexHomeDir.exists()) { throw new EnunciateException("Flex home not found ('" + flexHomeDir.getAbsolutePath() + "')."); } File javaBinDir = new File(System.getProperty("java.home"), "bin"); File javaExecutable = new File(javaBinDir, "java"); if (!javaExecutable.exists()) { //append the "exe" for windows users. javaExecutable = new File(javaBinDir, "java.exe"); } String javaCommand = javaExecutable.getAbsolutePath(); if (!javaExecutable.exists()) { warn("No java executable found in %s. We'll just hope the environment is set up to execute 'java'...", javaBinDir.getAbsolutePath()); javaCommand = "java"; } int compileCommandIndex; int outputFileIndex; int sourcePathIndex; int mainMxmlPathIndex; List<String> commandLine = new ArrayList<String>(); int argIndex = 0; commandLine.add(argIndex++, javaCommand); for (String jvmarg : this.compilerConfig.getJVMArgs()) { commandLine.add(argIndex++, jvmarg); } commandLine.add(argIndex++, "-cp"); File flexHomeLib = new File(flexHomeDir, "lib"); if (!flexHomeLib.exists()) { throw new EnunciateException("File not found: " + flexHomeLib); } else { StringBuilder builder = new StringBuilder(); Iterator<File> flexLibIt = Arrays.asList(flexHomeLib.listFiles()).iterator(); while (flexLibIt.hasNext()) { File flexJar = flexLibIt.next(); if (flexJar.getAbsolutePath().endsWith("jar")) { builder.append(flexJar.getAbsolutePath()); if (flexLibIt.hasNext()) { builder.append(File.pathSeparatorChar); } } else { debug("File %s will not be included on the classpath because it's not a jar.", flexJar); } } commandLine.add(argIndex++, builder.toString()); } compileCommandIndex = argIndex; commandLine.add(argIndex++, null); commandLine.add(argIndex++, "-output"); outputFileIndex = argIndex; commandLine.add(argIndex++, null); if (compilerConfig.getFlexConfig() == null) { compilerConfig.setFlexConfig(new File(new File(flexHome, "frameworks"), "flex-config.xml")); } if (compilerConfig.getFlexConfig().exists()) { commandLine.add(argIndex++, "-load-config"); commandLine.add(argIndex++, compilerConfig.getFlexConfig().getAbsolutePath()); } else { warn("Configured flex configuration file %s doesn't exist. Ignoring...", compilerConfig.getFlexConfig()); } if (compilerConfig.getContextRoot() == null) { if (getEnunciate().getConfig().getLabel() != null) { compilerConfig.setContextRoot("/" + getEnunciate().getConfig().getLabel()); } else { compilerConfig.setContextRoot("/enunciate"); } } commandLine.add(argIndex++, "-compiler.context-root"); commandLine.add(argIndex++, compilerConfig.getContextRoot()); if (compilerConfig.getLocale() != null) { commandLine.add(argIndex++, "-compiler.locale"); commandLine.add(argIndex++, compilerConfig.getLocale()); } if (compilerConfig.getLicenses().size() > 0) { commandLine.add(argIndex++, "-licenses.license"); for (License license : compilerConfig.getLicenses()) { commandLine.add(argIndex++, license.getProduct()); commandLine.add(argIndex++, license.getSerialNumber()); } } if (compilerConfig.getOptimize() != null && compilerConfig.getOptimize()) { commandLine.add(argIndex++, "-compiler.optimize"); } if (compilerConfig.getDebug() != null && compilerConfig.getDebug()) { commandLine.add(argIndex++, "-compiler.debug=true"); } if (compilerConfig.getStrict() != null && compilerConfig.getStrict()) { commandLine.add(argIndex++, "-compiler.strict"); } if (compilerConfig.getUseNetwork() != null && compilerConfig.getUseNetwork()) { commandLine.add(argIndex++, "-use-network"); } if (compilerConfig.getIncremental() != null && compilerConfig.getIncremental()) { commandLine.add(argIndex++, "-compiler.incremental"); } if (compilerConfig.getShowActionscriptWarnings() != null && compilerConfig.getShowActionscriptWarnings()) { commandLine.add(argIndex++, "-show-actionscript-warnings"); } if (compilerConfig.getShowBindingWarnings() != null && compilerConfig.getShowBindingWarnings()) { commandLine.add(argIndex++, "-show-binding-warnings"); } if (compilerConfig.getShowDeprecationWarnings() != null && compilerConfig.getShowDeprecationWarnings()) { commandLine.add(argIndex++, "-show-deprecation-warnings"); } for (String arg : this.compilerConfig.getArgs()) { commandLine.add(argIndex++, arg); } commandLine.add(argIndex++, "-compiler.services"); File xmlGenerateDir = getXMLGenerateDir(); commandLine.add(argIndex++, new File(xmlGenerateDir, "merged-services-config.xml").getAbsolutePath()); commandLine.add(argIndex, "-include-sources"); File clientSideGenerateDir = getClientSideGenerateDir(); commandLine.add(argIndex + 1, clientSideGenerateDir.getAbsolutePath()); String swcName = getSwcName(); if (swcName == null) { String label = "enunciate"; if (getLabel() != null) { label = getLabel(); } else if ((enunciate.getConfig() != null) && (enunciate.getConfig().getLabel() != null)) { label = enunciate.getConfig().getLabel(); } swcName = label + "-as3-client.swc"; } File swcCompileDir = getSwcCompileDir(); swcFile = new File(swcCompileDir, swcName); boolean swcUpToDate = swcFile.exists() && enunciate.isUpToDate(xmlGenerateDir, swcCompileDir) && enunciate.isUpToDate(clientSideGenerateDir, swcCompileDir); if (!swcUpToDate) { commandLine.set(compileCommandIndex, compilerConfig.getSwcCompileCommand()); commandLine.set(outputFileIndex, swcFile.getAbsolutePath()); debug("Compiling %s for the client-side ActionScript classes...", swcFile.getAbsolutePath()); if (enunciate.isDebug()) { StringBuilder command = new StringBuilder(); for (String commandPiece : commandLine) { command.append(' ').append(commandPiece); } debug("Executing SWC compile for client-side actionscript with the command: %s", command); } compileSwc(commandLine); } else { info("Skipping compilation of %s as everything appears up-to-date...", swcFile.getAbsolutePath()); } //swc is compiled while (commandLine.size() > argIndex) { //remove the compc-specific options... commandLine.remove(argIndex); } if (compilerConfig.getProfile() != null && compilerConfig.getProfile()) { commandLine.add(argIndex++, "-compiler.profile"); } if (compilerConfig.getWarnings() != null && compilerConfig.getWarnings()) { commandLine.add(argIndex++, "-warnings"); } commandLine.add(argIndex++, "-source-path"); commandLine.add(argIndex++, clientSideGenerateDir.getAbsolutePath()); commandLine.add(argIndex++, "-source-path"); sourcePathIndex = argIndex; commandLine.add(argIndex++, null); commandLine.add(argIndex++, "--"); mainMxmlPathIndex = argIndex; commandLine.add(argIndex++, null); commandLine.set(compileCommandIndex, compilerConfig.getFlexCompileCommand()); File outputDirectory = getSwfCompileDir(); debug("Creating output directory: " + outputDirectory); outputDirectory.mkdirs(); for (FlexApp flexApp : flexApps) { String mainMxmlPath = flexApp.getMainMxmlFile(); if (mainMxmlPath == null) { throw new EnunciateException("A main MXML file for the flex app '" + flexApp.getName() + "' must be supplied with the 'mainMxmlFile' attribute."); } File mainMxmlFile = enunciate.resolvePath(mainMxmlPath); if (!mainMxmlFile.exists()) { throw new EnunciateException( "Main MXML file for the flex app '" + flexApp.getName() + "' doesn't exist."); } File swfDir = outputDirectory; if (flexApp.getOutputPath() != null && !"".equals(flexApp.getOutputPath())) { swfDir = new File(outputDirectory, flexApp.getOutputPath()); swfDir.mkdirs(); } File swfFile = new File(swfDir, flexApp.getName() + ".swf"); File appSrcDir = enunciate.resolvePath(flexApp.getSrcDir()); String swfFilePath = swfFile.getAbsolutePath(); boolean swfUpToDate = swfFile.exists() && mainMxmlFile.lastModified() < swfFile.lastModified() && enunciate.isUpToDate(appSrcDir, swfFile); if (!swfUpToDate) { commandLine.set(outputFileIndex, swfFilePath); commandLine.set(mainMxmlPathIndex, mainMxmlFile.getAbsolutePath()); commandLine.set(sourcePathIndex, appSrcDir.getAbsolutePath()); debug("Compiling %s ...", swfFilePath); if (enunciate.isDebug()) { StringBuilder command = new StringBuilder(); for (String commandPiece : commandLine) { command.append(' ').append(commandPiece); } debug("Executing flex compile for module %s with the command: %s", flexApp.getName(), command); } ProcessBuilder processBuilder = new ProcessBuilder( commandLine.toArray(new String[commandLine.size()])); processBuilder.directory(getSwfCompileDir()); processBuilder.redirectErrorStream(true); Process process = processBuilder.start(); BufferedReader procReader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line = procReader.readLine(); while (line != null) { info(line); line = procReader.readLine(); } int procCode; try { procCode = process.waitFor(); } catch (InterruptedException e1) { throw new EnunciateException("Unexpected inturruption of the Flex compile process."); } if (procCode != 0) { throw new EnunciateException("Flex compile failed for module " + flexApp.getName()); } } else { info("Skipping compilation of %s as everything appears up-to-date...", swfFilePath); } } } if (isAsSourcesDownloadable()) { String label = "enunciate"; if ((enunciate.getConfig() != null) && (enunciate.getConfig().getLabel() != null)) { label = enunciate.getConfig().getLabel(); } asSources = new File(new File(getCompileDir(), "src"), label + "-as3-sources.zip"); enunciate.zip(asSources, getClientSideGenerateDir()); } if (swcFile != null || asSources != null) { List<ArtifactDependency> clientDeps = new ArrayList<ArtifactDependency>(); BaseArtifactDependency as3Dependency = new BaseArtifactDependency(); as3Dependency.setId("flex-sdk"); as3Dependency.setArtifactType("zip"); as3Dependency.setDescription("The flex SDK."); as3Dependency.setURL("http://www.adobe.com/products/flex/"); as3Dependency.setVersion("2.0.1"); clientDeps.add(as3Dependency); ClientLibraryArtifact as3ClientArtifact = new ClientLibraryArtifact(getName(), "as3.client.library", "ActionScript 3 Client Library"); as3ClientArtifact.setPlatform("Adobe Flex"); //read in the description from file: as3ClientArtifact.setDescription(readResource("library_description.fmt")); as3ClientArtifact.setDependencies(clientDeps); if (swcFile != null) { NamedFileArtifact clientArtifact = new NamedFileArtifact(getName(), "as3.client.swc", swcFile); clientArtifact.setDescription("The compiled SWC."); clientArtifact.setPublic(false); clientArtifact.setArtifactType(ArtifactType.binaries); as3ClientArtifact.addArtifact(clientArtifact); enunciate.addArtifact(clientArtifact); } if (asSources != null) { NamedFileArtifact clientArtifact = new NamedFileArtifact(getName(), "as3.client.sources", asSources); clientArtifact.setDescription("The client-side ActionScript sources."); clientArtifact.setPublic(false); clientArtifact.setArtifactType(ArtifactType.sources); as3ClientArtifact.addArtifact(clientArtifact); enunciate.addArtifact(clientArtifact); } enunciate.addArtifact(as3ClientArtifact); } }
From source file:org.testeditor.fixture.swt.SwtBotFixture.java
/** * Executes the AUT for local Debugging outsite the TE Context as an JUnit * Test./*from w w w.jav a 2 s. c o m*/ * * @param applicationPath * to AUT * @param workspace * the workspace for the testeditor_aut * @param bundleDir * Path to the Parent directory of the SWTBot agent server * bundle. * @throws Exception * on Test execution */ protected void startJUnitApplication(String applicationPath, String workspace, String bundleDir) throws Exception { try { String autConfiguration = createAUTConfiguration(applicationPath, bundleDir); ArrayList<String> list = new ArrayList<String>(); list.add(applicationPath); list.add("-clean"); list.add("-application"); list.add("org.testeditor.agent.swtbot.TestEditorSWTBotAgent"); list.add("-aut"); list.add("org.eclipse.e4.ui.workbench.swt.E4Application"); list.add("-data"); list.add(workspace); list.add("-nl"); list.add("de_de"); list.add("-configuration"); list.add(autConfiguration); ProcessBuilder builder = new ProcessBuilder(list); builder.redirectErrorStream(true); LOGGER.info("Start SWT-app-under-test"); process = builder.start(); createAndRunLoggerOnStream(process.getInputStream(), false); createAndRunLoggerOnStream(process.getErrorStream(), true); LOGGER.info("Output from SWT-app-under-test"); boolean launched = false; while (!launched) { try { Thread.sleep(100); LOGGER.info("waiting for launch"); launched = isLaunched(); } catch (InterruptedException e) { LOGGER.error("startApplication InterruptedException: ", e); } } LOGGER.info("SWT-app-under-test is ready for test"); try { Thread.sleep(500); } catch (InterruptedException e) { LOGGER.error("startApplication InterruptedException: ", e); } } catch (Exception exp) { LOGGER.error("Error Test execution: ", exp); throw exp; } }
From source file:org.testeditor.fixture.swt.SwtBotFixture.java
/** * Creates and launches the Process for the AUT. * // w ww.java2 s . c om * @throws Exception * on problems to create the AUT process. */ private void createAndLaunchProcess() throws Exception { LOGGER.trace("Start List: " + Arrays.toString(launchApplicationCommandList.toArray())); ProcessBuilder builder = new ProcessBuilder(launchApplicationCommandList); builder.redirectErrorStream(true); LOGGER.info("Start SWT-app-under-test"); process = builder.start(); createAndRunLoggerOnStream(process.getInputStream(), false); createAndRunLoggerOnStream(process.getErrorStream(), true); LOGGER.info("Output from SWT-app-under-test"); boolean launched = false; int timeOut = 0; while (!launched) { try { Thread.sleep(200); LOGGER.info("waiting for launch"); launched = isLaunched(); timeOut++; if (timeOut > 200) { stopApplication(); throw new StopTestException("Time out launching AUT."); } } catch (InterruptedException e) { LOGGER.error("startApplication InterruptedException: ", e); } } LOGGER.info("SWT-app-under-test is ready for test"); sendMessage("setTestName" + COMMAND_DELIMITER + testName); try { Thread.sleep(500); } catch (InterruptedException e) { LOGGER.error("startApplication InterruptedException: ", e); } }
From source file:net.emotivecloud.scheduler.drp4ost.OStackClient.java
public String createVM(String flavorID, String baseImageID, String vmName, String host) { // http://docs.openstack.org/essex/openstack-compute/admin/content/specify-host-to-boot-instances-on.html // nova boot --image 1 --flavor 2 --key_name test --hint force_hosts=server2 my-first-server String ret = null;/*w w w . ja v a 2 s . c om*/ try { // execution of the add command System.out.println("DRP4OST>HOST: " + host); // Create a list with command and its arguments ArrayList<String> myCmd = new ArrayList<String>(); myCmd.add("nova"); myCmd.add("boot"); myCmd.add(String.format("--flavor=%s", flavorID)); myCmd.add(String.format("--image=%s", baseImageID)); myCmd.add(String.format("--availability_zone=nova:%s", host)); myCmd.add(String.format("%s", vmName)); ProcessBuilder pb = new ProcessBuilder(myCmd); // Set up the environment to communicate with OpenStack Map<String, String> envir = pb.environment(); envir.put("OS_AUTH_URL", this.OS_AUTH_URL); envir.put("OS_TENANT_ID", this.OS_TENANT_ID); envir.put("OS_TENANT_NAME", this.OS_TENANT_NAME); envir.put("OS_USERNAME", this.OS_USERNAME); envir.put("OS_PASSWORD", this.OS_PASSWORD); envir.put("mycommand", "nova boot"); pb.redirectErrorStream(true); Process p = pb.start(); InputStream pis = p.getInputStream(); String novaOutput = ISToString(pis); System.out.println("DRP4OST-createVM > what nova boot returns me" + novaOutput); // Read the id line from the nova-client output String vmID = getIdFromNova(novaOutput); // Get Server details, that will be returned ret = getServer(vmID); pis.close(); } catch (Exception e) { e.printStackTrace(); throw new DRPOSTException("Exception creating the image", StatusCodes.BAD_REQUEST); } return ret; }
From source file:org.apache.sling.maven.slingstart.run.LauncherCallable.java
private ProcessDescription start(final File jar) throws Exception { final ProcessDescription cfg = new ProcessDescription(this.configuration.getId(), this.configuration.getFolder()); final ProcessBuilder builder = new ProcessBuilder(); final List<String> args = new ArrayList<String>(); args.add("java"); add(args, this.configuration.getVmOpts()); add(args, this.configuration.getVmDebugOpts(this.environment.getDebug())); args.add("-cp"); args.add("bin"); args.add(Main.class.getName()); // first three arguments: jar, listener port, verbose args.add(jar.getPath());//from ww w . j a v a2s. com args.add(String.valueOf(cfg.getControlListener().getPort())); args.add("true"); // from here on launchpad properties add(args, this.configuration.getOpts()); final String contextPath = this.configuration.getContextPath(); if (contextPath != null && contextPath.length() > 0 && !contextPath.equals("/")) { args.add("-r"); args.add(contextPath); } if (this.configuration.getPort() != null) { args.add("-p"); args.add(this.configuration.getPort()); } if (this.configuration.getControlPort() != null) { args.add("-j"); args.add(this.configuration.getControlPort()); } if (this.configuration.getRunmode() != null && this.configuration.getRunmode().length() > 0) { args.add("-Dsling.run.modes=" + this.configuration.getRunmode()); } if (!this.environment.isShutdownOnExit()) { args.add("start"); } builder.command(args.toArray(new String[args.size()])); builder.directory(this.configuration.getFolder()); builder.redirectErrorStream(true); builder.redirectOutput(Redirect.INHERIT); builder.redirectError(Redirect.INHERIT); logger.info("Starting Launchpad " + this.configuration.getId() + "..."); logger.debug("Launchpad cmd: " + builder.command()); logger.debug("Launchpad dir: " + builder.directory()); try { cfg.setProcess(builder.start()); } catch (final IOException e) { if (cfg.getProcess() != null) { cfg.getProcess().destroy(); cfg.setProcess(null); } throw new Exception("Could not start the Launchpad", e); } return cfg; }