List of usage examples for java.lang ProcessBuilder start
public Process start() throws IOException
From source file:de.fau.cs.osr.hddiff.perfsuite.RunXyDiff.java
private String runXyDiff(File fileA, File fileB, File fileDiff) throws Exception { ProcessBuilder pb = new ProcessBuilder(new String[] { xyDiffBin, "-o", fileDiff.getAbsolutePath(), fileA.getAbsolutePath(), fileB.getAbsolutePath() }); try (StringWriter w = new StringWriter()) { Process p = pb.start(); new ThreadedStreamReader(p.getErrorStream(), "ERROR", w); new ThreadedStreamReader(p.getInputStream(), "OUTPUT", w); try {// w ww.ja va 2s. co m TimeoutProcess.waitFor(p, 2000); } catch (Exception e) { throw new XyDiffException(e); } if (p.exitValue() == 0) return w.toString(); else throw new XyDiffException(w.toString()); } }
From source file:edu.clemson.cs.nestbed.server.util.UsbDeviceInformation.java
private void updateInternal() { ProcessBuilder processBuilder; Process process;//from w ww. j a va 2s .c o m int exitValue; // tmp //if (GET_DEV_INFO == null) return; try { //processBuilder = new ProcessBuilder(GET_DEV_INFO, "-s", moteSerialID); processBuilder = new ProcessBuilder("/usr/bin/sudo", GET_DEV_INFO, "-s", moteSerialID); process = processBuilder.start(); process.waitFor(); exitValue = process.exitValue(); if (exitValue == 0) { Properties p = new Properties(); p.load(process.getInputStream()); String busString = p.getProperty("bus"); String deviceString = p.getProperty("device"); String portString = p.getProperty("port"); log.debug("busString = " + busString); log.debug("deviceString = " + deviceString); log.debug("portString = " + portString); if ((busString != null) && (deviceString != null) && (portString != null)) { try { bus = Integer.parseInt(busString); device = Integer.parseInt(deviceString); port = Integer.parseInt(portString); } catch (NumberFormatException ex) { log.error("Error converting string to int", ex); } } else { log.error("Required property not set"); } } else { log.error("Unable to get USB device information for " + "moteSerialID: " + moteSerialID); } } catch (InterruptedException ex) { log.error("Process interrupted", ex); } catch (IOException ex) { log.error("I/O Exception occured while reading device info", ex); } }
From source file:cu.uci.uengine.runner.impl.FileRunner.java
@Override public RunnerResult run(Runnable runnable, RunnerContext runnerContext) throws IOException, InterruptedException { String command = buildCommand(runnable.getLanguageName(), runnable.getRunnableFile().getAbsolutePath(), runnerContext.getTemporaryDirectory().getAbsolutePath()); log.debug("Running dataset " + runnerContext.getInputFile().getName()); String name = FilenameUtils.getBaseName(runnerContext.getInputFile().getName()); File outFile = new File(runnerContext.getTemporaryDirectory(), name + ".out"); File errFile = new File(runnerContext.getTemporaryDirectory(), name + ".err"); ProcessBuilder pb = buildProcessBuilder(runnable.getLimits(), runnable.getLanguageName(), runnerContext.getInputFile().getAbsolutePath(), outFile, errFile, command, String.valueOf(runnable.getId()), runnable.isTrusted()); Process process = pb.start(); process.waitFor();//w w w . ja v a2s . c o m if (process.exitValue() != 0) { byte[] processError = new byte[process.getErrorStream().available()]; process.getErrorStream().read(processError); return new RunnerResult(RunnerResult.Result.IE, FileUtils.readFileToString(errFile) + new String(processError)); } // result,usertime,cputime,memory String[] results = IOUtils.toString(process.getInputStream()).split(","); // el resultado OK significa que no dio problema ejecutar // con libsandbox. Los demas resultados son errores internos // o resultados que no precisan que se siga ejecutando (TLE, // MLE, etc.) // En OK se debe seguir con el proximo juego de datos, los // demas resultados ya detienen la ejecucion. RunnerResult result = null; String resultCode = results[SandboxResults.RESULT]; switch (resultCode) { case "OK": result = new RunnerResult(RunnerResult.Result.OK, name, Long.valueOf(results[SandboxResults.USER_TIME]), Long.valueOf(results[SandboxResults.CPU_TIME]), Long.valueOf(results[SandboxResults.MEMORY]) * 1024); break; case "AT": result = new RunnerResult(RunnerResult.Result.RT); result.messageConcat(FileUtils.readFileToString(errFile)); break; case "TL": result = new RunnerResult(RunnerResult.Result.CTL); break; case "RF": case "ML": case "OL": case "RT": case "IE": case "BP": case "PD": result = new RunnerResult(RunnerResult.Result.valueOf(resultCode)); result.messageConcat(FileUtils.readFileToString(errFile)); break; } if (outFile.length() > runnable.getLimits().getMaxOutput()) { result = new RunnerResult(RunnerResult.Result.OL); } return result; }
From source file:com.moss.appsnap.keeper.windows.MSWindowsAppHandler.java
@Override public void launch() { InstallableId id = info.currentVersion(); if (id == null) { throw new NullPointerException("There is no current version for " + info.id()); }// w w w.j ava 2 s . com ResolvedJavaLaunchSpec rls = guts.data.javaLaunchSpecs.get(id); StringBuilder line = launchCommand(rls); try { Process p; if (info.isKeeperSoftware()) { // System.out.println("Using line: " + line); // String regex = "\""; // String replacement = "\\\\\""; // String arg = line.toString().replaceAll(regex, replacement); // System.out.println("Using arg: " + arg); ProcessBuilder pb = new ProcessBuilder(daemonLauncherExe.getAbsolutePath()); pb.directory(installDirPath); p = pb.start(); } else { p = Runtime.getRuntime().exec(line.toString()); } new MonitorThread(p).start(); } catch (IOException e) { e.printStackTrace(); JOptionPane.showMessageDialog(null, "Launch error: " + e.getClass().getSimpleName() + ": " + e.getMessage()); } // JOptionPane.showMessageDialog(null, "ERROR: NOT YET IMPLEMENTED"); }
From source file:com.github.ffremont.microservices.springboot.node.tasks.StartTask.java
/** * Syntaxe : java [-options] class [args...] (pour l'excution d'une classe) * ou java [-options] -jar jarfile [args...] (pour l'excution d'un fichier * JAR//w w w . j ava 2s .com * * @param task * @throws * com.github.ffremont.microservices.springboot.node.exceptions.FailStartedException * @throws * com.github.ffremont.microservices.springboot.node.exceptions.FileMsNotFoundException */ @Override public void run(MicroServiceTask task) throws FailStartedException, FileMsNotFoundException { LOG.info("Dmarrage du micro service {}", task.getMs().getName()); Path jar = helper.targetJarOf(task.getMs()); Path workingDir = helper.targetDirOf(task.getMs()); if (!Files.exists(jar) || !Files.exists(Paths.get(workingDir.toString(), InstallTask.CHECKSUM_FILE_NAME + ".txt"))) { throw new FileMsNotFoundException("Jar inexistant ou invalide"); } String javaEx = this.javaExec.isEmpty() ? System.getProperty("java.home") + "/bin/java" : this.javaExec; ProcessBuilder ps = new ProcessBuilder(javaEx, "-jar", helper.targetJarOf(task.getMs()).toString(), "&"); ps.directory(workingDir.toFile()); try { Path consoleLog = Paths.get(workingDir.toString(), "console.log"); ps.redirectOutput(consoleLog.toFile()); ps.redirectError(consoleLog.toFile()); LOG.info("Run de {}", ps.command().toString()); ps.start(); } catch (IOException ex) { throw new FailStartedException("Impossible de dmarrer le programme java : " + task.getMs().getId(), ex); } LOG.info("Micro service {} dmarr", task.getMs().getName()); }
From source file:com.microsoft.tfs.client.common.ui.protocolhandler.ProtocolHandlerWindowsRegistrationCommand.java
private void updateRegistryIfNeeded(final String launcher) throws IOException, InterruptedException { if (isRegistryUpdateNeeded()) { log.info(MessageFormat.format("Registering {0} as the \"{1}\" protocol handler", //$NON-NLS-1$ PROTOCOL_HANDLER_REG_VALUE, ProtocolHandler.PROTOCOL_HANDLER_SCHEME)); final File script = createRegeditFile(launcher); final ProcessBuilder pb = new ProcessBuilder("cmd.exe", //$NON-NLS-1$ "/C", //$NON-NLS-1$ "regedit.exe /s \"" + script.getPath() + "\""); //$NON-NLS-1$ //$NON-NLS-2$ final Process cmd = pb.start(); int rc = cmd.waitFor(); log.info(" rc = " + rc); //$NON-NLS-1$ script.delete();//from w w w . ja v a 2s. co m } }
From source file:generate.MapGenerateAction.java
@Override public String execute() { String file_path = "/home/chanakya/NetBeansProjects/Concepto/UploadedFiles"; try {/*from ww w . j a va 2 s . c om*/ File fileToCreate = new File(file_path, concept_map.getUploadedFileFileName()); FileUtils.copyFile(concept_map.getUploadedFile(), fileToCreate); } catch (Throwable t) { System.out.println("E1: " + t.getMessage()); return ERROR; } try { List<String> temp_text = FileUtils.readLines(concept_map.getUploadedFile()); StringBuilder text = new StringBuilder(); for (String s : temp_text) { text.append(s); } concept_map.setInput_text(text.toString()); } catch (IOException e) { //e.printStackTrace(); System.out.println("E2: " + e.getMessage()); return ERROR; } String temp_filename = concept_map.getUploadedFileFileName().split("\\.(?=[^\\.]+$)")[0]; temp_filename = temp_filename.trim(); try { String temp = "java -jar /home/chanakya/NetBeansProjects/Concepto/src/java/generate/MajorCore.jar " + file_path + " " + temp_filename; System.out.println(temp); File jarfile = new File("/home/chanakya/NetBeansProjects/Concepto/src/java/generate/MajorCore.jar"); JarFile jar = new JarFile(jarfile); Manifest manifest = jar.getManifest(); Attributes attrs = manifest.getMainAttributes(); String mainClassName = attrs.getValue(Attributes.Name.MAIN_CLASS); System.out.println(mainClassName); URL url = new URL("file", null, jarfile.getAbsolutePath()); ClassLoader cl = new URLClassLoader(new URL[] { url }); Class mainClass = cl.loadClass(mainClassName); Method mainMethod = mainClass.getMethod("main", new Class[] { String[].class }); String[] args = new String[2]; args[0] = file_path; args[1] = temp_filename; System.out.println(args[0]); System.out.println(args[1]); try { mainMethod.invoke(mainClass, new Object[] { args }); } catch (InvocationTargetException e) { System.out.println("This is the exception: " + e.getTargetException().toString()); } } catch (IllegalArgumentException | IllegalAccessException | NoSuchMethodException | ClassNotFoundException | IOException e) { System.out.println("E3: " + e.getMessage()); return ERROR; } try { String temp2 = "java -jar /home/chanakya/NetBeansProjects/Concepto/src/java/generate/MajorCoreII.jar " + file_path + " " + temp_filename; System.out.println(temp2); File jarfile = new File("/home/chanakya/NetBeansProjects/Concepto/src/java/generate/MajorCoreII.jar"); JarFile jar = new JarFile(jarfile); Manifest manifest = jar.getManifest(); Attributes attrs = manifest.getMainAttributes(); String mainClassName = attrs.getValue(Attributes.Name.MAIN_CLASS); System.out.println(mainClassName); URL url = new URL("file", null, jarfile.getAbsolutePath()); ClassLoader cl = new URLClassLoader(new URL[] { url }); Class mainClass = cl.loadClass(mainClassName); Method mainMethod = mainClass.getMethod("main", new Class[] { String[].class }); String[] args = new String[2]; args[0] = file_path; args[1] = temp_filename; mainMethod.invoke(mainClass, new Object[] { args }); } catch (InvocationTargetException | IllegalArgumentException | IllegalAccessException | NoSuchMethodException | ClassNotFoundException | IOException e) { System.out.println("E4: " + e.getMessage()); return ERROR; } String cmd = "python /home/chanakya/NetBeansProjects/Concepto/src/java/generate/add_to_graph.py \"/home/chanakya/NetBeansProjects/Concepto/UploadedFiles/" + temp_filename + "_OllieOutput.txt\""; String[] finalCommand; finalCommand = new String[3]; finalCommand[0] = "/bin/sh"; finalCommand[1] = "-c"; finalCommand[2] = cmd; System.out.println("CMD: " + cmd); try { //ProcessBuilder builder = new ProcessBuilder(finalCommand); //builder.redirectErrorStream(true); //Process process = builder.start(); Process process = Runtime.getRuntime().exec(finalCommand); int exitVal = process.waitFor(); System.out.println("Process exitValue2: " + exitVal); } catch (Throwable t) { System.out.println("E5: " + t.getMessage()); return ERROR; } cmd = "python /home/chanakya/NetBeansProjects/Concepto/src/java/generate/json_correct.py"; finalCommand = new String[3]; finalCommand[0] = "/bin/sh"; finalCommand[1] = "-c"; finalCommand[2] = cmd; try { //Process process = Runtime.getRuntime().exec(finalCommand); ProcessBuilder builder = new ProcessBuilder(finalCommand); // builder.redirectErrorStream(true); Process process = builder.start(); int exitVal = process.waitFor(); System.out.println("Process exitValue3: " + exitVal); } catch (Throwable t) { System.out.println("E6: " + t.getMessage()); return ERROR; } try { List<String> temp_text_1 = FileUtils .readLines(FileUtils.getFile("/home/chanakya/NetBeansProjects/Concepto/web", "new_graph.json")); StringBuilder text_1 = new StringBuilder(); for (String s : temp_text_1) { text_1.append(s); } concept_map.setOutput_text(text_1.toString()); } catch (IOException e) { System.out.println("E7: " + e.getMessage()); return ERROR; } Random rand = new Random(); int unique_id = rand.nextInt(99999999); System.out.println("Going In DB"); try { MongoClient mongo = new MongoClient(); DB db = mongo.getDB("Major"); DBCollection collection = db.getCollection("ConceptMap"); BasicDBObject document = new BasicDBObject(); document.append("InputText", concept_map.getInput_text()); document.append("OutputText", concept_map.getOutput_text()); document.append("ChapterName", concept_map.getChapter_name()); document.append("ChapterNumber", concept_map.getChapter_number()); document.append("SectionName", concept_map.getSection_name()); document.append("SectionNumber", concept_map.getSection_number()); document.append("UniqueID", Integer.toString(unique_id)); collection.insert(document); //collection.save(document); } catch (MongoException e) { System.out.println("E8: " + e.getMessage()); return ERROR; } catch (UnknownHostException ex) { Logger.getLogger(MapGenerateAction.class.getName()).log(Level.SEVERE, null, ex); System.out.println("E9"); return ERROR; } System.out.println("Out DB"); return SUCCESS; }
From source file:jenkins.plugins.tanaguru.TanaguruRunner.java
public void callTanaguruService() throws IOException, InterruptedException { File logFile = TanaguruRunnerBuilder.createTempFile(contextDir, "log-" + new Random().nextInt() + ".log", "");// w ww.j a v a2 s . c o m File scenarioFile = TanaguruRunnerBuilder.createTempFile(contextDir, scenarioName + "_#" + buildNumber, TanaguruRunnerBuilder.forceVersion1ToScenario(scenario)); ProcessBuilder pb = new ProcessBuilder(tgScriptName, "-f", firefoxPath, "-r", referential, "-l", level, "-d", displayPort, "-x", xmxValue, "-o", logFile.getAbsolutePath(), "-t", "Scenario", scenarioFile.getAbsolutePath()); pb.directory(contextDir); pb.redirectErrorStream(true); Process p = pb.start(); p.waitFor(); extractDataAndPrintOut(logFile, listener.getLogger()); if (!isDebug) { FileUtils.deleteQuietly(logFile); } FileUtils.deleteQuietly(scenarioFile); }
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 {//ww w . j a v a2 s . com // 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:net.landora.video.mediainfo.MediaInfoParser.java
public Video handleFile(File f) { try {/* w w w .j ava 2s. com*/ //ProcessBuilder process = new ProcessBuilder(Program.MediaInfo.getConfiguredPath(), "-Full", "--Language=raw", f.getAbsolutePath()); ProcessBuilder process = new ProcessBuilder( ProgramsAddon.getInstance().getConfiguredPath(CommonPrograms.MEDIAINFO), "-Full", "--Language=raw", f.getAbsolutePath()); process.redirectErrorStream(true); Process p = process.start(); StringWriter buffer = new StringWriter(); IOUtils.copy(p.getInputStream(), buffer); p.waitFor(); String reply = buffer.toString(); buffer = null; file = new Video(); file.setFile(f); state = State.EmptyLine; BufferedReader reader = new BufferedReader(new StringReader(reply)); String line; while ((line = reader.readLine()) != null) { Matcher m = dataPattern.matcher(line); if (m.matches()) { String field = m.group(1); String value = m.group(2); switch (state) { case General: handleGeneral(field, value); break; case Video: handleVideo(field, value); break; case Audio: handleAudio(field, value); break; case Text: handleSubtitle(field, value); break; case Chapters: handleChapter(field, value); break; } } else if (line.trim().isEmpty()) { state = State.EmptyLine; } else { line = line.trim(); if (line.equals("General")) { state = State.General; } else if (line.equals("Video")) { state = State.Video; curVideo = new VideoStream(); file.getVideoStreams().add(curVideo); } else if (line.equals("Audio")) { state = State.Audio; curAudio = new AudioStream(); curAudio.setStreamId(++audioCount); file.getAudioStreams().add(curAudio); } else if (line.equals("Text")) { state = State.Text; curSubtitle = new SubtitleStream(); curSubtitle.setStreamId(subtitleCount++); file.getSubtitleStreams().add(curSubtitle); } else if (line.equals("Chapters")) { state = State.Chapters; } } } cleanupChapters(); return file; } catch (Exception e) { return null; } }