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.github.mojos.distribute.PackageMojo.java
public void execute() throws MojoExecutionException, MojoFailureException { if (version != null) { packageVersion = version;/*from w ww .jav a2 s . co m*/ } //Copy sourceDirectory final File sourceDirectoryFile = new File(sourceDirectory); final File buildDirectory = Paths.get(project.getBuild().getDirectory(), "py").toFile(); try { FileUtils.copyDirectory(sourceDirectoryFile, buildDirectory); } catch (IOException e) { throw new MojoExecutionException("Failed to copy source", e); } final File setup = Paths.get(buildDirectory.getPath(), "setup.py").toFile(); final boolean setupProvided = setup.exists(); final File setupTemplate = setupProvided ? setup : Paths.get(buildDirectory.getPath(), "setup-template.py").toFile(); try { if (!setupProvided) { //update VERSION to latest version List<String> lines = new ArrayList<String>(); final InputStream inputStream = new BufferedInputStream(new FileInputStream(setupTemplate)); try { lines.addAll(IOUtils.readLines(inputStream)); } finally { inputStream.close(); } int index = 0; for (String line : lines) { line = line.replace(VERSION, packageVersion); line = line.replace(PROJECT_NAME, packageName); lines.set(index, line); index++; } final OutputStream outputStream = new FileOutputStream(setup); try { IOUtils.writeLines(lines, "\n", outputStream); } finally { outputStream.flush(); outputStream.close(); } } //execute setup script ProcessBuilder processBuilder = new ProcessBuilder(pythonExecutable, setup.getCanonicalPath(), "bdist_egg"); processBuilder.directory(buildDirectory); processBuilder.redirectErrorStream(true); Process pr = processBuilder.start(); int exitCode = pr.waitFor(); BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream())); String line = ""; while ((line = buf.readLine()) != null) { getLog().info(line); } if (exitCode != 0) { throw new MojoExecutionException("python setup.py returned error code " + exitCode); } } catch (FileNotFoundException e) { throw new MojoExecutionException("Unable to find " + setup.getPath(), e); } catch (IOException e) { throw new MojoExecutionException("Unable to read " + setup.getPath(), e); } catch (InterruptedException e) { throw new MojoExecutionException("Unable to execute python " + setup.getPath(), e); } }
From source file:functionaltests.scilab.AbstractScilabTest.java
public void run() throws Throwable { init();// www.jav a 2 s . c o m ProcessBuilder pb = new ProcessBuilder(); pb.directory(sci_tb_home); pb.redirectErrorStream(true); if (System.getProperty("scilab.bin.path") != null) { pb.command(System.getProperty("scilab.bin.path"), "-nw", "-f", (new File(test_home + fs + "PrepareTest.sci")).getCanonicalPath()); } else { pb.command("scilab", "-nw", "-f", (new File(test_home + fs + "PrepareTest.sci")).getCanonicalPath()); } System.out.println("Running command : " + pb.command()); File okFile = new File(sci_tb_home + fs + "ok.tst"); File koFile = new File(sci_tb_home + fs + "ko.tst"); if (okFile.exists()) { okFile.delete(); } if (koFile.exists()) { koFile.delete(); } Process p = pb.start(); IOTools.LoggingThread lt1 = new IOTools.LoggingThread(p.getInputStream(), "[AbstractScilabTest]", System.out); Thread t1 = new Thread(lt1, "AbstractScilabTest"); t1.setDaemon(true); t1.start(); p.waitFor(); assertTrue("Prepare Scilab Test passed", okFile.exists()); }
From source file:ml.shifu.shifu.core.alg.TensorflowTrainer.java
public void train() throws IOException { List<String> commands = buildCommands(); ProcessBuilder pb = new ProcessBuilder(commands); pb.directory(new File("./")); pb.redirectErrorStream(true); LOGGER.info("Start trainning sub process. Commands {}", commands.toString()); Process process = pb.start(); StreamCollector sc = new StreamCollector(process.getInputStream()); sc.start();/*from w w w. ja v a2 s . c o m*/ try { process.waitFor(); } catch (InterruptedException e) { throw new RuntimeException(e); } finally { if (sc != null) { sc.close(); } } }
From source file:com.liferay.petra.doulos.processor.BaseShellDoulosRequestProcessor.java
protected void execute(ShellStatus shellStatus) throws Exception { shellStatus.status = "executing"; List<String> shellCommandsList = getShellCommands(shellStatus); shellCommandsList.add(0, "/bin/bash"); shellCommandsList.add(1, "-x"); shellCommandsList.add(2, "-c"); String[] shellCommands = shellCommandsList.toArray(new String[shellCommandsList.size()]); shellStatus.shellCommands = StringUtils.join(shellCommands, "\n"); ProcessBuilder processBuilder = new ProcessBuilder(shellCommands); processBuilder.redirectErrorStream(true); Process process = processBuilder.start(); StringBuilder sb = new StringBuilder(); String line = null;// w ww . j a v a 2s .com BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream())); while ((line = bufferedReader.readLine()) != null) { sb.append(line); sb.append("\n"); } bufferedReader.close(); try { if (_log.isDebugEnabled()) { _log.debug("Wait for process to finish"); } process.waitFor(); shellStatus.exitValue = String.valueOf(process.exitValue()); shellStatus.output = sb.toString(); shellStatus.status = "finished"; } catch (Exception e) { Writer writer = new StringWriter(); PrintWriter printWriter = new PrintWriter(writer); e.printStackTrace(printWriter); shellStatus.exception = writer.toString(); shellStatus.status = "exception"; } }
From source file:com.netflix.dynomitemanager.defaultimpl.FloridaProcessManager.java
public void start() throws IOException { logger.info(String.format("Starting dynomite server")); List<String> command = Lists.newArrayList(); if (!"root".equals(System.getProperty("user.name"))) { command.add(SUDO_STRING);/* w w w. j ava2 s . c om*/ command.add("-n"); command.add("-E"); } command.addAll(getStartCommand()); ProcessBuilder startDynomite = new ProcessBuilder(command); Map<String, String> env = startDynomite.environment(); setEnv(env); startDynomite.directory(new File("/")); startDynomite.redirectErrorStream(true); Process starter = startDynomite.start(); try { sleeper.sleepQuietly(SCRIPT_EXECUTE_WAIT_TIME_MS); int code = starter.exitValue(); if (code == 0) { logger.info("Dynomite server has been started"); instanceState.setStorageProxyAlive(true); } else { logger.error("Unable to start Dynomite server. Error code: {}", code); } logProcessOutput(starter); } catch (Exception e) { logger.warn("Starting Dynomite has an error", e); } }
From source file:org.opencastproject.composer.impl.AbstractCmdlineEmbedderEngine.java
/** * // www.ja v a 2 s . co m * {@inheritDoc} Language attribute is normalized via <code>normalizeLanguage</code> method even if it is not present. * If normalized language returned is <code>null</code>, exception will be thrown. * * @see org.opencastproject.composer.api.EmbedderEngine#embed(java.io.File, java.io.File, java.util.Map) */ @Override public File embed(File mediaSource, File[] captionSources, String[] captionLanguages, Map<String, String> properties) throws EmbedderException { if (mediaSource == null) { logger.error("Media source is missing"); throw new EmbedderException("Missing media source."); } if (captionSources == null || captionSources.length == 0) { logger.error("Captions are missing"); throw new EmbedderException("Missing captions."); } if (captionLanguages == null || captionLanguages.length == 0) { logger.error("Caption languages are missing"); throw new EmbedderException("Missing caption language codes."); } // add all properties Map<String, String> embedderProperties = new HashMap<String, String>(); embedderProperties.putAll(properties); // add file properties embedderProperties.put("in.media.path", mediaSource.getAbsolutePath()); embedderProperties.put("out.media.path", mediaSource.getAbsoluteFile().getParent() + File.separator + UUID.randomUUID() + "-caption." + FilenameUtils.getExtension(mediaSource.getAbsolutePath())); for (int i = 0; i < ((captionSources.length > captionLanguages.length) ? captionSources.length : captionLanguages.length); i++) { embedderProperties.put("in.captions.path." + i, captionSources[i].getAbsolutePath()); // check/normalize language property String language = normalizeLanguage(captionLanguages[i]); if (language == null) { logger.error("Language property was set to null."); throw new EmbedderException("Captions language has not been set."); } embedderProperties.put("param.lang." + i, language); } // execute command List<String> commandList = buildCommandFromTemplate(embedderProperties); logger.debug("Executing embedding command {}", commandList); Process embedderProcess = null; BufferedReader processReader = null; // create and start process try { ProcessBuilder pb = new ProcessBuilder(commandList); pb.redirectErrorStream(true); embedderProcess = pb.start(); // process embedder output processReader = new BufferedReader(new InputStreamReader(embedderProcess.getInputStream())); String line = null; while ((line = processReader.readLine()) != null) { handleEmbedderOutput(line); } embedderProcess.waitFor(); int exitCode = embedderProcess.exitValue(); if (exitCode != 0) { throw new EmbedderException("Embedder exited abnormally with error code: " + exitCode); } return getOutputFile(embedderProperties); } catch (Exception e) { logger.error(e.getMessage()); throw new EmbedderException(e); } finally { IoSupport.closeQuietly(processReader); IoSupport.closeQuietly(embedderProcess); } }
From source file:net.fenyo.gnetwatch.actions.ExternalCommand.java
/** * Launches a process but do not wait for its completion. * any thread./*from w w w. j a v a 2 s. c om*/ * @param none. * @return void. * @throws IOException i/o exception <bold>before</bold> reading the process output stream. */ public synchronized void fork() throws IOException { final ProcessBuilder pb = new ProcessBuilder(cmdLine); pb.directory(new File(directory)); pb.redirectErrorStream(merge); process = pb.start(); if (process == null) throw new IOException("null process"); reader = new BufferedReader(new InputStreamReader(process.getInputStream())); errReader = new BufferedReader(new InputStreamReader(process.getErrorStream())); }
From source file:controllers.Consumer.java
public static void vncConnection(final String vncAddress, final String vncPort, final String vncPassword) { Logger.info("---------INSIDE CONSUMER OFFERDETAILS()---------------"); String user = session.get("username"); if (user != null) { Logger.info("------------EXITING CONSUMER OFFERDETAILS()--------------"); try {//from w ww . j av a 2 s. co m // TODO: connect ssh to retrieve data from each vm Properties props = new Properties(); // load a properties file props.load(new FileInputStream(Play.getFile("conf/config.properties"))); final String noVNCPath = props.getProperty("noVNC"); final String noVNCPort = props.getProperty("noVNCPort"); final String noVNCServer = props.getProperty("noVNCServer"); // final String sp = noVNCPath + "utils/websockify --web " + // noVNCPath + " " + noVNCPort + " " + vncAddress + ":" + // vncPort; ProcessBuilder pb = new ProcessBuilder("public/noVNC/utils/websockify", "--web", "public/noVNC/", noVNCPort, vncAddress + ":" + vncPort); pb.redirectErrorStream(); // redirect stderr to stdout Process process = pb.start(); play.mvc.Http.Request current = play.mvc.Http.Request.current(); String url = current.url; String domain = current.domain; Integer newPortRaw = Integer.parseInt(noVNCPort); Integer newPort = newPortRaw == 6900 ? 6080 : newPortRaw + 1; props.setProperty("noVNCPort", newPort.toString()); props.save(new FileOutputStream(new File("conf/config.properties")), ""); render(vncAddress, vncPort, vncPassword, noVNCServer, noVNCPort, url, user, domain); // process.waitFor(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { flash.error("You are not connected.Please Login"); Login.login_page(); } }
From source file:azkaban.jobExecutor.utils.process.AzkabanProcess.java
/** * Execute this process, blocking until it has completed. */// w w w. j a v a2 s . com public void run() throws IOException { if (this.isStarted() || this.isComplete()) { throw new IllegalStateException("The process can only be used once."); } ProcessBuilder builder = new ProcessBuilder(cmd); builder.directory(new File(workingDir)); builder.environment().putAll(env); builder.redirectErrorStream(true); this.process = builder.start(); try { this.processId = processId(process); if (processId == 0) { logger.debug("Spawned thread with unknown process id"); } else { logger.debug("Spawned thread with process id " + processId); } this.startupLatch.countDown(); LogGobbler outputGobbler = new LogGobbler(new InputStreamReader(process.getInputStream()), logger, Level.INFO, 30); LogGobbler errorGobbler = new LogGobbler(new InputStreamReader(process.getErrorStream()), logger, Level.ERROR, 30); outputGobbler.start(); errorGobbler.start(); int exitCode = -1; try { exitCode = process.waitFor(); } catch (InterruptedException e) { logger.info("Process interrupted. Exit code is " + exitCode, e); } completeLatch.countDown(); // try to wait for everything to get logged out before exiting outputGobbler.awaitCompletion(5000); errorGobbler.awaitCompletion(5000); if (exitCode != 0) { String output = new StringBuilder().append("Stdout:\n").append(outputGobbler.getRecentLog()) .append("\n\n").append("Stderr:\n").append(errorGobbler.getRecentLog()).append("\n") .toString(); throw new ProcessFailureException(exitCode, output); } } finally { IOUtils.closeQuietly(process.getInputStream()); IOUtils.closeQuietly(process.getOutputStream()); IOUtils.closeQuietly(process.getErrorStream()); } }
From source file:edu.stanford.junction.director.JAVADirector.java
private Process launchJAR(URL jarURL, URI activityURI) { final String JAR_PATH = "jars/"; String jarName = JAR_PATH + "/" + jarURL.getPath().substring(1).replace("/", "-"); File jarFile = new File(jarName); File tmpFile = new File(jarName + ".tmp"); if (!jarFile.exists() && !tmpFile.exists()) { try {/*from w w w . j av a 2 s. com*/ FileOutputStream out = new FileOutputStream(tmpFile); InputStream in = jarURL.openStream(); byte[] buf = new byte[4 * 1024]; int bytesRead; while ((bytesRead = in.read(buf)) != -1) { out.write(buf, 0, bytesRead); } in.close(); out.close(); boolean res = tmpFile.renameTo(jarFile); if (!res) { throw new Exception("Could not rename file."); } } catch (Exception e) { e.printStackTrace(); return null; } } if (!jarFile.exists()) { System.out.println("Failed to get JAR file " + jarFile.getName()); return null; } // Launch the new JVM try { List<String> command = new ArrayList<String>(); command.add("java"); command.add("-jar"); command.add(jarFile.getAbsolutePath()); command.add(activityURI.toString()); System.out.println("Executing: " + command.toString()); ProcessBuilder pb = new ProcessBuilder(command); pb.directory(jarFile.getParentFile()); pb.redirectErrorStream(true); Process p = pb.start(); // TODO: make sure it worked return p; } catch (Exception e) { System.out.println("failed to launch JAR."); e.printStackTrace(); } return null; }