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:org.apache.kudu.client.MiniKuduCluster.java
/** * Starts a process using the provided command and configures it to be daemon, * redirects the stderr to stdout, and starts a thread that will read from the process' input * stream and redirect that to LOG.//from w w w . j a va 2 s . c o m * @param port RPC port used to identify the process * @param command process and options * @return The started process * @throws Exception Exception if an error prevents us from starting the process, * or if we were able to start the process but noticed that it was then killed (in which case * we'll log the exit value). */ private Process configureAndStartProcess(int port, List<String> command) throws Exception { ProcessBuilder processBuilder = new ProcessBuilder(command); processBuilder.redirectErrorStream(true); if (miniKdc != null) { processBuilder.environment().putAll(miniKdc.getEnvVars()); } Process proc = processBuilder.start(); ProcessInputStreamLogPrinterRunnable printer = new ProcessInputStreamLogPrinterRunnable( proc.getInputStream()); Thread thread = new Thread(printer); thread.setDaemon(true); thread.setName(Iterables.getLast(Splitter.on(File.separatorChar).split(command.get(0))) + ":" + port); PROCESS_INPUT_PRINTERS.add(thread); thread.start(); Thread.sleep(300); try { int ev = proc.exitValue(); throw new Exception(String.format("We tried starting a process (%s) but it exited with value=%s", command.get(0), ev)); } catch (IllegalThreadStateException ex) { // This means the process is still alive, it's like reverse psychology. } return proc; }
From source file:com.datasalt.pangool.solr.SolrRecordWriter.java
private Path findSolrConfig(Configuration conf) throws IOException { Path solrHome = null;//from w w w . j ava2s.co m // we added these lines to make this patch work on Hadoop 0.20.2 FileSystem localFs = FileSystem.getLocal(conf); if (FileSystem.get(conf).equals(localFs)) { return new Path(localSolrHome); } // end-of-addition Path[] localArchives = DistributedCache.getLocalCacheArchives(conf); if (localArchives.length == 0) { throw new IOException(String.format("No local cache archives, where is %s", zipName)); } for (Path unpackedDir : localArchives) { // Only logged if debugging if (LOG.isDebugEnabled()) { LOG.debug(String.format("Examining unpack directory %s for %s", unpackedDir, zipName)); ProcessBuilder lsCmd = new ProcessBuilder( new String[] { "/bin/ls", "-lR", unpackedDir.toString() }); lsCmd.redirectErrorStream(); Process ls = lsCmd.start(); try { byte[] buf = new byte[16 * 1024]; InputStream all = ls.getInputStream(); int count; while ((count = all.read(buf)) > 0) { System.err.write(buf, 0, count); } } catch (IOException ignore) { } System.err.format("Exit value is %d%n", ls.exitValue()); } if (unpackedDir.getName().equals(zipName)) { solrHome = unpackedDir; break; } } return solrHome; }
From source file:com.amazonaws.eclipse.dynamodb.testtool.TestToolProcess.java
/** * Start the DynamoDBLocal process.//from w ww . j av a2s. c om * * @param onExitAction optional action to be executed when the process * exits * @throws IOException if starting the process fails */ public synchronized void start(final Runnable onExitAction) throws IOException { if (process != null) { throw new IllegalStateException("Already started!"); } ProcessBuilder builder = new ProcessBuilder(); builder.directory(installDirectory); builder.command(jre.getInstallLocation().getAbsolutePath().concat("/bin/java"), "-Djava.library.path=".concat(findLibraryDirectory().getAbsolutePath()), "-jar", "DynamoDBLocal.jar", "--port", Integer.toString(port)); // Drop STDERR into STDOUT so we can handle them together. builder.redirectErrorStream(true); // Register a shutdown hook to kill DynamoDBLocal if Eclipse exits. Runtime.getRuntime().addShutdownHook(shutdownHook); // Start the DynamoDBLocal process. process = builder.start(); // Start a background thread to read any output from DynamoDBLocal // and dump it to an IConsole. new ConsoleOutputLogger(process.getInputStream(), onExitAction).start(); }
From source file:org.gbif.ocurrence.index.solr.SolrRecordWriter.java
private Path findSolrConfig(Configuration conf) throws IOException { Path solrHome = null;//from w ww .j av a 2s. co m Path[] localArchives = DistributedCache.getLocalCacheArchives(conf); if (localArchives.length == 0) { throw new IOException(String.format("No local cache archives, where is %s:%s", SolrOutputFormat.getSetupOk(), SolrOutputFormat.getZipName(conf))); } for (Path unpackedDir : localArchives) { // Only logged if debugging if (LOG.isDebugEnabled()) { LOG.debug(String.format("Examining unpack directory %s for %s", unpackedDir, SolrOutputFormat.getZipName(conf))); ProcessBuilder lsCmd = new ProcessBuilder( new String[] { "/bin/ls", "-lR", unpackedDir.toString() }); lsCmd.redirectErrorStream(); Process ls = lsCmd.start(); try { byte[] buf = new byte[16 * 1024]; InputStream all = ls.getInputStream(); int count; while ((count = all.read(buf)) > 0) { System.err.write(buf, 0, count); } } catch (IOException ignore) { } System.err.format("Exit value is %d%n", ls.exitValue()); } if (unpackedDir.getName().equals(SolrOutputFormat.getZipName(conf))) { solrHome = unpackedDir; break; } } return solrHome; }
From source file:gov.pnnl.goss.gridappsd.simulation.SimulationManagerImpl.java
/** * This method is called by Process Manager to start a simulation * @param simulationId/*www . j a va 2s .c o m*/ * @param simulationFile */ @Override public void startSimulation(int simulationId, File simulationFile, SimulationConfig simulationConfig) { try { logManager.log(new LogMessage(this.getClass().getName() + "-" + Integer.toString(simulationId), new Date().getTime(), "Starting simulation " + simulationId, LogLevel.INFO, ProcessStatus.STARTING, true), GridAppsDConstants.username); } catch (Exception e2) { log.warn("Error while reporting status " + e2.getMessage()); } Thread thread = new Thread(new Runnable() { @Override public void run() { Process gridlabdProcess = null; Process fncsProcess = null; Process fncsBridgeProcess = null; Process vvoAppProcess = null; InitializedTracker isInitialized = new InitializedTracker(); try { File defaultLogDir = simulationFile.getParentFile(); //Start FNCS //TODO, verify no errors on this String broker_location = "tcp://*:5570"; if (simulationConfig != null && simulationConfig.model_creation_config != null && simulationConfig.model_creation_config.schedule_name != null && simulationConfig.model_creation_config.schedule_name.trim().length() > 0) { broker_location = "tcp://" + simulationConfig.getSimulation_broker_location() + ":" + String.valueOf(simulationConfig.getSimulation_broker_port()); File serviceDir = serviceManager.getServiceConfigDirectory(); //copy zipload_schedule.player file try { RunCommandLine.runCommand("cp " + serviceDir.getAbsolutePath() + File.separator + "etc" + File.separator + "zipload_schedule.player " + simulationFile.getParentFile().getAbsolutePath() + File.separator + simulationConfig.model_creation_config.schedule_name + ".player"); } catch (Exception e) { log.warn("Could not copy player file to working directory"); } } logManager.log(new LogMessage(this.getClass().getName() + "-" + Integer.toString(simulationId), new Date().getTime(), "Calling " + getPath(GridAppsDConstants.FNCS_PATH) + " 2", LogLevel.INFO, ProcessStatus.STARTING, true), GridAppsDConstants.username); ProcessBuilder fncsBuilder = new ProcessBuilder(getPath(GridAppsDConstants.FNCS_PATH), "2"); fncsBuilder.redirectErrorStream(true); fncsBuilder.redirectOutput( new File(defaultLogDir.getAbsolutePath() + File.separator + "fncs.log")); Map<String, String> fncsEnvironment = fncsBuilder.environment(); fncsEnvironment.put("FNCS_BROKER", broker_location); fncsProcess = fncsBuilder.start(); // Watch the process watch(fncsProcess, "FNCS"); //TODO: check if FNCS is started correctly and send publish simulation status accordingly logManager.log(new LogMessage(this.getClass().getName() + "-" + Integer.toString(simulationId), new Date().getTime(), "FNCS Co-Simulator started", LogLevel.INFO, ProcessStatus.RUNNING, true), GridAppsDConstants.username); //client.publish(GridAppsDConstants.topic_simulationStatus+simulationId, "FNCS Co-Simulator started"); //Start GridLAB-D logManager.log(new LogMessage(this.getClass().getName() + "-" + Integer.toString(simulationId), new Date().getTime(), "Calling " + getPath(GridAppsDConstants.GRIDLABD_PATH) + " " + simulationFile, LogLevel.INFO, ProcessStatus.RUNNING, true), GridAppsDConstants.username); ProcessBuilder gridlabDBuilder = new ProcessBuilder(getPath(GridAppsDConstants.GRIDLABD_PATH), simulationFile.getAbsolutePath()); gridlabDBuilder.redirectErrorStream(true); gridlabDBuilder.redirectOutput( new File(defaultLogDir.getAbsolutePath() + File.separator + "gridlabd.log")); //launch from directory containing simulation files gridlabDBuilder.directory(simulationFile.getParentFile()); gridlabdProcess = gridlabDBuilder.start(); // Watch the process watch(gridlabdProcess, "GridLABD"); //TODO: check if GridLAB-D is started correctly and send publish simulation status accordingly logManager.log(new LogMessage(this.getClass().getName() + "-" + Integer.toString(simulationId), new Date().getTime(), "GridLAB-D started", LogLevel.INFO, ProcessStatus.RUNNING, true), GridAppsDConstants.username); //Start VVO Application //TODO filname really should be constant String vvoInputFile = simulationFile.getParentFile().getAbsolutePath() + File.separator + "vvo_inputs.json"; logManager.log(new LogMessage(this.getClass().getName() + "-" + Integer.toString(simulationId), new Date().getTime(), "Calling " + "python " + getPath(GridAppsDConstants.VVO_APP_PATH) + " " + simulationId + " " + vvoInputFile, LogLevel.INFO, ProcessStatus.RUNNING, true), GridAppsDConstants.username); ProcessBuilder vvoAppBuilder = new ProcessBuilder("python", getPath(GridAppsDConstants.VVO_APP_PATH), "-f", vvoInputFile, "" + simulationId); vvoAppBuilder.redirectErrorStream(true); vvoAppBuilder.redirectOutput( new File(defaultLogDir.getAbsolutePath() + File.separator + "vvo_app.log")); vvoAppProcess = vvoAppBuilder.start(); // Watch the process watch(vvoAppProcess, "VVO Application"); logManager.log(new LogMessage(this.getClass().getName() + "-" + Integer.toString(simulationId), new Date().getTime(), "FNCS-GOSS Bridge started", LogLevel.INFO, ProcessStatus.RUNNING, true), GridAppsDConstants.username); //Start GOSS-FNCS Bridge logManager.log(new LogMessage(this.getClass().getName() + "-" + Integer.toString(simulationId), new Date().getTime(), "Calling " + "python " + getPath(GridAppsDConstants.FNCS_BRIDGE_PATH) + " " + simulationConfig.getSimulation_name(), LogLevel.INFO, ProcessStatus.RUNNING, true), GridAppsDConstants.username); ProcessBuilder fncsBridgeBuilder = new ProcessBuilder("python", getPath(GridAppsDConstants.FNCS_BRIDGE_PATH), simulationConfig.getSimulation_name(), broker_location); fncsBridgeBuilder.redirectErrorStream(true); fncsBridgeBuilder.redirectOutput( new File(defaultLogDir.getAbsolutePath() + File.separator + "fncs_goss_bridge.log")); fncsBridgeProcess = fncsBridgeBuilder.start(); // Watch the process watch(fncsBridgeProcess, "FNCS GOSS Bridge"); //TODO: check if bridge is started correctly and send publish simulation status accordingly logManager.log(new LogMessage(this.getClass().getName() + "-" + Integer.toString(simulationId), new Date().getTime(), "FNCS-GOSS Bridge started", LogLevel.INFO, ProcessStatus.RUNNING, true), GridAppsDConstants.username); //Subscribe to fncs-goss-bridge output topic client.subscribe(GridAppsDConstants.topic_FNCS_output, new GossFncsResponseEvent(logManager, isInitialized, simulationId)); int initAttempts = 0; while (!isInitialized.isInited && initAttempts < MAX_INIT_ATTEMPTS) { //Send 'isInitialized' call to fncs-goss-bridge to check initialization until it is initialized. //TODO add limiting how long it checks for initialized, or cancel if the fncs process exits //This call would return true/false for initialization and simulation output of time step 0. logManager.log( new LogMessage(this.getClass().getName() + "-" + Integer.toString(simulationId), new Date().getTime(), "Checking fncs is initialized, currently " + isInitialized.isInited, LogLevel.INFO, ProcessStatus.RUNNING, true), GridAppsDConstants.username); client.publish(GridAppsDConstants.topic_FNCS_input, "{\"command\": \"isInitialized\"}"); initAttempts++; Thread.sleep(1000); } if (initAttempts < MAX_INIT_ATTEMPTS) { logManager.log( new LogMessage(Integer.toString(simulationId), new Date().getTime(), "FNCS Initialized", LogLevel.INFO, ProcessStatus.RUNNING, true), GridAppsDConstants.username); //Send the timesteps by second for the amount of time specified in the simulation config sendTimesteps(simulationConfig, simulationId); } else { logManager.log( new LogMessage(Integer.toString(simulationId), new Date().getTime(), "FNCS Initialization Failed", LogLevel.ERROR, ProcessStatus.ERROR, true), GridAppsDConstants.username); } //call to stop the fncs broker client.publish(GridAppsDConstants.topic_FNCS_input, "{\"command\": \"stop\"}"); logManager.log(new LogMessage(Integer.toString(simulationId), new Date().getTime(), "Simulation " + simulationId + " complete", LogLevel.INFO, ProcessStatus.COMPLETE, true), GridAppsDConstants.username); } catch (Exception e) { log.error("Error during simulation", e); try { logManager.log(new LogMessage(Integer.toString(simulationId), new Date().getTime(), "Simulation error: " + e.getMessage(), LogLevel.ERROR, ProcessStatus.ERROR, true), GridAppsDConstants.username); } catch (Exception e1) { log.error("Error while reporting error status", e); } } finally { //shut down fncs broker and gridlabd and bridge if still running if (fncsProcess != null) { fncsProcess.destroy(); } if (gridlabdProcess != null) { gridlabdProcess.destroy(); } if (fncsBridgeProcess != null) { fncsBridgeProcess.destroy(); } } } }); thread.start(); }
From source file:org.opencastproject.execute.impl.ExecuteServiceImpl.java
private String runCommand(List<String> command, File outFile, Type expectedType) throws ExecuteException { Process p = null;//from www.j a v a 2 s.c om int result = 0; try { logger.info("Running command {}", command.get(0)); logger.debug("Starting subprocess {} with arguments {}", command.get(0), StringUtils.join(command.subList(1, command.size()), ", ")); ProcessBuilder pb = new ProcessBuilder(command); pb.redirectErrorStream(true); p = pb.start(); result = p.waitFor(); logger.debug("Command {} finished with result {}", command.get(0), result); if (result == 0) { // Read the command output if (outFile != null) { if (outFile.isFile()) { URI newURI = workspace.putInCollection(COLLECTION, outFile.getName(), new FileInputStream(outFile)); if (outFile.delete()) { logger.debug("Deleted the local copy of the encoded file at {}", outFile.getAbsolutePath()); } else { logger.warn("Unable to delete the encoding output at {}", outFile.getAbsolutePath()); } return MediaPackageElementParser.getAsXml(MediaPackageElementBuilderFactory.newInstance() .newElementBuilder().elementFromURI(newURI, expectedType, null)); } } return ""; } else { // 'Scanner' reads tokens delimited by an specific character (set). // By telling a Scanner to use the 'beginning of the input boundary' character as delimiter, which of course // will never find, yields the whole String as the next token. String line; try { line = new Scanner(p.getInputStream()).useDelimiter("\\A").next(); } catch (NoSuchElementException e) { line = ""; } throw new ExecuteException(String.format("Process %s returned error code %d with this output:\n%s", command.get(0), result, line.trim())); } } catch (InterruptedException e) { throw new ExecuteException("The executor thread has been unexpectedly interrupted", e); } catch (IOException e) { // Only log the first argument, the executable, as other arguments may contain sensitive values // e.g. MySQL password/user, paths, etc. that should not be shown to caller logger.error("Could not start subprocess {}", command.get(0)); throw new ExecuteException("Could not start subprocess: " + command.get(0), e); } catch (UnsupportedElementException e) { throw new ExecuteException( "Couldn't create a new MediaPackage element of type " + expectedType.toString(), e); } catch (ConfigurationException e) { throw new ExecuteException("Couldn't instantiate a new MediaPackage element builder", e); } catch (MediaPackageException e) { throw new ExecuteException( "Couldn't serialize a new Mediapackage element of type " + expectedType.toString(), e); } finally { IoSupport.closeQuietly(p); } }
From source file:nz.co.fortytwo.signalk.handler.GitHandler.java
private void runNpmInstall(final File output, File destDir) throws Exception { FileUtils.writeStringToFile(output, "\nBeginning npm install", true); ProcessBuilder pb = new ProcessBuilder("npm", "install"); Map<String, String> env = System.getenv(); if (env.containsKey("PATH")) { pb.environment().put("PATH", env.get("PATH")); }//from w w w . j a v a2s. c o m if (env.containsKey("Path")) { pb.environment().put("Path", env.get("Path")); } if (env.containsKey("path")) { pb.environment().put("path", env.get("path")); } pb.directory(destDir); pb.redirectErrorStream(true); pb.redirectOutput(output); final Process p = pb.start(); Thread t = new Thread() { @Override public void run() { try { p.waitFor(); FileUtils.writeStringToFile(output, "\nDONE: Npm ended sucessfully", true); } catch (Exception e) { try { logger.error(e); FileUtils.writeStringToFile(output, "\nNpm ended badly:" + e.getMessage(), true); FileUtils.writeStringToFile(output, "\n" + e.getStackTrace(), true); } catch (IOException e1) { logger.error(e1); } } } }; t.start(); }
From source file:eu.excitementproject.eop.distsim.redisinjar.EmbeddedRedisServerRunner.java
private ProcessBuilder createRedisProcessBuilder() { ProcessBuilder pb = null; if ((rdbDir == null) || (rdbName == null)) { pb = new ProcessBuilder(command.getAbsolutePath(), "--maxmemory", REDIS_MAXMEMORY, "--port", Integer.toString(port)); pb.directory(command.getParentFile()); } else {/*from ww w.jav a2 s . c o m*/ pb = new ProcessBuilder(command.getAbsolutePath(), "--maxmemory", REDIS_MAXMEMORY, "--port", Integer.toString(port), "--dir", rdbDir, "--dbfilename", rdbName); pb.directory(command.getParentFile()); } pb.redirectErrorStream(true); // both STDERR/STDOUT via getInputStream: needed for rare cases where run fails due to GLIBC problem, etc. return pb; }
From source file:com.photon.phresco.plugins.xcode.XcodeBuild.java
/** * Execute the xcode command line utility. *//*from w w w . ja v a 2 s .co m*/ public void execute() throws MojoExecutionException { if (!xcodeCommandLine.exists()) { throw new MojoExecutionException( "Invalid path, invalid xcodebuild file: " + xcodeCommandLine.getAbsolutePath()); } /* * // Compute archive name String archiveName = * project.getBuild().getFinalName() + ".cust"; File finalDir = new * File(buildDirectory, archiveName); * * // Configure archiver MavenArchiver archiver = new MavenArchiver(); * archiver.setArchiver(jarArchiver); archiver.setOutputFile(finalDir); */ try { if (!SdkVerifier.isAvailable(sdk)) { throw new MojoExecutionException("Selected version " + sdk + " is not available!"); } } catch (IOException e2) { throw new MojoExecutionException("SDK verification failed!"); } catch (InterruptedException e2) { throw new MojoExecutionException("SDK verification interrupted!"); } try { init(); configure(); ProcessBuilder pb = new ProcessBuilder(xcodeCommandLine.getAbsolutePath()); // Include errors in output pb.redirectErrorStream(true); List<String> commands = pb.command(); if (xcodeProject != null) { commands.add("-project"); commands.add(xcodeProject); } if (StringUtils.isNotBlank(configuration)) { commands.add("-configuration"); commands.add(configuration); } if (StringUtils.isNotBlank(sdk)) { commands.add("-sdk"); commands.add(sdk); } commands.add("OBJROOT=" + buildDirectory); commands.add("SYMROOT=" + buildDirectory); commands.add("DSTROOT=" + buildDirectory); if (StringUtils.isNotBlank(xcodeTarget)) { commands.add("-target"); commands.add(xcodeTarget); } if (StringUtils.isNotBlank(gccpreprocessor)) { commands.add("GCC_PREPROCESSOR_DEFINITIONS=" + gccpreprocessor); } if (unittest) { commands.add("clean"); commands.add("build"); } getLog().info("List of commands" + pb.command()); // pb.command().add("install"); pb.directory(new File(basedir)); Process child = pb.start(); // Consume subprocess output and write to stdout for debugging InputStream is = new BufferedInputStream(child.getInputStream()); int singleByte = 0; while ((singleByte = is.read()) != -1) { // output.write(buffer, 0, bytesRead); System.out.write(singleByte); } child.waitFor(); int exitValue = child.exitValue(); getLog().info("Exit Value: " + exitValue); if (exitValue != 0) { throw new MojoExecutionException("Compilation error occured. Resolve the error(s) and try again!"); } if (!unittest) { //In case of unit testcases run, the APP files will not be generated. createdSYM(); createApp(); } /* * child.waitFor(); * * InputStream in = child.getInputStream(); InputStream err = * child.getErrorStream(); getLog().error(sb.toString()); */ } catch (IOException e) { getLog().error("An IOException occured."); throw new MojoExecutionException("An IOException occured", e); } catch (InterruptedException e) { getLog().error("The clean process was been interrupted."); throw new MojoExecutionException("The clean process was been interrupted", e); } catch (MojoFailureException e) { // TODO Auto-generated catch block e.printStackTrace(); } File directory = new File(this.basedir + "/pom.xml"); this.project.getArtifact().setFile(directory); }
From source file:edu.clemson.cs.nestbed.server.management.deployment.ProgramDeploymentManagerImpl.java
public List<String> installTraceReceiver(List<MoteTestbedAssignment> interestingMotes) throws RemoteException { List<String> success = new ArrayList<String>(); for (MoteTestbedAssignment mta : interestingMotes) { Mote mote = MoteManagerImpl.getInstance().getMote(mta.getMoteID()); int address = mta.getMoteAddress(); String moteSerialID = mote.getMoteSerialID(); String tosPlatform = "telosb"; // Should really look this up String commPort = "/dev/motes/" + moteSerialID; try {// w ww . ja v a 2 s . c om ProcessBuilder processBuilder; log.info("Installing: " + INSTALL + " " + TRACE_RECORDER_DIR + " " + tosPlatform + " " + address + " " + commPort); processBuilder = new ProcessBuilder(INSTALL, TRACE_RECORDER_DIR, tosPlatform, Integer.toString(address), commPort); processBuilder.redirectErrorStream(true); Process process = processBuilder.start(); process.waitFor(); int exitValue = process.exitValue(); if (exitValue != 0) { log.error(moteSerialID + " -- Install failed with exit code: " + exitValue); } success.add(Integer.toString(address)); } catch (Exception ex) { log.error("installTraceReceiver failed for mote: " + address, ex); } } return success; }