List of usage examples for java.lang ProcessBuilder start
public Process start() throws IOException
From source file:eu.abc4trust.cryptoEngine.uprove.util.UProveLauncher.java
public void start(int port, String name) { this.startCalled = true; // System.out.println("UProveLauncher.start - instance : " + this + // " - port : " + launchName + " :" + launchPort + " - is stopped == " + // stopped + " - uproveProcess " + this.uproveProcess ); ProcessBuilder processBuilder; if (this.isWindows()) { processBuilder = new ProcessBuilder(this.WINDOWS_COMMAND); } else {/*from w ww .ja va 2 s .com*/ processBuilder = new ProcessBuilder(this.NON_WINDOWS_COMMAND); } processBuilder.command().add("" + port); //Map<String, String> env = processBuilder.environment(); //env.clear(); processBuilder.directory(this.workingDirectory); try { this.uproveProcess = processBuilder.start(); // System.out.println(this.uproveProcess.exitValue()); InputStream is = this.uproveProcess.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line; String terminationString = "Press Enter to exit"; boolean done = false; while (!done) { line = br.readLine(); if (line != null) { System.out.println(line); done = line.endsWith(terminationString); } else { System.out.println("UProveLauncher - we get null on stdout from process - process has died.."); break; } } this.debugOutputCollector = new DebugOutputCollector(this.uproveProcess, name); this.debugOutput = new Thread(this.debugOutputCollector, "DebugCollector"); if (done) this.debugOutput.start(); // System.out.println("process started"); } catch (IOException ex) { throw new RuntimeException(ex); } }
From source file:org.generationcp.ibpworkbench.launcher.Launcher.java
protected void launchMySQLService() { ProcessBuilder pb = new ProcessBuilder("NET", "start", "MySQLIBWS"); try {/*from ww w . ja va 2 s . c om*/ Process process = pb.start(); if (process != null) { process.waitFor(); } } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } }
From source file:de.huberlin.wbi.hiway.common.Worker.java
private int exec() { File script = new File("./" + containerId); script.setExecutable(true);/* w ww . j a v a 2 s .c om*/ ProcessBuilder processBuilder = new ProcessBuilder(script.getPath()); processBuilder.directory(new File(".")); Process process; int exitValue = -1; try { File stdOutFile = new File(Invocation.STDOUT_FILENAME); File stdErrFile = new File(Invocation.STDERR_FILENAME); processBuilder.redirectOutput(stdOutFile); processBuilder.redirectError(stdErrFile); process = processBuilder.start(); exitValue = process.waitFor(); } catch (IOException | InterruptedException e) { e.printStackTrace(); System.exit(-1); } return exitValue; }
From source file:com.frostwire.gui.updates.InstallerUpdater.java
private void showUpdateMessage() { GUIMediator.safeInvokeLater(new Runnable() { public void run() { if (_executableFile == null) { return; }// ww w .ja v a 2s . c o m int result = JOptionPane.showConfirmDialog(null, _updateMessage.getMessageInstallerReady(), I18n.tr("Update"), JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE); if (result == JOptionPane.YES_OPTION) { try { if (OSUtils.isWindows()) { String[] commands = new String[] { "CMD.EXE", "/C", _executableFile.getAbsolutePath() }; ProcessBuilder pbuilder = new ProcessBuilder(commands); pbuilder.start(); } else if (OSUtils.isLinux() && OSUtils.isUbuntu()) { String[] commands = new String[] { "gdebi-gtk", _executableFile.getAbsolutePath() }; ProcessBuilder pbuilder = new ProcessBuilder(commands); pbuilder.start(); } else if (OSUtils.isMacOSX()) { String[] mountCommand = new String[] { "hdiutil", "attach", _executableFile.getAbsolutePath() }; String[] finderShowCommand = new String[] { "open", "/Volumes/" + FilenameUtils.getBaseName(_executableFile.getName()) }; ProcessBuilder pbuilder = new ProcessBuilder(mountCommand); Process mountingProcess = pbuilder.start(); mountingProcess.waitFor(); pbuilder = new ProcessBuilder(finderShowCommand); pbuilder.start(); } GUIMediator.shutdown(); } catch (Throwable e) { LOG.error("Unable to launch new installer", e); } } } }); }
From source file:com.nabla.project.application.tool.runner.ServiceInvoker.java
private void invokeInNewJVM(MethodInvocation invocation) { try {// ww w . ja v a 2s. c o m checkInvocationArgumentsForJVMTransfer(invocation.getArguments()); String classpath = System.getProperty("java.class.path"); if (newVMClasspathRoot != null) { classpath = generateClassPath(newVMClasspathRoot); } ProcessBuilder pb = new ProcessBuilder(new String[] { "java", "-classpath", classpath, "com.nabla.project.application.tool.runner.ServiceRunner", newVMconfigFileName, newVMServiceBeanName, invocation.getMethod().getName() }); Process p = pb.start(); ObjectOutputStream oos = new ObjectOutputStream(p.getOutputStream()); oos.writeObject(invocation.getArguments()); oos.flush(); } catch (Exception ioe) { throw new RuntimeException(ioe); } }
From source file:jenkins.plugins.asqatasun.AsqatasunRunner.java
public void callService() throws IOException, InterruptedException { File logFile = AsqatasunRunnerBuilder.createTempFile(contextDir, "log-" + new Random().nextInt() + ".log", "");/*from w ww . j a va 2 s . co m*/ File scenarioFile = AsqatasunRunnerBuilder.createTempFile(contextDir, scenarioName + "_#" + buildNumber, AsqatasunRunnerBuilder.forceVersion1ToScenario(scenario)); ProcessBuilder pb = new ProcessBuilder(tgScriptName, "-f", firefoxPath, "-r", referential, "-l", level, "-d", displayPort, "-x", xmxValue, "-o", logFile.getAbsolutePath(), "-t", "Scenario", scenarioFile.getAbsolutePath()); pb.directory(contextDir); pb.redirectErrorStream(true); listener.getLogger().print("Launching asqatasun runner with the following options : "); listener.getLogger().print(pb.command()); Process p = pb.start(); p.waitFor(); extractDataAndPrintOut(logFile, listener.getLogger()); if (!isDebug) { FileUtils.forceDelete(logFile); } FileUtils.forceDelete(scenarioFile); }
From source file:com.ikanow.aleph2.harvest.logstash.services.LogstashHarvestService.java
/** Runs logstash in test mode before doing anything else, to check its formatting (otherwise deploying the config can crash the entire thread) * @param script/*from www . j a va 2 s. co m*/ * @param bucket * @param config * @param globals * @return */ protected BasicMessageBean validateLogstashConfigBeforeRunning(final String script, final DataBucketBean bucket, final LogstashBucketConfigBean config, final LogstashHarvesterConfigBean globals) { final ProcessBuilder pb = LogstashUtils.buildLogstashTest(_globals.get(), config, script, 0L, Optional.empty()); try { final Process px = pb.start(); final StringWriter outputAndError = new StringWriter(); final OutputCollectorService outAndErrorStream = new OutputCollectorService(px.getInputStream(), new PrintWriter(outputAndError)); outAndErrorStream.start(); if (!px.waitFor(60L, TimeUnit.SECONDS)) { // exited px.destroy(); } outAndErrorStream.join(); int ret_val = px.exitValue(); return ErrorUtils.buildMessage(ret_val == 0, this.getClass().getSimpleName(), "validateLogstashConfigBeforeRunning", outputAndError.toString()); } catch (Exception e) { return ErrorUtils.buildErrorMessage(this.getClass().getSimpleName(), "validateLogstashConfigBeforeRunning", ErrorUtils.getLongForm("{0}", e)); } }
From source file:com.skcraft.launcher.launch.Runner.java
@Override public Process call() throws Exception { if (!instance.isInstalled()) { throw new LauncherException("Update required", _("runner.updateRequired")); }//from w w w. j ava 2 s. c om config = launcher.getConfig(); builder = new JavaProcessBuilder(); assetsRoot = launcher.getAssets(); // Load manifiests versionManifest = mapper.readValue(instance.getVersionPath(), VersionManifest.class); // Load assets index File assetsFile = assetsRoot.getIndexPath(versionManifest); try { assetsIndex = mapper.readValue(assetsFile, AssetsIndex.class); } catch (FileNotFoundException e) { instance.setInstalled(false); Persistence.commitAndForget(instance); throw new LauncherException("Missing assets index " + assetsFile.getAbsolutePath(), _("runner.missingAssetsIndex", instance.getTitle(), assetsFile.getAbsolutePath())); } catch (IOException e) { instance.setInstalled(false); Persistence.commitAndForget(instance); throw new LauncherException("Corrupt assets index " + assetsFile.getAbsolutePath(), _("runner.corruptAssetsIndex", instance.getTitle(), assetsFile.getAbsolutePath())); } // Copy over assets to the tree try { AssetsRoot.AssetsTreeBuilder assetsBuilder = assetsRoot.createAssetsBuilder(versionManifest); progress = assetsBuilder; virtualAssetsDir = assetsBuilder.build(); } catch (LauncherException e) { instance.setInstalled(false); Persistence.commitAndForget(instance); throw e; } progress = new DefaultProgress(0.9, _("runner.collectingArgs")); addJvmArgs(); addLibraries(); addJarArgs(); addProxyArgs(); addWindowArgs(); addPlatformArgs(); builder.classPath(getJarPath()); builder.setMainClass(versionManifest.getMainClass()); callLaunchModifier(); ProcessBuilder processBuilder = new ProcessBuilder(builder.buildCommand()); processBuilder.directory(instance.getContentDir()); Runner.log.info("Launching: " + builder); checkInterrupted(); progress = new DefaultProgress(1, _("runner.startingJava")); return processBuilder.start(); }
From source file:de.teamgrit.grit.checking.compile.HaskellCompileChecker.java
/** * checkProgram invokes the Haskell compiler on a given file and reports * the output.//from www .j av a 2s . com * * @param pathToProgramFile * Specifies the file or folder containing that should be * compiled. (accepts .lhs and .hs files) * @param compilerName * The compiler to be used (usually ghc). * @param compilerFlags * Additional flags to be passed to the compiler. * @throws FileNotFoundException * Is thrown when the file in pathToProgramFile cannot be * opened * @throws BadCompilerSpecifiedException * Is thrown when the given compiler cannot be called * @return A {@link CompilerOutput} that contains all compiler messages and * flags on how the compile run went. * @throws BadFlagException * When ghc doesn't recognize a flag, this exception is thrown. */ @Override public CompilerOutput checkProgram(Path pathToProgramFile, String compilerName, List<String> compilerFlags) throws FileNotFoundException, BadCompilerSpecifiedException, BadFlagException { Process compilerProcess = null; try { // create compiler invocation. List<String> compilerInvocation = createCompilerInvocation(pathToProgramFile, compilerName, compilerFlags); ProcessBuilder compilerProcessBuilder = new ProcessBuilder(compilerInvocation); // make sure the compiler stays in its directory. compilerProcessBuilder.directory(pathToProgramFile.getParent().toFile()); compilerProcess = compilerProcessBuilder.start(); // this will never happen because createCompilerInvocation never // throws this Exception. Throw declaration needs to be in method // declaration because of the implemented Interface although we // never use it in the HaskellCompileChecker } catch (CompilerOutputFolderExistsException e) { LOGGER.severe("A problem while compiling, which never should happen, occured" + e.getMessage()); } catch (BadCompilerSpecifiedException e) { throw new BadCompilerSpecifiedException(e.getMessage()); } catch (IOException e) { // If we cannot call the compiler we return a CompilerOutput // initialized with false, false, indicating // that the compiler wasn't invoked properly and that there was no // clean Compile. CompilerOutput compilerInvokeError = new CompilerOutput(); compilerInvokeError.setClean(false); compilerInvokeError.setCompilerInvoked(false); return compilerInvokeError; } // Now we read compiler output. If everything is ok ghc reports // nothing in the errorStream. InputStream compilerOutputStream = compilerProcess.getErrorStream(); InputStreamReader compilerStreamReader = new InputStreamReader(compilerOutputStream); BufferedReader compilerOutputBuffer = new BufferedReader(compilerStreamReader); String line; CompilerOutput compilerOutput = new CompilerOutput(); compilerOutput.setCompilerInvoked(true); List<String> compilerOutputLines = new LinkedList<>(); try { while ((line = compilerOutputBuffer.readLine()) != null) { compilerOutputLines.add(line); } // Errors are separated via an empty line (""). But after the // the last error the OutputBuffer has nothing more to write. // In order to recognize the last error we insert an empty String // at the end of the list. // Only needs to be done when there are errors. if (compilerOutputLines.size() != 0) { line = ""; compilerOutputLines.add(line); } compilerOutputStream.close(); compilerStreamReader.close(); compilerOutputBuffer.close(); compilerProcess.destroy(); } catch (IOException e) { // Reading might go wrong here if ghc should unexpectedly die LOGGER.severe("Error while reading from compiler stream."); compilerOutput.setClean(false); compilerOutput.setCompileStreamBroken(true); return compilerOutput; } // ghc -c generates a .o(object) and a .hi(haskell interface) file. // But we don't need those files so they can be deleted. // The generated files have the same name like our input file so we // can just exchange the file endings in order to get the // correct file paths for deletion if (Files.isDirectory(pathToProgramFile, LinkOption.NOFOLLOW_LINKS)) { // we use a file walker in order to find all files in the folder // and its subfolders RegexDirectoryWalker dirWalker = new RegexDirectoryWalker(".+\\.([Ll])?[Hh][Ss]"); try { Files.walkFileTree(pathToProgramFile, dirWalker); } catch (IOException e) { LOGGER.severe("Could not walk submission " + pathToProgramFile.toString() + " while building copiler invocation: " + e.getMessage()); } for (Path candidatePath : dirWalker.getFoundFiles()) { File candidateFile = candidatePath.toFile(); if (!candidateFile.isDirectory()) { String extension = FilenameUtils.getExtension(candidateFile.toString()); if (extension.matches("[Ll]?[Hh][Ss]")) { File ghcGeneratedObject = new File( FilenameUtils.removeExtension(candidateFile.toString()) + ".o"); File ghcGeneratedInterface = new File( FilenameUtils.removeExtension(candidateFile.toString()) + ".hi"); ghcGeneratedObject.delete(); ghcGeneratedInterface.delete(); } } } } else { String extension = FilenameUtils.getExtension(pathToProgramFile.toString()); if (extension.matches("[Ll]?[Hh][Ss]")) { File ghcGeneratedObject = new File( FilenameUtils.removeExtension(pathToProgramFile.toString()) + ".o"); File ghcGeneratedInterface = new File( FilenameUtils.removeExtension(pathToProgramFile.toString()) + ".hi"); ghcGeneratedObject.delete(); ghcGeneratedInterface.delete(); } } // if there are no errors there is no Output to handle if (compilerOutputLines.size() != 0) { compilerOutput = splitCompilerOutput(compilerOutputLines, compilerOutput); } else { compilerOutput.setClean(true); } return compilerOutput; }
From source file:org.obiba.onyx.jade.instrument.gehealthcare.CardiosoftInstrumentRunner.java
private void initParticipantData() { File participantDataFile = new File(getDatabasePath() + getBtrRecordFileName()); try {/*from w w w .j av a 2 s . c o m*/ Map<String, Data> inputData = instrumentExecutionService.getInputParametersValue( "INPUT_PARTICIPANT_BARCODE", "INPUT_PARTICIPANT_LAST_NAME", "INPUT_PARTICIPANT_FIRST_NAME", "INPUT_PARTICIPANT_GENDER", "INPUT_PARTICIPANT_HEIGHT", "INPUT_PARTICIPANT_WEIGHT", "INPUT_PARTICIPANT_ETHNIC_GROUP", "INPUT_PARTICIPANT_BIRTH_YEAR", "INPUT_PARTICIPANT_BIRTH_MONTH", "INPUT_PARTICIPANT_BIRTH_DAY", "INPUT_PARTICIPANT_PACEMAKER"); FileOutputStream participantDataOuputStream = new FileOutputStream(participantDataFile); BtrInputGenerator inputGenerator = new BtrInputGenerator(); participantDataOuputStream.write((inputGenerator.generateByteBuffer(inputData)).array()); participantDataOuputStream.close(); } catch (Exception ex) { throw new RuntimeException("Error writing ecg participant data file: ", ex); } List<String> command = new ArrayList<String>(); command.add("cmd"); command.add("/c"); command.add( getExecutableForParticipantInfo() + " " + getBtrRecordFileName() + " " + getBtrDatabaseFileName()); ProcessBuilder builder = new ProcessBuilder(command); builder.directory(new File(getDatabasePath())); try { log.info("Executing command '{}'", command); Process process = builder.start(); log.info("Waiting for process '{}'", process); process.waitFor(); } catch (IOException e) { log.error("Could not create external process.", e); throw new RuntimeException(e); } catch (InterruptedException e) { log.error("Error waiting for process to end.", e); throw new RuntimeException(e); } }