List of usage examples for java.lang ProcessBuilder ProcessBuilder
public ProcessBuilder(String... command)
From source file:com.gochinatv.datasync.util.Shell.java
/** * Run a command//from ww w .jav a2s .c o m */ private void runCommand() throws IOException { ProcessBuilder builder = new ProcessBuilder(getExecString()); Timer timeOutTimer = null; ShellTimeoutTimerTask timeoutTimerTask; timedOut = new AtomicBoolean(false); completed = new AtomicBoolean(false); if (environment != null) { builder.environment().putAll(this.environment); } if (dir != null) { builder.directory(this.dir); } process = builder.start(); if (timeOutInterval > 0) { timeOutTimer = new Timer(); timeoutTimerTask = new ShellTimeoutTimerTask(this); //One time scheduling. timeOutTimer.schedule(timeoutTimerTask, timeOutInterval); } final BufferedReader errReader = new BufferedReader(new InputStreamReader(process.getErrorStream())); BufferedReader inReader = new BufferedReader(new InputStreamReader(process.getInputStream())); final StringBuffer errMsg = new StringBuffer(); // read error and input streams as this would free up the buffers // free the error stream buffer Thread errThread = new Thread() { @Override public void run() { try { String line = errReader.readLine(); while ((line != null) && !isInterrupted()) { errMsg.append(line); errMsg.append(System.getProperty("line.separator")); line = errReader.readLine(); } } catch (IOException ioe) { LOG.warn("Error reading the error stream", ioe); } } }; try { errThread.start(); } catch (IllegalStateException ignored) { } try { parseExecResult(inReader); // parse the output // clear the input stream buffer String line = inReader.readLine(); while (line != null) { line = inReader.readLine(); } // wait for the process to finish and check the exit code exitCode = process.waitFor(); try { // make sure that the error thread exits errThread.join(); } catch (InterruptedException ie) { LOG.warn("Interrupted while reading the error stream", ie); } completed.set(true); //the timeout thread handling //taken care in finally block if (exitCode != 0) { throw new ExitCodeException(exitCode, errMsg.toString()); } } catch (InterruptedException ie) { throw new IOException(ie.toString()); } finally { if ((timeOutTimer != null) && !timedOut.get()) { timeOutTimer.cancel(); } // close the input stream try { inReader.close(); } catch (IOException ioe) { LOG.warn("Error while closing the input stream", ioe); } if (!completed.get()) { errThread.interrupt(); } try { errReader.close(); } catch (IOException ioe) { LOG.warn("Error while closing the error stream", ioe); } process.destroy(); lastTime = System.currentTimeMillis(); } }
From source file:com.ikanow.aleph2.data_model.utils.ProcessUtils.java
private static boolean killProcess(final String pid, final Optional<Integer> kill_signal) throws IOException { // kill -15 the process, wait a few cycles to let it die final ProcessBuilder pb = new ProcessBuilder(Arrays.asList("kill", "-" + kill_signal.orElse(15), pid)); logger.debug("trying to kill -" + kill_signal.orElse(15) + " pid: " + pid); final Process px = pb.start(); for (int i = 0; i < 5; ++i) { try {/* w w w . j a va 2 s . c o m*/ Thread.sleep(1000L); } catch (Exception e) { } if (!isProcessRunning(pid)) { break; } } if (!isProcessRunning(pid)) { return 0 == px.exitValue(); } else { //we are still alive, so send a harder kill signal if we haven't already sent a 9 if (kill_signal.isPresent() && kill_signal.get() == 9) { return false; } else { logger.debug("Timed out trying to kill: " + pid + " sending kill -9 to force kill"); return killProcess(pid, Optional.of(9)); } } }
From source file:eu.udig.omsbox.core.OmsScriptExecutor.java
/** * Execute an OMS script.// w w w . j a va2 s. c om * * @param script the script file or the script string. * @param internalStream * @param errorStream * @param loggerLevelGui the log level as presented in the GUI, can be OFF|ON. This is not the OMS logger level, which * in stead has to be picked from the {@link OmsBoxConstants#LOGLEVELS_MAP}. * @param ramLevel the heap size to use in megabytes. * @return the process. * @throws Exception */ public Process exec(String script, final PrintStream internalStream, final PrintStream errorStream, String loggerLevelGui, String ramLevel) throws Exception { if (loggerLevelGui == null) loggerLevelGui = OmsBoxConstants.LOGLEVEL_GUI_OFF; File scriptFile = new File(script); if (!scriptFile.exists()) { // if the file doesn't exist, it is a script, let's put it into a file scriptFile = File.createTempFile("omsbox_script_", ".oms"); BufferedWriter bw = null; try { bw = new BufferedWriter(new FileWriter(scriptFile)); bw.write(script); } finally { bw.close(); } } else { // it is a script in a file, read it to log it BufferedReader br = null; StringBuilder sb = new StringBuilder(); try { br = new BufferedReader(new FileReader(scriptFile)); String line = null; while ((line = br.readLine()) != null) { sb.append(line).append("\n"); } } finally { br.close(); } script = sb.toString(); } // tmp folder String tempdir = System.getProperty("java.io.tmpdir"); File omsTmp = new File(tempdir + File.separator + "oms"); if (!omsTmp.exists()) omsTmp.mkdirs(); List<String> arguments = new ArrayList<String>(); arguments.add(javaFile); // ram usage String ramExpr = "-Xmx" + ramLevel + "m"; arguments.add(ramExpr); // modules jars List<String> modulesJars = OmsModulesManager.getInstance().getModulesJars(); StringBuilder sb = new StringBuilder(); for (String moduleJar : modulesJars) { sb.append(File.pathSeparator).append(moduleJar); } String modulesJarsString = sb.toString().replaceFirst(File.pathSeparator, ""); String resourcesFlag = "-Doms.sim.resources=\"" + modulesJarsString + "\""; arguments.add(resourcesFlag); // grass gisbase String grassGisbase = OmsBoxPlugin.getDefault().getGisbasePreference(); if (grassGisbase != null && grassGisbase.length() > 0) { arguments.add("-D" + OmsBoxConstants.GRASS_ENVIRONMENT_GISBASE_KEY + "=" + grassGisbase); } String grassShell = OmsBoxPlugin.getDefault().getShellPreference(); if (grassShell != null && grassShell.length() > 0) { arguments.add("-D" + OmsBoxConstants.GRASS_ENVIRONMENT_SHELL_KEY + "=" + grassShell); } // all the arguments arguments.add("-cp"); arguments.add(classPath); arguments.add(CLI.class.getCanonicalName()); arguments.add("-r "); arguments.add("\"" + scriptFile.getAbsolutePath() + "\""); String homeDir = System.getProperty("java.io.tmpdir"); File homeFile = new File(homeDir); StringBuilder runSb = new StringBuilder(); for (String arg : arguments) { runSb.append(arg).append(" "); } String[] args; if (Platform.getOS().equals(Platform.OS_WIN32)) { File tmpRunFile = new File(homeFile, "udig_spatialtoolbox.bat"); FileUtils.writeStringToFile(tmpRunFile, "@echo off\n" + runSb.toString()); args = new String[] { "cmd", "/c", tmpRunFile.getAbsolutePath() }; } else { File tmpRunFile = new File(homeFile, "udig_spatialtoolbox.sh"); FileUtils.writeStringToFile(tmpRunFile, runSb.toString()); args = new String[] { "sh", tmpRunFile.getAbsolutePath() }; } // {javaFile, ramExpr, resourcesFlag, "-cp", classPath, // CLI.class.getCanonicalName(), "-r", // scriptFile.getAbsolutePath()}; ProcessBuilder processBuilder = new ProcessBuilder(args); // work in home // processBuilder.directory(homeFile); // environment Map<String, String> environment = processBuilder.environment(); // environment.put("CLASSPATH", classPath); final Process process = processBuilder.start(); internalStream.println( "Process started: " + new DateTime().toString(OmsBoxConstants.dateTimeFormatterYYYYMMDDHHMMSS)); internalStream.println(""); // command launched if (loggerLevelGui.equals(OmsBoxConstants.LOGLEVEL_GUI_ON)) { internalStream.println("------------------------------>8----------------------------"); internalStream.println("Launching command: "); internalStream.println("------------------"); List<String> command = processBuilder.command(); for (String arg : command) { internalStream.print(arg); internalStream.print(" "); } internalStream.println("\n"); internalStream.println("(you can run the above from command line, customizing the content)"); internalStream.println("----------------------------------->8---------------------------------"); internalStream.println(""); // script run internalStream.println("Script run: "); internalStream.println("-----------"); internalStream.println(script); internalStream.println(""); internalStream.println("------------------------------>8----------------------------"); internalStream.println(""); // environment used internalStream.println("Environment used: "); internalStream.println("-----------------"); Set<Entry<String, String>> entrySet = environment.entrySet(); for (Entry<String, String> entry : entrySet) { internalStream.print(entry.getKey()); internalStream.print(" =\t"); internalStream.println(entry.getValue()); } internalStream.println("------------------------------>8----------------------------"); internalStream.println(""); } internalStream.println(""); isRunning = true; new Thread() { public void run() { BufferedReader br = null; try { InputStream is = process.getInputStream(); InputStreamReader isr = new InputStreamReader(is); br = new BufferedReader(isr); String line; while ((line = br.readLine()) != null) { internalStream.println(line); } } catch (Exception e) { e.printStackTrace(); errorStream.println(e.getLocalizedMessage()); } finally { if (br != null) try { br.close(); } catch (IOException e) { e.printStackTrace(); } isRunning = false; updateListeners(); } internalStream.println(""); internalStream.println(""); internalStream.println("Process finished: " + new DateTime().toString(OmsBoxConstants.dateTimeFormatterYYYYMMDDHHMMSS)); }; }.start(); new Thread() { public void run() { BufferedReader br = null; try { InputStream is = process.getErrorStream(); InputStreamReader isr = new InputStreamReader(is); br = new BufferedReader(isr); String line; while ((line = br.readLine()) != null) { /* * remove of ugly recurring geotools warnings. Not nice, but * at least users do not get confused. */ if (ConsoleMessageFilter.doRemove(line)) { continue; } errorStream.println(line); } } catch (Exception e) { e.printStackTrace(); errorStream.println(e.getLocalizedMessage()); } finally { if (br != null) try { br.close(); } catch (IOException e) { e.printStackTrace(); } } }; }.start(); return process; }
From source file:com.yahoo.storm.yarn.TestIntegration.java
@SuppressWarnings({ "rawtypes", "unchecked" }) private static int execute(List<String> cmd) throws InterruptedException, IOException { LOG.info(Joiner.on(" ").join(cmd)); ProcessBuilder pb = new ProcessBuilder(cmd); Map env = pb.environment();// w w w . ja v a 2s.com env.putAll(System.getenv()); env.put(Environment.PATH.name(), "bin:" + storm_home + File.separator + "bin:" + env.get(Environment.PATH.name())); String yarn_conf_dir = yarn_site_xml.getParent().toString(); env.put("STORM_YARN_CONF_DIR", yarn_conf_dir); List<URL> logback_xmls = Utils.findResources("logback.xml"); if (logback_xmls != null && logback_xmls.size() >= 1) { String logback_xml = logback_xmls.get(0).getFile(); LOG.debug("logback_xml:" + yarn_conf_dir + File.separator + "logback.xml"); FileUtils.copyFile(new File(logback_xml), new File(yarn_conf_dir + File.separator + "logback.xml")); } List<URL> log4j_properties = Utils.findResources("log4j.properties"); if (log4j_properties != null && log4j_properties.size() >= 1) { String log4j_properties_file = log4j_properties.get(0).getFile(); LOG.debug("log4j_properties_file:" + yarn_conf_dir + File.separator + "log4j.properties"); FileUtils.copyFile(new File(log4j_properties_file), new File(yarn_conf_dir + File.separator + "log4j.properties")); } Process proc = pb.start(); Util.redirectStreamAsync(proc.getInputStream(), System.out); Util.redirectStreamAsync(proc.getErrorStream(), System.err); int status = proc.waitFor(); return status; }
From source file:de.teamgrit.grit.checking.compile.JavaCompileChecker.java
/** * Runs a command specified by a compiler invocation. * * @param compilerInvocation/*from w w w . ja va2 s. co m*/ * specifies what program with which flags is being executed * @param pathToSourceFolder * the path to the source folder of the submission * @return CompilerOutput with fields initialized according to the outcome * of the process * @throws BadFlagException * if a flag is not known to javac */ private CompilerOutput runJavacProcess(List<String> compilerInvocation, Path pathToSourceFolder, boolean junit) throws BadFlagException { Process compilerProcess = null; try { ProcessBuilder compilerProcessBuilder = new ProcessBuilder(compilerInvocation); // make sure the compiler stays in its directory. if (Files.isDirectory(pathToSourceFolder, LinkOption.NOFOLLOW_LINKS)) { compilerProcessBuilder.directory(pathToSourceFolder.toFile()); } else { compilerProcessBuilder.directory(pathToSourceFolder.getParent().toFile()); } compilerProcess = compilerProcessBuilder.start(); } catch (IOException e) { // If we cannot call the compiler we return a CompilerOutput // which is // 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 javac reports // nothing at all. 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); } compilerOutputStream.close(); compilerStreamReader.close(); compilerOutputBuffer.close(); compilerProcess.destroy(); } catch (IOException e) { // Reading might go wrong here if javac should unexpectedly // terminate LOGGER.severe("Could not read compiler ourput from its output stream." + " Aborting compile of: " + pathToSourceFolder.toString() + " Got message: " + e.getMessage()); compilerOutput.setClean(false); compilerOutput.setCompileStreamBroken(true); return compilerOutput; } splitCompilerOutput(compilerOutputLines, compilerOutput); if (compilerOutputLines.size() == 0) { compilerOutput.setClean(true); } return compilerOutput; }
From source file:org.springframework.cloud.deployer.spi.local.AbstractLocalDeployerSupport.java
/** * Builds the process builder./* www .j a v a 2 s. co m*/ * * @param request the request * @param appInstanceEnv the instance environment variables * @param appProperties the app properties * @return the process builder */ protected ProcessBuilder buildProcessBuilder(AppDeploymentRequest request, Map<String, String> appInstanceEnv, Map<String, String> appProperties, Optional<Integer> appInstanceNumber) { Assert.notNull(request, "AppDeploymentRequest must be set"); Assert.notNull(appProperties, "Args must be set"); String[] commands = null; Map<String, String> appInstanceEnvToUse = new HashMap<>(appInstanceEnv); Map<String, String> appPropertiesToUse = new HashMap<>(); handleAppPropertiesPassing(request, appProperties, appInstanceEnvToUse, appPropertiesToUse); if (request.getResource() instanceof DockerResource) { commands = this.dockerCommandBuilder.buildExecutionCommand(request, appInstanceEnvToUse, appPropertiesToUse, appInstanceNumber); } else { commands = this.javaCommandBuilder.buildExecutionCommand(request, appInstanceEnvToUse, appPropertiesToUse, appInstanceNumber); } // tweak escaping double quotes needed for windows if (LocalDeployerUtils.isWindows()) { for (int i = 0; i < commands.length; i++) { commands[i] = commands[i].replace("\"", "\\\""); } } ProcessBuilder builder = new ProcessBuilder(commands); if (!(request.getResource() instanceof DockerResource)) { builder.environment().putAll(appInstanceEnv); } retainEnvVars(builder.environment().keySet()); return builder; }
From source file:DAO.DataAccessObject.java
/**. * Standardkonstruktor/* ww w .ja v a2s. c o m*/ */ public DataAccessObject() { //Erstellung des Entity-Managers //Dadurch wird die Verbindung zur Datenbank hergestellt und bei //Bedarf werden die Entities in Datenbanktabellen umgesetzt this.em = Persistence.createEntityManagerFactory("Softwareprojekt2014PU").createEntityManager(); try { //Versuche den letzten Programmstart zu ermitteln Steuertabelle st = this.gibSteuerparameter("Letzter Programmstart"); //Wenn das Programm noch nie gestarten wurde... if (st == null) { //...soll ein Startskript ausgefhrt werden das die Datenbank //mit einigen Eintrge fllt die fr einen ordnungsgemen //Betrieb notwendig sind String[] befehl = { "CMD", "/C", "start", "/B", "fillDatabase.bat" }; ProcessBuilder pb = new ProcessBuilder(befehl); Process p = pb.start(); this.erstelleSteuereintrag("Installationsdatum", new Date().toString()); } //Erstelle bzw. berschreibe den Eintrag "Letztes Programmstart" this.erstelleSteuereintrag("Letzter Programmstart", new Date().toString()); } catch (ApplicationException | IOException e) { } }
From source file:edu.cornell.med.icb.clustering.MCLClusterer.java
/** * Groups instances into clusters. Returns the indices of the instances that belong to a cluster * as an int array in the list result./*from w ww . j a v a2 s .com*/ * * @param calculator The {@link SimilarityDistanceCalculator} * that should be used when clustering * @param qualityThreshold The QT clustering algorithm quality threshold (d) * @return The list of clusters. */ public List<int[]> cluster(final SimilarityDistanceCalculator calculator, final double qualityThreshold) { if (mclCommand == null) { throw new IllegalStateException("mcl command not set!"); } // reset cluster results clusterCount = 0; for (int i = 0; i < instanceCount; i++) { clusters[i].clear(); } BufferedReader br = null; try { final File mclInputFile = File.createTempFile("mcl-input", ".txt"); writeMCLInputFile(mclInputFile, calculator, qualityThreshold); final File mclOutputFile = File.createTempFile("mcl-output", ".txt"); final String[] command = { mclCommand, mclInputFile.getAbsolutePath(), "--abc", "-o", mclOutputFile.getAbsolutePath() }; LOGGER.info("Executing: " + ArrayUtils.toString(command)); final ProcessBuilder builder = new ProcessBuilder(command); builder.redirectErrorStream(true); final Process process = builder.start(); final InputStream is = process.getInputStream(); final InputStreamReader isr = new InputStreamReader(is); br = new BufferedReader(isr); String line; while ((line = br.readLine()) != null) { LOGGER.info(line); } process.waitFor(); LOGGER.info("Program terminated!"); readMCLOutputFile(mclOutputFile); } catch (IOException e) { LOGGER.error("Counldn't create MCL file", e); throw new ClusteringException("Counldn't create MCL file", e); } catch (InterruptedException e) { LOGGER.error("Interrupted!", e); Thread.currentThread().interrupt(); } finally { IOUtils.closeQuietly(br); } return getClusters(); }
From source file:net.solarnetwork.node.dao.jdbc.derby.DerbyOnlineSyncJob.java
private void performSync(String dbPath) { assert syncCommand != null; List<String> cmd = new ArrayList<String>(syncCommand.size()); for (String param : syncCommand) { param = param.replace(SOURCE_DIRECTORY_PLACEHOLDER, dbPath); param = param.replace(DESTINATION_DIRECTORY_PLACEHOLDER, destinationPath); cmd.add(param);//from w w w . j a v a 2s . c o m } if (log.isDebugEnabled()) { StringBuilder buf = new StringBuilder(); for (String p : cmd) { if (buf.length() > 0) { buf.append(' '); } buf.append(p); } log.debug("Derby sync command: {}", buf.toString()); } ProcessBuilder pb = new ProcessBuilder(cmd); BufferedReader in = null; PrintWriter out = null; try { Process pr = pb.start(); pr.waitFor(); if (pr.exitValue() == 0) { if (log.isDebugEnabled()) { in = new BufferedReader(new InputStreamReader(pr.getInputStream())); StringBuilder buf = new StringBuilder(); String line = null; while ((line = in.readLine()) != null) { buf.append(line).append('\n'); } log.debug("Derby sync command output:\n{}", buf.toString()); } log.info("Derby backup sync complete"); } else { StringBuilder buf = new StringBuilder(); in = new BufferedReader(new InputStreamReader(pr.getErrorStream())); String line = null; while ((line = in.readLine()) != null) { buf.append(line).append('\n'); } log.error("Sync command returned non-zero exit code {}: {}", pr.exitValue(), buf.toString().trim()); } } catch (IOException e) { throw new RuntimeException(e); } catch (InterruptedException e) { throw new RuntimeException(e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { // ignore } } if (out != null) { out.flush(); out.close(); } } }