List of usage examples for java.lang ProcessBuilder start
public Process start() throws IOException
From source file:edu.hm.muse.controller.AdminController.java
@RequestMapping(value = "/admininternpic.secu", method = RequestMethod.GET) private ModelAndView showAllPictures(HttpSession session, @CookieValue(value = "admintoken", required = false) String adminToken, @RequestParam(value = "path", required = false) String pathToWatch) { if (!checkToken(session, adminToken)) { throw new SuperFatalAndReallyAnnoyingException("Already bad..."); }// ww w. ja va 2 s . c o m if (pathToWatch == null || pathToWatch.isEmpty()) { pathToWatch = "webapps/secu/img"; } StringBuilder builder = new StringBuilder(); //just works in linux or?? try { ProcessBuilder procBuilder = new ProcessBuilder("bash", "-c", String.format("ls -gGH %s", pathToWatch)); Process proc = procBuilder.start(); proc.waitFor(); BufferedReader bReader = new BufferedReader(new InputStreamReader(proc.getInputStream())); String readLine = bReader.readLine(); while (readLine != null) { builder.append(readLine).append("<br/>"); readLine = bReader.readLine(); } builder.append("Thats All..."); } catch (IOException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } catch (InterruptedException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } ModelAndView mv = new ModelAndView("admininterndic"); String result = builder.toString(); mv.addObject("files", result); return mv; }
From source file:com.netflix.raigad.defaultimpl.ElasticSearchProcessManager.java
public void stop() throws IOException { logger.info("Stopping Elasticsearch server ...."); List<String> command = Lists.newArrayList(); if (!"root".equals(System.getProperty("user.name"))) { command.add(SUDO_STRING);//from w w w. ja v a 2s .c o m command.add("-n"); command.add("-E"); } for (String param : config.getElasticsearchStopScript().split(" ")) { if (StringUtils.isNotBlank(param)) command.add(param); } ProcessBuilder stopCass = new ProcessBuilder(command); stopCass.directory(new File("/")); stopCass.redirectErrorStream(true); Process stopper = stopCass.start(); sleeper.sleepQuietly(SCRIPT_EXECUTE_WAIT_TIME_MS); try { int code = stopper.exitValue(); if (code == 0) logger.info("Elasticsearch server has been stopped"); else { logger.error("Unable to stop Elasticsearch server. Error code: {}", code); logProcessOutput(stopper); } } catch (Exception e) { logger.warn("couldn't shut down Elasticsearch correctly", e); } }
From source file:com.photon.phresco.framework.param.impl.IosDeviceTypeParameterImpl.java
private String cureentXcodeVersion() throws IOException { String version = ""; ProcessBuilder pb = new ProcessBuilder("/bin/sh", "-c", "xcodebuild -version"); pb.redirectErrorStream(true);//from w w w. j a v a2s. c o m pb.directory(new File("/")); Process process = pb.start(); InputStream is = process.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line; while ((line = br.readLine()) != null) { String[] splited = line.split("\\s"); version = splited[1]; break; } return version; }
From source file:de.uzk.hki.da.convert.PublishVideoConversionStrategy.java
/** * @author Daniel M. de Oliveira/*from w w w .java 2 s . co m*/ * @author Christian Weitz * @author Thomas Kleinke * * @param cmd The command to execute * @param targetFile The target file to check regularly * @return true if the conversion was successful, otherwise false */ private boolean executeConversionTool(String[] cmd, File targetFile) { logger.debug("Running cmd \"{}\"", Arrays.toString(cmd)); Process p = null; try { ProcessBuilder pb = new ProcessBuilder(cmd); p = pb.start(); long targetFileSize = 0; long previousTargetFileSize = 0; do { previousTargetFileSize = targetFileSize; Thread.sleep(processTimeout); targetFileSize = targetFile.length(); } while (previousTargetFileSize < targetFileSize); p.destroy(); } catch (FileNotFoundException e) { logger.error("File not found in runShellCommand", e); return false; } catch (Exception e) { logger.error("Error in runShellCommand", e); return false; } finally { if (p != null) LinuxEnvironmentUtils.closeStreams(p); } return true; }
From source file:es.ehu.si.ixa.qwn.ppv.UKBwrapper.java
public void propagate(String ctxtFile) throws IOException { try {/*from www .ja v a 2 s . c o m*/ String[] command = { ukbPath + "/ukb_ppv", "-K", this.graph, "-D", this.langDict, "--variants", "-O", this.outDir, ctxtFile }; System.err.println("UKB komandoa: " + Arrays.toString(command)); ProcessBuilder ukbBuilder = new ProcessBuilder().command(command); //.redirectErrorStream(true); Process ukb_ppv = ukbBuilder.start(); int success = ukb_ppv.waitFor(); System.err.println("ukb_ppv succesful? " + success); if (success != 0) { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(ukb_ppv.getErrorStream()), 1); String line; while ((line = bufferedReader.readLine()) != null) { System.err.println(line); } } } catch (Exception e) { System.err.println("PropagationUKB class: error when calling ukb_ppv\n."); e.printStackTrace(); } //"$UKB_PATH"/bin/ukb_ppv -K "$PROPAGATION_PATH"/lkb_resources/wnet30_enSyn.bin -D "$UKB_PATH"/lkb_sources/30/wnet30_dict.txt --variants -O "$PPV_OUT_DIR" $TMP_DIR/propag_posSeeds_syn.ctx //mv "$PPV_OUT_DIR"/ctx_01.ppv "$PPV_OUT_DIR"/pos_syn.ppv }
From source file:aiai.ai.core.ExecProcessService.java
public Result execCommand(List<String> cmd, File execDir, File consoleLogFile) throws IOException, InterruptedException { ProcessBuilder pb = new ProcessBuilder(); pb.command(cmd);/* w w w .j a v a 2s . c o m*/ pb.directory(execDir); pb.redirectErrorStream(true); final Process process = pb.start(); final StreamHolder streamHolder = new StreamHolder(); int exitCode; try (final FileOutputStream fos = new FileOutputStream(consoleLogFile); BufferedOutputStream bos = new BufferedOutputStream(fos)) { final Thread reader = new Thread(() -> { try { streamHolder.is = process.getInputStream(); int c; while ((c = streamHolder.is.read()) != -1) { bos.write(c); } } catch (IOException e) { log.error("Error collect data from output stream", e); } }); reader.start(); exitCode = process.waitFor(); reader.join(); } finally { try { if (streamHolder.is != null) { streamHolder.is.close(); } } catch (Throwable th) { log.warn("Error with closing InputStream", th); } } log.info("Any errors of execution? {}", (exitCode == 0 ? "No" : "Yes")); log.debug("'\tcmd: {}", cmd); log.debug("'\texecDir: {}", execDir.getPath()); String console = readLastLines(500, consoleLogFile); log.debug("'\tconsole output:\n{}", console); return new Result(exitCode == 0, exitCode, console); }
From source file:com.laex.cg2d.screeneditor.handlers.RenderHandler.java
/** * the command has been executed, so extract extract the needed information * from the application context./*from w w w . j a va2 s. c o m*/ * * @param event * the event * @return the object * @throws ExecutionException * the execution exception */ public Object execute(ExecutionEvent event) throws ExecutionException { IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event); final IEditorPart editorPart = window.getActivePage().getActiveEditor(); editorPart.doSave(new NullProgressMonitor()); validate(window.getShell()); // Eclipse Jobs API final Job job = new Job("Render Game") { @Override protected IStatus run(IProgressMonitor monitor) { if (monitor.isCanceled()) { return Status.CANCEL_STATUS; } try { IFile file = ((IFileEditorInput) editorPart.getEditorInput()).getFile(); monitor.beginTask("Building rendering command", 5); ILog log = Activator.getDefault().getLog(); String mapFile = file.getLocation().makeAbsolute().toOSString(); String controllerFile = file.getLocation().removeFileExtension().addFileExtension("lua") .makeAbsolute().toOSString(); String[] command = buildRunnerCommandFromProperties(mapFile, controllerFile); monitor.worked(5); monitor.beginTask("Rendering external", 5); ProcessBuilder pb = new ProcessBuilder(command); Process p = pb.start(); monitor.worked(4); Scanner scn = new Scanner(p.getErrorStream()); while (scn.hasNext() && !monitor.isCanceled()) { if (monitor.isCanceled()) { throw new InterruptedException("Cancelled"); } log.log(new Status(IStatus.INFO, Activator.PLUGIN_ID, scn.nextLine())); } monitor.worked(5); monitor.done(); this.done(Status.OK_STATUS); return Status.OK_STATUS; } catch (RuntimeException e) { return handleException(e); } catch (IOException e) { return handleException(e); } catch (CoreException e) { return handleException(e); } catch (InterruptedException e) { return handleException(e); } } private IStatus handleException(Exception e) { Activator.log(e); return Status.CANCEL_STATUS; } }; job.setUser(true); job.setPriority(Job.INTERACTIVE); job.schedule(); return null; }
From source file:ape.ContinueNodeCommand.java
public boolean runImpl(String[] args) throws IOException { String nodeType = null;//from w w w. j a v a 2 s . c om nodeType = args[0]; if (Main.VERBOSE) System.out.println("Nodetype" + args[0]); Process p; if (nodeType.toLowerCase().equals("datanode") || nodeType.toLowerCase().equals("tasktracker") || nodeType.toLowerCase().equals("jobtracker") || nodeType.toLowerCase().equals("namenode")) { System.out.println("Suspend is about to execute the following command:"); String cmd = "echo \"kill -18 \\$(ps aux | grep -i " + nodeType + " | grep -v grep | grep -v ape | awk -F ' ' '{print \\$2}')\" > kill-node.sh && chmod +x kill-node.sh && ./kill-node.sh"; System.out.println(cmd); /** * The above code block checks to see if a valid node type is passed. * If it is, then it sends a very ugly bash command to kill the corresponding process. * It gets a list of running processes, then greps it for the node type, then * removes the result generated by running grep, then it gets the process ID of that line * */ ProcessBuilder pb = new ProcessBuilder("bash", "-c", cmd); pb.redirectErrorStream(true); Process sh; try { sh = pb.start(); } catch (IOException e1) { e1.printStackTrace(); Main.logger.info(e1); return false; } try { sh.waitFor(); } catch (InterruptedException e) { System.out.println("The suspend node command caught an interrupt"); e.printStackTrace(); Main.logger.info("The suspend command caught an interrupt"); Main.logger.info(e); return false; } InputStream shIn = sh.getInputStream(); int c; while ((c = shIn.read()) != -1) { System.out.write(c); } try { shIn.close(); } catch (IOException e) { System.out.println("Could not close InputStream from the suspend process."); e.printStackTrace(); Main.logger.info("Could not close InputStream from the suspend process."); Main.logger.info(e); return false; } return true; } else { System.err.println("Invalid node type."); return false; } }
From source file:com.netflix.dynomitemanager.defaultimpl.StorageProcessManager.java
public void stop() throws IOException { logger.info("Stopping Storage process ...."); List<String> command = Lists.newArrayList(); if (!"root".equals(System.getProperty("user.name"))) { command.add(SUDO_STRING);//from ww w . j av a 2 s . c om command.add("-n"); command.add("-E"); } for (String param : config.getStorageStopScript().split(" ")) { if (StringUtils.isNotBlank(param)) command.add(param); } ProcessBuilder stopCass = new ProcessBuilder(command); stopCass.directory(new File("/")); stopCass.redirectErrorStream(true); Process stopper = stopCass.start(); sleeper.sleepQuietly(SCRIPT_EXECUTE_WAIT_TIME_MS); try { int code = stopper.exitValue(); if (code == 0) { logger.info("Storage process has been stopped"); instanceState.setStorageProxyAlive(false); } else { logger.error("Unable to stop storage process. Error code: {}", code); logProcessOutput(stopper); } } catch (Exception e) { logger.warn("couldn't shut down Storage process correctly", e); } }
From source file:net.landora.video.mplayer.MPlayerParser.java
private MPlayerInfoParse mplayerIdentify(File f, Integer videoId, Integer audioId, Integer subtitleId) throws IOException, InterruptedException { //mplayer -frames 0 -msglevel identify=9 "$1" -vo null -ao null 2>/dev/null | grep "^ID" List<String> cmd = new ArrayList<String>(); cmd.add(ProgramsAddon.getInstance().getConfiguredPath(CommonPrograms.MPLAYER)); cmd.add("-frames"); cmd.add("0"); cmd.add("-msglevel"); cmd.add("identify=9"); cmd.add("-vo"); cmd.add("null"); cmd.add("-ao"); cmd.add("null"); if (videoId != null) { cmd.add("-vid"); cmd.add(videoId.toString());// www. ja va 2 s.co m } if (audioId != null) { cmd.add("-aid"); cmd.add(audioId.toString()); } if (subtitleId != null) { cmd.add("-sid"); cmd.add(subtitleId.toString()); } cmd.add(f.getAbsolutePath()); ProcessBuilder process = new ProcessBuilder(cmd); process.redirectErrorStream(true); Process p = process.start(); StringWriter buffer = new StringWriter(); IOUtils.copy(p.getInputStream(), buffer); p.waitFor(); Matcher infoMatcher = dataPattern.matcher(buffer.toString()); MPlayerInfoParse result = new MPlayerInfoParse(); while (infoMatcher.find()) { result.add(infoMatcher.group(1), infoMatcher.group(2)); } return result; }