public static boolean testCommand( final Context context, final String command, final String contains, final List<String> arguments) { try { final List<String> commandAndArgs = new ArrayList<String>(); commandAndArgs.add(command); commandAndArgs.addAll(arguments); final ProcessBuilder pb = new ProcessBuilder(commandAndArgs); logCommand(context, pb); final Process compilation = pb.start(); final ConsumeStream result = ConsumeStream.start(compilation.getInputStream(), null); final ConsumeStream error = ConsumeStream.start(compilation.getErrorStream(), null); compilation.waitFor(); result.join(); error.join(); return error.output.toString().contains(contains) || result.output.toString().contains(contains); } catch (IOException ex) { context.log(ex.getMessage()); return false; } catch (InterruptedException ex) { context.log(ex.getMessage()); return false; } }
public Process createProcess() throws ExecutionException { if (LOG.isDebugEnabled()) { LOG.debug("Executing [" + getCommandLineString() + "]"); } List<String> commands; try { checkWorkingDirectory(); if (StringUtil.isEmptyOrSpaces(myExePath)) { throw new ExecutionException( IdeBundle.message("run.configuration.error.executable.not.specified")); } commands = CommandLineUtil.toCommandLine(myExePath, myProgramParams.getList()); } catch (ExecutionException e) { LOG.warn(e); throw e; } try { ProcessBuilder builder = new ProcessBuilder(commands); setupEnvironment(builder.environment()); builder.directory(myWorkDirectory); builder.redirectErrorStream(myRedirectErrorStream); return builder.start(); } catch (IOException e) { LOG.warn(e); throw new ProcessNotCreatedException(e.getMessage(), e, this); } }
private void startupProcess(boolean restart) throws IOException { if (myIsShuttingDown) { return; } if (ShutDownTracker.isShutdownHookRunning()) { myIsShuttingDown = true; return; } if (myStartAttemptCount++ > MAX_PROCESS_LAUNCH_ATTEMPT_COUNT) { notifyOnFailure(ApplicationBundle.message("watcher.failed.to.start"), null); return; } if (restart) { shutdownProcess(); } LOG.info("Starting file watcher: " + myExecutable); ProcessBuilder processBuilder = new ProcessBuilder(myExecutable.getAbsolutePath()); Process process = processBuilder.start(); myProcessHandler = new MyProcessHandler(process); myProcessHandler.addProcessListener(new MyProcessAdapter()); myProcessHandler.startNotify(); if (restart) { List<String> recursive = myRecursiveWatchRoots; List<String> flat = myFlatWatchRoots; if (recursive.size() + flat.size() > 0) { setWatchRoots(recursive, flat, true); } } }
/** Run new Maven os process with given arguments and commands. */ public void execute() { Process process = null; BufferedReader br = null; try { ProcessBuilder processBuilder = getProcessBuilder(); processBuilder.redirectErrorStream(true); log.info("Starting process: " + processBuilder.command()); process = processBuilder.start(); // Read output br = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while ((line = br.readLine()) != null) { System.out.println(line); } process.waitFor(); } catch (Exception e) { throw new RuntimeException(e); } finally { close(br); destroyProcess(process); } }
public static String test123() { String r = ""; try { // System.setSecurityManager(null); // String[] callArgs = {"mkdir", "/home/alexis/test123"}; String[] callArgs = {"ls"}; ProcessBuilder pb = new ProcessBuilder(callArgs); pb.redirectErrorStream(true); Process p = pb.start(); p.waitFor(); // BufferedReader br = new BufferedReader(new InputStreamReader(p.getErrorStream() )); BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = ""; System.out.println("Start Output"); while ((line = br.readLine()) != null) r += line + "\n"; System.out.println("End Output"); /*Process p = Runtime.getRuntime().exec(callArgs); p.waitFor(); System.out.println("Test Complete");*/ r = line; } catch (IOException e) { System.out.println(e); r = "Test failed"; } catch (Exception e) { } return r; }
private void setExecutablePermissions(File gradleHome) { if (isWindows()) { return; } File gradleCommand = new File(gradleHome, "bin/gradle"); String errorMessage = null; try { ProcessBuilder pb = new ProcessBuilder("chmod", "755", gradleCommand.getCanonicalPath()); Process p = pb.start(); if (p.waitFor() == 0) { System.out.println("Set executable permissions for: " + gradleCommand.getAbsolutePath()); } else { BufferedReader is = new BufferedReader(new InputStreamReader(p.getInputStream())); Formatter stdout = new Formatter(); String line; while ((line = is.readLine()) != null) { stdout.format("%s%n", line); } errorMessage = stdout.toString(); } } catch (IOException e) { errorMessage = e.getMessage(); } catch (InterruptedException e) { errorMessage = e.getMessage(); } if (errorMessage != null) { System.out.println( "Could not set executable permissions for: " + gradleCommand.getAbsolutePath()); System.out.println("Please do this manually if you want to use the Gradle UI."); } }
public static Either<CommandResult> runCommand( final Context context, final String command, final File path, final List<String> arguments) { try { final List<String> commandAndArgs = new ArrayList<String>(); commandAndArgs.add(command); commandAndArgs.addAll(arguments); final ProcessBuilder pb = new ProcessBuilder(commandAndArgs); if (path != null) { pb.directory(path); } logCommand(context, pb); final Process compilation = pb.start(); final ConsumeStream result = ConsumeStream.start(compilation.getInputStream(), context); final ConsumeStream error = ConsumeStream.start(compilation.getErrorStream(), context); final int exitCode = compilation.waitFor(); result.join(); error.join(); if (result.exception != null) { return Either.fail(result.exception); } if (error.exception != null) { return Either.fail(error.exception); } return Either.success( new CommandResult(result.output.toString(), error.output.toString(), exitCode)); } catch (IOException ex) { return Either.fail(ex); } catch (InterruptedException ex) { return Either.fail(ex); } }
/** * Creates a deep copy of this instance. * * @see Cloneable#clone() */ public ProcessBuilder copy() { final ProcessBuilder builder = new ProcessBuilder(); builder.inherit_parent_environment = inherit_parent_environment; builder.parent_environment = parent_environment; builder.executable = executable; builder.env = env.copy(); builder.arguments.addAll(arguments); builder.listeners.addAll(listeners); return builder; }
private void initLogstash(String testName) { initLogstashHost(); String pathToLogstash = SGTestHelper.getSGTestRootDir().replace("\\", "/") + "/src/main/resources/logstash"; String confFilePath = pathToLogstash + "/logstash-shipper-client.conf"; String fixedTestName = testName.substring(0, testName.length() - 2); String backupFilePath = pathToLogstash + "/logstash-shipper-client-" + fixedTestName + ".conf"; if (process == null) { try { LogUtils.log("copying file " + confFilePath + " to " + backupFilePath); IOUtils.copyFile(confFilePath, backupFilePath); // backupFilePath = IOUtils.backupFile(confFilePath); IOUtils.replaceTextInFile( backupFilePath, "<path_to_test_folder>", SGTestHelper.getSGTestRootDir().replace("\\", "/") + "/../" + suiteName + "/" + testName); IOUtils.replaceTextInFile(backupFilePath, "<suite_name>", suiteName); IOUtils.replaceTextInFile(backupFilePath, "<test_name>", testName); IOUtils.replaceTextInFile(backupFilePath, "<build_number>", buildNumber); IOUtils.replaceTextInFile(backupFilePath, "<version>", version); IOUtils.replaceTextInFile(backupFilePath, "<host>", logstashHost); String logstashJarPath = DeploymentUtils.getLocalRepository() + "net/logstash/1.2.2/logstash-1.2.2.jar"; logstashLogPath = pathToLogstash + "/logstash-" + fixedTestName + ".txt"; String cmdLine = "java -jar " + logstashJarPath + " agent -f " + backupFilePath + " -l " + logstashLogPath; final String[] parts = cmdLine.split(" "); final ProcessBuilder pb = new ProcessBuilder(parts); LogUtils.log("Executing Command line: " + cmdLine); TimeUnit.SECONDS.sleep(1); process = pb.start(); } catch (Exception e) { e.printStackTrace(); } } }
String confValue(String name, List<String> extraPaths, boolean daemon) { // The original code from python started a process that started a jvm // with backtype.storm.command.config_value main method that would // read the conf value and print it out to an output stream. python // tapped on to the output stream of that subprocess and returned the // confvalue for the name. Because the pythong code has been shipped // to java now it should not spawn a new process which is a jvm since // we are already in jvm. Instead it should just be doing as the code // commeneted below. // However looking at the pythong code it was // starting a jvm with -cp argument that had classpaths which might // not be available to this java process. Hence there is a chance // that the below code might break existing scripts. As a result I // have decided to still spawn a new process from java just like // python with similar classpaths being constructed for the jvm // execution /*IFn fn = Utils.loadClojureFn("backtype.storm.config", "read-storm-config"); Object o = fn.invoke(); return ((Map) o).get(name).toString();*/ String confValue = ""; ProcessBuilder processBuilder = new ProcessBuilder( this.javaCommand, "-client", this.getConfigOptions(), "-Dstorm.conf.file=" + this.configFile, "-cp", this.getClassPath(extraPaths, daemon), "backtype.storm.command.config_value", name); BufferedReader br; try { Process process = processBuilder.start(); br = new BufferedReader( new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8)); process.waitFor(); String line; while ((line = br.readLine()) != null) { String[] tokens = line.split(" "); if ("VALUE:".equals(tokens[0])) { confValue = StringUtils.join(Arrays.copyOfRange(tokens, 1, tokens.length), " "); break; } } br.close(); } catch (Exception ex) { System.out.println( "Exception occured while starting process via " + "processbuilder " + ex.getMessage()); } return confValue; }
@Override public Object apply(List<Object> args, Context context) throws ParseException { File outFile = null; String editor = getEditor(); try { outFile = File.createTempFile("stellar_shell", "out"); if (args.size() > 0) { String arg = (String) args.get(0); try (PrintWriter pw = new PrintWriter(outFile)) { IOUtils.write(arg, pw); } } } catch (IOException e) { String message = "Unable to create temp file: " + e.getMessage(); LOG.error(message, e); throw new IllegalStateException(message, e); } Optional<Object> console = context.getCapability(CONSOLE, false); try { PausableInput.INSTANCE.pause(); // shut down the IO for the console ProcessBuilder processBuilder = new ProcessBuilder(editor, outFile.getAbsolutePath()); processBuilder.redirectInput(ProcessBuilder.Redirect.INHERIT); processBuilder.redirectOutput(ProcessBuilder.Redirect.INHERIT); processBuilder.redirectError(ProcessBuilder.Redirect.INHERIT); try { Process p = processBuilder.start(); // wait for termination. p.waitFor(); try (BufferedReader br = new BufferedReader(new FileReader(outFile))) { String ret = IOUtils.toString(br).trim(); return ret; } } catch (Exception e) { String message = "Unable to read output: " + e.getMessage(); LOG.error(message, e); return null; } } finally { try { PausableInput.INSTANCE.unpause(); if (console.isPresent()) { ((Console) console.get()).pushToInputStream("\b\n"); } } catch (IOException e) { LOG.error("Unable to unpause: " + e.getMessage(), e); } if (outFile.exists()) { outFile.delete(); } } }
void executeStormClass( String className, String jvmType, List<String> jvmOptions, List<String> extraJars, List<String> args, boolean fork, boolean daemon, String daemonName) { List<String> extraPaths = new ArrayList<>(); extraPaths.add(this.clusterConfDirectory); String stormLogDirectory = this.confValue("storm.log.dir", extraPaths, daemon); if ((stormLogDirectory == null) || ("".equals(stormLogDirectory)) || ("nil".equals(stormLogDirectory))) { stormLogDirectory = this.stormHomeDirectory + this.fileSeparator + "logs"; } List<String> commandList = new ArrayList<String>(); commandList.add(this.javaCommand); commandList.add(jvmType); commandList.add("-Ddaemon.name=" + daemonName); commandList.add(this.getConfigOptions()); commandList.add("-Dstorm.home=" + this.stormHomeDirectory); commandList.add("-Dstorm.log.dir=" + stormLogDirectory); commandList.add( "-Djava.library.path=" + this.confValue("java.library.path", extraJars, daemon)); commandList.add("-Dstorm.conf.file=" + this.configFile); commandList.add("-cp"); commandList.add(this.getClassPath(extraJars, daemon)); commandList.addAll(jvmOptions); commandList.add(className); commandList.addAll(args); ProcessBuilder processBuilder = new ProcessBuilder(commandList); processBuilder.inheritIO(); try { Process process = processBuilder.start(); System.out.println("Executing the command: "); String commandLine = StringUtils.join(commandList, " "); System.out.println(commandLine); if (daemon == true) { Runtime.getRuntime().addShutdownHook(new ShutdownHookThread(process, commandLine)); } System.out.println("Waiting for subprocess to finish"); process.waitFor(); System.out.println("subprocess finished"); System.out.println("Exit value from subprocess is :" + process.exitValue()); } catch (Exception ex) { System.out.println( "Exception occured while starting process via " + "processbuilder " + ex.getMessage()); } }
private static void logCommand(final Context context, final ProcessBuilder builder) { final StringBuilder description = new StringBuilder("Running: "); for (final String arg : builder.command()) { description.append(arg).append(" "); } context.log(description.toString()); }
public void restartApplication() { try { final String javaBin = System.getProperty("java.home") + File.separator + "bin" + File.separator + "javaw"; final File currentJar = new File(network.class.getProtectionDomain().getCodeSource().getLocation().toURI()); System.out.println("javaBin " + javaBin); System.out.println("currentJar " + currentJar); System.out.println("currentJar.getPath() " + currentJar.getPath()); /* is it a jar file? */ // if(!currentJar.getName().endsWith(".jar")){return;} try { // xmining = 0; // systemx.shutdown(); } catch (Exception e) { e.printStackTrace(); } /* Build command: java -jar application.jar */ final ArrayList<String> command = new ArrayList<String>(); command.add(javaBin); command.add("-jar"); command.add("-Xms256m"); command.add("-Xmx1024m"); command.add(currentJar.getPath()); final ProcessBuilder builder = new ProcessBuilder(command); builder.start(); // try{Thread.sleep(10000);} catch (InterruptedException e){} // close and exit SystemTray.getSystemTray().remove(network.icon); System.exit(0); } // try catch (Exception e) { JOptionPane.showMessageDialog(null, e.getCause()); } } // ******************************
/** * Get Java process builder with basic command line execution based on given os nature. * * @return */ private ProcessBuilder getProcessBuilder() { List<String> commands = new ArrayList<String>(); if (SystemUtils.IS_OS_UNIX) { commands.add(BASH); commands.add(BASH_OPTION_C); } else { commands.add(CMD); commands.add(CMD_OPTION_C); } commands.add(buildCommand()); ProcessBuilder pb = new ProcessBuilder(commands); pb.directory(Paths.get("").toFile().getAbsoluteFile()); log.trace("Returning ProcessBuilder for command:" + commands); return pb; }
private void startProcess(List<String> command) { ProcessBuilder processBuilder = new ProcessBuilder(command); DarkMod darkMod = DarkMod.getInstance(); DarkModUI ui = darkMod.getUI(); try { if (ui != null) { ui.setVisible(false); ui.dispose(); } Process process = processBuilder.start(); StreamRedirectFactory.createInputToOutputRedirect(process.getInputStream(), System.out); StreamRedirectFactory.createInputToOutputRedirect(process.getErrorStream(), System.err); StreamRedirectFactory.createInputToOutputRedirect(System.in, process.getOutputStream()); System.exit(process.waitFor()); } catch (Exception exception) { exception.printStackTrace(); System.exit(-1); } }
private Process openMediaFile_inLinux(MediaFile mf) { ProcessBuilder p; List<String> path = new ArrayList<String>(); path.add("vlc"); if (mf.isMediaType(TypeX.MEDIA_DIR) && mf.isDirContainsType(TypeX.VIDEO)) // open videos in queue { MediaFile[] medFold = mf.listMediaFiles(); for (MediaFile f : medFold) { if (f.isMediaType(TypeX.VIDEO)) { path.add(f.getAbsoluteFilePath()); } } } else if (mf.isMediaType(TypeX.VIDEO)) { path.add(mf.getAbsoluteFilePath()); } if (mf.isMediaType(TypeX.MEDIA_DIR) && !mf.isDirContainsType(TypeX.VIDEO)) { System.out.println("******Can't open none video files****"); for (MediaFile f : mf.listMediaFiles()) { System.out.println("" + f.getName()); } return null; } else if (!mf.isMediaType(TypeX.MEDIA_DIR) && !mf.isMediaType(TypeX.VIDEO)) { System.out.println("******Can't open none video files****"); System.out.println("" + mf.getName()); return null; } p = new ProcessBuilder(path); try { return p.start(); } catch (IOException e) { System.out.println("Runtime error : " + e); return null; } }
public static void main(String args[]) throws InterruptedException, IOException { List<String> command = new ArrayList<String>(); command.add(System.getenv("windir") + "\\system32\\" + "tree.com"); command.add("/A"); ProcessBuilder builder = new ProcessBuilder(command); Map<String, String> environ = builder.environment(); builder.directory(new File(System.getenv("temp"))); System.out.println("Directory : " + System.getenv("temp")); final Process process = builder.start(); InputStream is = process.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line; while ((line = br.readLine()) != null) { System.out.println(line); } System.out.println("Program terminated!"); }
/** * Executes a command as {@code user}. Saves the stdout/stderr in the corresponding fields and * returns the return code of the child process. * * @param cmd The command to execute * @param data The data to send to the stdin of the process * @param timelimt How many seconds the command can run * @param memlimit How many megabytes the command can use */ private int exec(String cmdS, String data, int timelimit, int memlimit) throws Exception { ArrayList<String> cmd = new ArrayList<String>(cmdPrefix); cmd.add("-m"); cmd.add("" + memlimit); cmd.add("-c"); cmd.add("" + timelimit); cmd.add("-w"); cmd.add("" + (3 * timelimit + 1)); cmd.add("-x"); cmd.add(cmdS); String tmp = ""; for (String cs : cmd) tmp += " \"" + cs + "\""; log.fine("exec " + tmp); ProcessBuilder pb = new ProcessBuilder(cmd); pb.directory(workDir); Process p = pb.start(); OutputStreamWriter writer = new OutputStreamWriter(p.getOutputStream()); StreamReader rOut = new StreamReader(p.getInputStream()); StreamReader rErr = new StreamReader(p.getErrorStream()); rOut.start(); rErr.start(); // TODO I think this may block for big tests. Check and Fix. // send and receive data "in parallel" writer.write(data); writer.flush(); writer.close(); rOut.join(); rErr.join(); stdout = rOut.result; stderr = rErr.result; if (rOut.exception != null) throw rOut.exception; if (rErr.exception != null) throw rErr.exception; // log.finer("out: " + stdout); // log.finer("err: " + stderr); // log.finer("done exec"); return p.waitFor(); }
private void startProcess() throws IOException, SrvrMgrException { ProcessBuilder builder = new ProcessBuilder(runTimeCommand); this.lastCommandDate = System.currentTimeMillis(); try { builder.redirectErrorStream(true); this.process = builder.start(); } catch (Exception ex) { throw new SrvrMgrException("Can't start process " + Arrays.toString(runTimeCommand)); } this.locked = false; this.processInput = new BufferedWriter(new OutputStreamWriter(process.getOutputStream())); this.processOutputStream = process.getInputStream(); this.PID = getProcessId(process); /*TODO: debug*/ processLog(runTimeCommand, "Input Command"); byte[] inputData = new byte[1024]; String result = ""; int numBytes; while ((numBytes = readInputStreamWithTimeout(processOutputStream, inputData, 1000)) > 0 || !result.contains("srvrmgr>")) { if (numBytes > 0) result += new String(inputData, StandardCharsets.UTF_8); else { try { Thread.sleep(500); } catch (InterruptedException ex) { } } if (result.contains(("Fatal error"))) { this.process.destroy(); throw new SrvrMgrException("Could not open connection to Siebel Gateway configuration"); } // System.out.println(result); inputData = new byte[1024]; } /*TODO: debug*/ processLog(result, "Output after process creation"); }
private void spawnWorkerAndWait(Script myWhatToDo) { String currentClassPathString = System.getProperty("java.class.path"); Set<File> classPaths = calculateClassPath(new File(System.getProperty("user.dir"))); List<String> commandLine = new ArrayList<String>(); commandLine.add(JavaEnvUtils.getJreExecutable("java")); commandLine.addAll(Arrays.asList(JVM_ARGS)); StringBuilder sb = new StringBuilder(); String pathSeparator = System.getProperty("path.separator"); for (File cp : classPaths) { sb.append(pathSeparator); sb.append(cp.getAbsolutePath()); } // copy ant libs for (String entry : currentClassPathString.split(pathSeparator)) { if (entry.indexOf("ant") >= 0) { sb.append(pathSeparator); sb.append(entry); } } commandLine.add("-classpath"); commandLine.add(sb.toString()); commandLine.add(MakeWorker.class.getCanonicalName()); try { commandLine.add(myWhatToDo.dumpToTmpFile().getAbsolutePath()); } catch (FileNotFoundException e) { throw new BuildException(e); } ProcessBuilder pb = new ProcessBuilder(JavaEnvUtils.getJreExecutable("java")); pb.command(commandLine); pb.directory(new File(System.getProperty("user.dir"))); executeProcess(pb); }
/** * Run command in separated console. * * @param workFolder Work folder for command. * @param args A string array containing the program and its arguments. * @return Started process. * @throws IOException If failed to start process. */ public static Process openInConsole(@Nullable File workFolder, String... args) throws IOException { String[] commands = args; String cmd = F.concat(Arrays.asList(args), " "); if (U.isWindows()) commands = F.asArray("cmd", "/c", String.format("start %s", cmd)); if (U.isMacOs()) commands = F.asArray( "osascript", "-e", String.format("tell application \"Terminal\" to do script \"%s\"", cmd)); if (U.isUnix()) commands = F.asArray("xterm", "-sl", "1024", "-geometry", "200x50", "-e", cmd); ProcessBuilder pb = new ProcessBuilder(commands); if (workFolder != null) pb.directory(workFolder); return pb.start(); }
public boolean ok(String out, String reference) { try { File fo = File.createTempFile("homeworkeval", ".out"); File fr = File.createTempFile("homeworkeval", ".ref"); log.fine("Running custom validator."); save(out, fo); save(reference, fr); ArrayList<String> c = new ArrayList<String>(); c.add(command); c.add(fo.getPath()); c.add(fr.getPath()); ProcessBuilder pb = new ProcessBuilder(c); Process p = pb.start(); int rc = p.waitFor(); fo.delete(); fr.delete(); log.fine("Custom validator " + command + " says " + rc); return rc == 0; } catch (Exception e) { // Assume NOK. Don't propagate info to the client. log.finer("exc: " + UtilSrv.describe(e)); return false; } }
private void restartApp() { if (!updateThis()) { JOptionPane.showMessageDialog( getProgressPanel().getParent(), "The update has completed successfully, but the control panel " + "was unable to restart itself automatically. Please close then " + "restart the control panel manually to use the updated version.", "Update Completed", JOptionPane.WARNING_MESSAGE); return; } String javaBin = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java"; try { String appPath = FileUtil.getJarFile().getPath(); String newJarName = _differ.getNewJarName(); if (!(newJarName == null || appPath.endsWith(newJarName))) { appPath = getPathForNewAppName(appPath); if (appPath == null) { throw new IllegalArgumentException(); } } java.util.List<String> command = new ArrayList<String>(); command.add(javaBin); command.add("-jar"); command.add(FileUtil.getJarFile().getPath()); command.add("-updateCompleted"); ProcessBuilder builder = new ProcessBuilder(command); builder.start(); System.exit(0); } catch (Exception e) { showError("Failed to restart the Control Panel. Please restart manually."); } }
// Creates a new thread, runs the program in that thread, and reports any errors as needed. private void run(String clazz) { try { // Makes sure the JVM resets if it's already running. if (JVMrunning) kill(); // Some String constants for java path and OS-specific separators. String separator = System.getProperty("file.separator"); String path = System.getProperty("java.home") + separator + "bin" + separator + "java"; // Tries to run compiled code. ProcessBuilder builder = new ProcessBuilder(path, clazz); // Should be good now! Everything past this is on you. Don't mess it up. println( "Build succeeded on " + java.util.Calendar.getInstance().getTime().toString(), progErr); println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~", progErr); JVM = builder.start(); // Note that as of right now, there is no support for input. Only output. Reader errorReader = new InputStreamReader(JVM.getErrorStream()); Reader outReader = new InputStreamReader(JVM.getInputStream()); // Writer inReader = new OutputStreamWriter(JVM.getOutputStream()); redirectErr = redirectIOStream(errorReader, err); redirectOut = redirectIOStream(outReader, out); // redirectIn = redirectIOStream(null, inReader); } catch (IOException e) { // JVM = builder.start() can throw this. println("IOException when running the JVM.", progErr); e.printStackTrace(); displayLog(); return; } }
private void makeWithAnt() { String antHome = System.getProperty("ant.home"); if (antHome == null || !new File(antHome).exists()) { return; } String fileSeparator = System.getProperty("file.separator"); ProcessBuilder pb = new ProcessBuilder( JavaEnvUtils.getJreExecutable("java"), "-Dant.home=" + System.getProperty("ant.home"), "-cp", System.getProperty("ant.home") + fileSeparator + "lib" + fileSeparator + "ant-launcher.jar", "org.apache.tools.ant.launch.Launcher", "-buildfile", "AllTests/make_all_modules.xml"); pb.directory(new File(System.getProperty("user.dir"))); executeProcess(pb); }
private void executeProcess(ProcessBuilder pb) { final CyclicBarrier barrier = new CyclicBarrier(3); try { Process p = pb.start(); copyStream(p.getErrorStream(), System.err, barrier); copyStream(p.getInputStream(), System.out, barrier); p.waitFor(); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } try { barrier.await(); } catch (InterruptedException e) { } catch (BrokenBarrierException e) { } }
public static void main(String[] args) { ProcessBuilder process = new ProcessBuilder(); Integer port; if (process.environment().get("PORT") != null) { port = Integer.parseInt(process.environment().get("PORT")); } else { port = 4567; } staticFileLocation("/public"); String layout = "templates/layout.vtl"; get( "/", (request, response) -> { HashMap<String, Object> model = new HashMap<String, Object>(); model.put("template", "templates/index.vtl"); return new ModelAndView(model, layout); }, new VelocityTemplateEngine()); // get(/) type of route get this url.. get( "/tasks", (request, response) -> { HashMap<String, Object> model = new HashMap<String, Object>(); model.put("tasks", Task.all()); model.put("template", "templates/tasks.vtl"); return new ModelAndView(model, layout); }, new VelocityTemplateEngine()); // After they submit the form, this is where they will be taken /tasks.vtl // get("tasks/new", (request, response) -> { // HashMap<String, Object> model = new HashMap<String, Object>(); // model.put("template", "templates/task-form.vtl"); // return new ModelAndView(model, layout); // }, new VelocityTemplateEngine()); // //task-form is where client inputs data and hits submit post( "/tasks", (request, response) -> { HashMap<String, Object> model = new HashMap<String, Object>(); Category category = Category.find(Integer.parseInt(request.queryParams("categoryId"))); String description = request.queryParams("description"); Task newTask = new Task(description); category.addTask(newTask); model.put("category", category); model.put("template", "templates/success.vtl"); return new ModelAndView(model, layout); }, new VelocityTemplateEngine()); // grabs information and makes a new description of the information in the array // takes you to a new page get( "/tasks/:id", (request, response) -> { HashMap<String, Object> model = new HashMap<String, Object>(); Task task = Task.find(Integer.parseInt(request.params(":id"))); model.put("task", task); model.put("template", "templates/task.vtl"); return new ModelAndView(model, layout); }, new VelocityTemplateEngine()); get( "/categories", (request, response) -> { HashMap<String, Object> model = new HashMap<String, Object>(); model.put("categories", Category.all()); model.put("template", "templates/categories.vtl"); return new ModelAndView(model, layout); }, new VelocityTemplateEngine()); get( "/categories/new", (request, response) -> { HashMap<String, Object> model = new HashMap<String, Object>(); model.put("template", "templates/category-form.vtl"); return new ModelAndView(model, layout); }, new VelocityTemplateEngine()); post( "/categories", (request, response) -> { HashMap<String, Object> model = new HashMap<String, Object>(); String name = request.queryParams("name"); Category newCategory = new Category(name); model.put("category", newCategory); model.put("template", "templates/success.vtl"); return new ModelAndView(model, layout); }, new VelocityTemplateEngine()); get( "/categories/:id", (request, response) -> { HashMap<String, Object> model = new HashMap<String, Object>(); model.put("category", Category.find(Integer.parseInt(request.params(":id")))); model.put("template", "templates/category.vtl"); return new ModelAndView(model, layout); }, new VelocityTemplateEngine()); get( "/categories/:id/tasks/new", (request, response) -> { HashMap<String, Object> model = new HashMap<String, Object>(); model.put("category", Category.find(Integer.parseInt(request.params(":id")))); model.put("template", "templates/category-tasks-form.vtl"); return new ModelAndView(model, layout); }, new VelocityTemplateEngine()); } // end of main
private void initLogstash2(ITestResult tr) { initLogstashHost(); String simpleClassName = tr.getTestClass().getRealClass().getSimpleName(); String pathToLogstash = SGTestHelper.getSGTestRootDir().replace("\\", "/") + "/src/main/resources/logstash"; String confFilePath2 = pathToLogstash + "/logstash-shipper-client-2.conf"; String backupFilePath2 = pathToLogstash + "/logstash-shipper-client-2-" + simpleClassName + ".conf"; File backupFile2 = new File(backupFilePath2); LogUtils.log( "trying to start logstash agent number 2. simple class name is " + simpleClassName); if (backupFile2.exists()) { LogUtils.log("the file " + backupFilePath2 + " already exists. not starting logstash"); } if (!isAfter(tr) && !backupFile2.exists()) { try { // backupFilePath2 = IOUtils.backupFile(confFilePath2); LogUtils.log("copying file " + confFilePath2 + " to " + backupFilePath2); IOUtils.copyFile(confFilePath2, backupFilePath2); IOUtils.replaceTextInFile(backupFilePath2, "<path_to_build>", SGTestHelper.getBuildDir()); IOUtils.replaceTextInFile( backupFilePath2, "<suite_number>", "suite_" + System.getProperty("iTests.suiteId", "0")); IOUtils.replaceTextInFile( backupFilePath2, "<path_to_test_class_folder>", SGTestHelper.getSGTestRootDir().replace("\\", "/") + "/../" + suiteName + "/" + tr.getTestClass().getName()); IOUtils.replaceTextInFile(backupFilePath2, "<suite_name>", suiteName); IOUtils.replaceTextInFile(backupFilePath2, "<test_name>", simpleClassName); IOUtils.replaceTextInFile(backupFilePath2, "<build_number>", buildNumber); IOUtils.replaceTextInFile(backupFilePath2, "<version>", version); IOUtils.replaceTextInFile(backupFilePath2, "<host>", logstashHost); String logstashJarPath = DeploymentUtils.getLocalRepository() + "net/logstash/1.2.2/logstash-1.2.2.jar"; logstashLogPath2 = pathToLogstash + "/logstash-" + simpleClassName + "-2.txt"; String cmdLine = "java -jar " + logstashJarPath + " agent -f " + backupFilePath2 + " -l " + logstashLogPath2; final String[] parts = cmdLine.split(" "); final ProcessBuilder pb = new ProcessBuilder(parts); LogUtils.log("Executing Command line: " + cmdLine); process2 = pb.start(); } catch (IOException e) { e.printStackTrace(); } } }
public int compileJava() { try { // create new bin directory boolean createBin = new File(classPath).mkdir(); // create new javac ProcessBuilder // ProcessBuilder pb = // new ProcessBuilder("javac", "-d", classPath, "./" + studentPath + "/*.java"); ProcessBuilder pbDir = new ProcessBuilder("dir"); // Determine current working directory File srcAbsPath = new File(sourcePath); srcAbsPathName = srcAbsPath.getAbsolutePath(); System.out.println("Compiler.java line 69 source path: " + sourcePath); System.out.println("Compiler.java line 69 source absolute path: " + srcAbsPathName); File cwd = pbDir.directory(); // debug code - to confirm correct directory // TestTools.dir(cwd); // NB - ProcessBuilder default is to return a null // pointer for the abstract path to indicate that it // is using System.Properties "user.dir", i.e., the // current system working directory; hence the // critical need to handle a NullPointerException. // Also returns a null pointer if the directory // doesn't exist. // all this is doing is changing the dir, can we approach this in a different way using a // value in our Data Object? -mh File nwd = TestTools.cd(cwd, studentPath); System.out.println("(Compiler.java line 88)new working directory: " + nwd.toString()); String studentPathName = nwd.getAbsolutePath(); File nwdPath = new File(studentPath); System.out.println("(Compiler.java line 91)new working directory path: " + studentPathName); // debug code to test new working directory // TestTools.dir(nwd); FileFilter filter = new FileFilter() {}; String[] javaFileList = nwdPath.list(filter); // set up output file File outputFile = new File(outputFileName); // System.out.println(outputFileName); outputFile.delete(); for (int k = 0; k < javaFileList.length; k++) { try { if (filter.accept(nwdPath, javaFileList[k]) == true) { System.out.println("COMPILER.JAVA (line 111) Compiling: " + javaFileList[k]); String compilePath = "javac" + "-d" + classPath + ".\\" + studentPath + "\\" + javaFileList[k]; System.out.println("Compiler.java 117 compile path: " + compilePath); ProcessBuilder pb = // new ProcessBuilder("javac ", "-d", classPath, ".\\" + studentPath + "\\" + // javaFileList[k]); new ProcessBuilder(compilePath); // System.out.println(pb.environment().toString()); <-- THIS IS VERY INTERESTING // Create environment map and set environmental variables Map<String, String> env = pb.environment(); env.clear(); env.put("PATH", path); env.put("CLASSPATH", classPath); // env.put("SOURCEPATH", sourcePath); // env.remove("OTHERVAR"); pb.redirectErrorStream(true); pb.redirectOutput(Redirect.appendTo(outputFile)); // start javac process Process p = pb.start(); // need other processes to wait for compilation to finish // basically joins the thread to the javac process to force sequential // execution - need to be careful - if any process hangs, whole run hangs success = p .waitFor(); // Returns the exit value of the process. By convention, 0 indicates // normal termination. // http://docs.oracle.com/javase/6/docs/api/java/lang/Process.html#waitFor%28%29 assert pb.redirectInput() == Redirect.PIPE; assert pb.redirectOutput().file() == outputFile; assert p.getInputStream().read() == -1; System.out.println("COMPILER.JAVA (line 138) end of loop, success = " + success); } } catch (Exception e) { System.out.println(" Compiler.java FOR LOOP Compile Exception: " + javaFileList[k]); } } } catch (Exception e) { System.out.println("Compile Exception, PROBABLY DUE TO FILE PATH"); System.out.println("source absolute path: " + srcAbsPathName); } return success; }