List of usage examples for java.lang ProcessBuilder start
public Process start() throws IOException
From source file:io.jmnarloch.cd.go.plugin.sbt.SbtTaskExecutor.java
private int execute(ProcessBuilder builder, JobConsoleLogger console) throws IOException, InterruptedException { Process process = null;/*from ww w . j a v a2 s . co m*/ try { process = builder.start(); console.readOutputOf(process.getInputStream()); console.readErrorOf(process.getErrorStream()); return process.waitFor(); } finally { if (process != null) { process.destroy(); } } }
From source file:com.blackducksoftware.integration.hub.docker.executor.Executor.java
public String[] executeCommand(final String commandString) throws IOException, InterruptedException, HubIntegrationException { final List<String> commandStringList = Arrays.asList(commandString.split(" ")); final ProcessBuilder builder = new ProcessBuilder(); builder.command(commandStringList.toArray(new String[commandStringList.size()])); builder.directory(new File(".")); final Process process = builder.start(); final boolean finished = process.waitFor(this.commandTimeout, TimeUnit.MILLISECONDS); if (!finished) { throw new HubIntegrationException(String.format( "Execution of command %s timed out (timeout: %d milliseconds)", commandString, commandTimeout)); }//from w ww .j a va2s. c om final int errCode = process.exitValue(); if (errCode == 0) { logger.debug(String.format("Execution of command: %s: Succeeded", commandString)); } else { throw new HubIntegrationException( String.format("Execution of command: %s: Error code: %d", commandString, errCode)); } final InputStream inputStream = process.getInputStream(); final String outputString = IOUtils.toString(inputStream, StandardCharsets.UTF_8); logger.debug(String.format("Command output:/n%s", outputString)); return outputString.split(System.lineSeparator()); }
From source file:edu.pitt.dbmi.ccd.queue.task.ScheduledAlgorithJob.java
private void killJob(Long queueId) { JobQueueInfo jobQueueInfo = jobQueueInfoService.findOne(queueId); if (jobQueueInfo.getStatus() == 0) { LOGGER.info("Delete Job ID by user from queue: " + queueId); jobQueueInfoService.deleteJobById(queueId); } else {// ww w.j ava 2 s. c om Long pid = jobQueueInfo.getPid(); if (pid == null) { LOGGER.info("Delete Job ID by user from queue: " + queueId); jobQueueInfoService.deleteJobById(queueId); } else { Platform platform = Platform.detect(); System.out.println( "Processes.isProcessRunning(platform, pid):" + Processes.isProcessRunning(platform, pid)); if (Processes.isProcessRunning(platform, pid)) { /* * ISupportConfig support = null; IStreamProcessor output = * null; */ List<String> commands = new LinkedList<>(); if (platform == Platform.Windows) { // return Processes.tryKillProcess(support, platform, // output, pid.intValue()); commands.add("taskkill"); commands.add("/pid"); commands.add(String.valueOf(pid)); commands.add("/f"); commands.add("/t"); } else { // return Processes.killProcess(support, platform, // output, pid.intValue()); commands.add("kill"); commands.add("-9"); commands.add(String.valueOf(pid)); } LOGGER.info("Kill Job Queue Id: " + jobQueueInfo.getId()); jobQueueInfo.setStatus(2); jobQueueInfoService.saveJobIntoQueue(jobQueueInfo); ProcessBuilder pb = new ProcessBuilder(commands); try { pb.start(); } catch (IOException e) { // TODO Auto-generated catch block LOGGER.error("Request to kill an algorithm job did not run successfully.", e); } } else { LOGGER.info("Job does not exist, delete Job ID from queue: " + queueId); jobQueueInfoService.deleteJobById(queueId); } } } }
From source file:com.frostwire.gui.updates.UpdateMediator.java
public void startUpdate() { GUIMediator.safeInvokeLater(new Runnable() { public void run() { File executableFile = getUpdateBinaryFile(); if (executableFile == null || latestMsg == null) { return; }// www. j a va2s . c o m 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:edu.stanford.epad.epadws.dcm4chee.Dcm4CheeOperations.java
public static boolean dcmsnd(File inputDirFile, boolean throwException) throws Exception { InputStream is = null;/* ww w. j av a2 s . c om*/ InputStreamReader isr = null; BufferedReader br = null; FileWriter tagFileWriter = null; boolean success = false; try { String aeTitle = EPADConfig.aeTitle; String dicomServerIP = EPADConfig.dicomServerIP; String dicomServerPort = EPADConfig.dicomServerPort; String dicomServerTitleAndPort = aeTitle + "@" + dicomServerIP + ":" + dicomServerPort; dicomServerTitleAndPort = dicomServerTitleAndPort.trim(); String dirPath = inputDirFile.getAbsolutePath(); if (pathContainsSpaces(dirPath)) dirPath = escapeSpacesInDirPath(dirPath); File dir = new File(dirPath); int nbFiles = -1; if (dir != null) { String[] filePaths = dir.list(); if (filePaths != null) nbFiles = filePaths.length; } log.info("./dcmsnd: sending " + nbFiles + " file(s) - command: ./dcmsnd " + dicomServerTitleAndPort + " " + dirPath); String[] command = { "./dcmsnd", dicomServerTitleAndPort, dirPath }; ProcessBuilder processBuilder = new ProcessBuilder(command); String dicomScriptsDir = EPADConfig.getEPADWebServerDICOMScriptsDir() + "bin/"; File script = new File(dicomScriptsDir, "dcmsnd"); if (!script.exists()) dicomScriptsDir = EPADConfig.getEPADWebServerDICOMBinDir(); script = new File(dicomScriptsDir, "dcmsnd"); if (!script.exists()) throw new Exception("No script found:" + script.getAbsolutePath()); // Java 6 - Runtime.getRuntime().exec("chmod u+x "+script.getAbsolutePath()); script.setExecutable(true); processBuilder.directory(new File(dicomScriptsDir)); processBuilder.redirectErrorStream(true); Process process = processBuilder.start(); is = process.getInputStream(); isr = new InputStreamReader(is); br = new BufferedReader(isr); String line; StringBuilder sb = new StringBuilder(); while ((line = br.readLine()) != null) { sb.append(line).append("\n"); log.info("./dcmsend output: " + line); } try { int exitValue = process.waitFor(); log.info("DICOM send exit value is: " + exitValue); if (exitValue == 0) success = true; } catch (InterruptedException e) { log.warning("Didn't send DICOM files in: " + inputDirFile.getAbsolutePath(), e); } String cmdLineOutput = sb.toString(); if (cmdLineOutput.toLowerCase().contains("error")) throw new IllegalStateException("Failed for: " + parseError(cmdLineOutput)); return success; } catch (Exception e) { log.warning("DicomSendTask failed to send DICOM files", e); if (e instanceof IllegalStateException && throwException) { throw e; } if (throwException) { throw new IllegalStateException("DicomSendTask failed to send DICOM files", e); } return success; } catch (OutOfMemoryError oome) { log.warning("DicomSendTask out of memory: ", oome); if (throwException) { throw new IllegalStateException("DicomSendTask out of memory: ", oome); } return success; } finally { IOUtils.closeQuietly(tagFileWriter); IOUtils.closeQuietly(br); IOUtils.closeQuietly(isr); IOUtils.closeQuietly(is); } }
From source file:edu.wisc.doit.tcrypt.TokenEncryptDecryptIT.java
@Test public void testOpenSSLEncJavaDec() throws Exception { //Encrypt with openssl final File encryptFileScript = setupTempFile("encryptToken.sh"); encryptFileScript.setExecutable(true); final File publicKey = setupTempFile("my.wisc.edu-public.pem"); final String expected = "foobar"; final ProcessBuilder pb = new ProcessBuilder(encryptFileScript.getAbsolutePath(), publicKey.getAbsolutePath(), expected); final Process p = pb.start(); final int ret = p.waitFor(); if (ret != 0) { final String pOut = IOUtils.toString(p.getInputStream(), TokenEncrypter.CHARSET).trim(); System.out.println(pOut); final String pErr = IOUtils.toString(p.getErrorStream(), TokenEncrypter.CHARSET).trim(); System.out.println(pErr); }/*from w w w.j a v a 2 s . c o m*/ assertEquals(0, ret); final String encrypted = IOUtils.toString(p.getInputStream(), TokenEncrypter.CHARSET).trim(); //Decrypt with java final String actual = this.tokenDecrypter.decrypt(encrypted); //Verify assertEquals(expected, actual); }
From source file:edu.pitt.dbmi.ccd.queue.service.AlgorithmQueueService.java
@Async public Future<Void> runAlgorithmFromQueue(JobQueueInfo jobQueueInfo) { Long queueId = jobQueueInfo.getId(); String fileName = jobQueueInfo.getFileName() + ".txt"; String jsonFileName = jobQueueInfo.getFileName() + ".json"; String commands = jobQueueInfo.getCommands(); String tmpDirectory = jobQueueInfo.getTmpDirectory(); String outputDirectory = jobQueueInfo.getOutputDirectory(); List<String> cmdList = new LinkedList<>(); cmdList.addAll(Arrays.asList(commands.split(";"))); cmdList.add("--out"); cmdList.add(tmpDirectory);//from w ww . j ava 2 s . c o m StringBuilder sb = new StringBuilder(); cmdList.forEach(cmd -> { sb.append(cmd); sb.append(" "); }); LOGGER.info("Algorithm command: " + sb.toString()); String errorFileName = String.format("error_%s", fileName); Path error = Paths.get(tmpDirectory, errorFileName); Path errorDest = Paths.get(outputDirectory, errorFileName); Path src = Paths.get(tmpDirectory, fileName); Path dest = Paths.get(outputDirectory, fileName); Path json = Paths.get(tmpDirectory, jsonFileName); Path jsonDest = Paths.get(outputDirectory, jsonFileName); try { ProcessBuilder pb = new ProcessBuilder(cmdList); pb.redirectError(error.toFile()); Process process = pb.start(); //Get process Id Long pid = Processes.processId(process); JobQueueInfo queuedJobInfo = jobQueueInfoService.findOne(queueId); LOGGER.info("Set Job's pid to be: " + pid); queuedJobInfo.setPid(pid); jobQueueInfoService.saveJobIntoQueue(queuedJobInfo); process.waitFor(); if (process.exitValue() == 0) { LOGGER.info(String.format("Moving txt file %s to %s", src, dest)); Files.move(src, dest, StandardCopyOption.REPLACE_EXISTING); LOGGER.info(String.format("Moving json file %s to %s", json, dest)); Files.move(json, jsonDest, StandardCopyOption.REPLACE_EXISTING); Files.deleteIfExists(error); } else { LOGGER.info(String.format("Deleting tmp txt file %s", src)); Files.deleteIfExists(src); LOGGER.info(String.format("Moving error file %s to %s", error, errorDest)); Files.move(error, errorDest, StandardCopyOption.REPLACE_EXISTING); } } catch (IOException | InterruptedException exception) { LOGGER.error("Algorithm did not run successfully.", exception); } LOGGER.info("Delete Job ID from queue: " + queueId); jobQueueInfoService.deleteJobById(queueId); return new AsyncResult<>(null); }
From source file:edu.wisc.doit.tcrypt.TokenEncryptDecryptIT.java
@Test public void testJavaEncOpenSSLDec() throws Exception { //Encrypt with Java final String expected = "foobar"; final String encrypted = this.tokenEncrypter.encrypt(expected); //Decrypt with OpenSSL final File decryptFileScript = setupTempFile("decryptToken.sh"); decryptFileScript.setExecutable(true); final File privateKey = setupTempFile("my.wisc.edu-private.pem"); final ProcessBuilder pb = new ProcessBuilder(decryptFileScript.getAbsolutePath(), privateKey.getAbsolutePath(), encrypted); final Process p = pb.start(); final int ret = p.waitFor(); if (ret != 0) { final String pOut = IOUtils.toString(p.getInputStream(), TokenEncrypter.CHARSET).trim(); System.out.println(pOut); final String pErr = IOUtils.toString(p.getErrorStream(), TokenEncrypter.CHARSET).trim(); System.out.println(pErr); }/* w w w. j a v a 2s . c o m*/ assertEquals(0, ret); final String actual = IOUtils.toString(p.getInputStream(), TokenEncrypter.CHARSET).trim(); //Verify assertEquals(expected, actual); }
From source file:com.sastix.cms.common.services.htmltopdf.PdfImpl.java
public byte[] getPDF() throws IOException, InterruptedException { ProcessBuilder processBuilder = new ProcessBuilder(getCommandAsArray()); Process process = processBuilder.start(); //Runtime runtime = Runtime.getRuntime(); //Process process = runtime.exec(getCommandAsArray()); for (Page page : pages) { if (page.getType().equals(PageType.htmlAsString)) { OutputStream stdInStream = process.getOutputStream(); stdInStream.write(page.getSource().getBytes("UTF-8")); stdInStream.close();//from ww w . j a va 2 s.c om } } StreamEater outputStreamEater = new StreamEater(process.getInputStream()); outputStreamEater.start(); StreamEater errorStreamEater = new StreamEater(process.getErrorStream()); errorStreamEater.start(); outputStreamEater.join(); errorStreamEater.join(); process.waitFor(); if (process.exitValue() != 0) { throw new RuntimeException("Process (" + getCommand() + ") exited with status code " + process.exitValue() + ":\n" + new String(errorStreamEater.getBytes())); } if (outputStreamEater.getError() != null) { throw outputStreamEater.getError(); } if (errorStreamEater.getError() != null) { throw errorStreamEater.getError(); } return outputStreamEater.getBytes(); }
From source file:org.apache.asterix.test.aql.TestExecutor.java
private static String executeVagrantScript(ProcessBuilder pb, String node, String scriptName) throws Exception { pb.command("vagrant", "ssh", node, "--", pb.environment().get("SCRIPT_HOME") + scriptName); Process p = pb.start();/* w w w . j a v a 2 s. c om*/ p.waitFor(); InputStream input = p.getInputStream(); return IOUtils.toString(input, StandardCharsets.UTF_8.name()); }