List of usage examples for java.lang ProcessBuilder directory
File directory
To view the source code for java.lang ProcessBuilder directory.
Click Source Link
From source file:org.sonar.application.process.ProcessLauncherImpl.java
private ProcessBuilder create(AbstractCommand<?> javaCommand, List<String> commands) { ProcessBuilder processBuilder = processBuilderSupplier.get(); processBuilder.command(commands);//from w ww. j a v a 2s.com processBuilder.directory(javaCommand.getWorkDir()); Map<String, String> environment = processBuilder.environment(); environment.putAll(javaCommand.getEnvVariables()); javaCommand.getSuppressedEnvVariables().forEach(environment::remove); processBuilder.redirectErrorStream(true); return processBuilder; }
From source file:org.apache.tika.batch.BatchProcessDriverCLI.java
private void start() throws Exception { ProcessBuilder builder = new ProcessBuilder(commandLine); builder.directory(Paths.get(".").toFile()); process = builder.start();/*from ww w .ja v a 2 s.c om*/ errorWatcher = new StreamWatcher(process.getErrorStream()); errorWatcherThread = new Thread(errorWatcher); errorWatcherThread.start(); outGobbler = new StreamGobbler(process.getInputStream()); outGobblerThread = new Thread(outGobbler); outGobblerThread.start(); interruptWriter = new InterruptWriter(process.getOutputStream()); interruptWriterThread = new Thread(interruptWriter); interruptWriterThread.start(); }
From source file:com.all.launcher.Launcher.java
private void setDirectoryIfMac(ProcessBuilder processBuilder) { if (Environment.isMac()) { String appRootPath = launcherConfig.getAppRootPath(); processBuilder.directory(new File(appRootPath, "/Contents/MacOS/")); log.info("Working directory: " + processBuilder.directory() + " " + appRootPath); } else {/*from w w w. ja va 2 s . c om*/ processBuilder.directory(new File(System.getProperty("user.dir"))); log.info("Working directory: " + processBuilder.directory()); } }
From source file:uk.co.codezen.maven.composer.mojo.AbstractComposerMojo.java
/** * Execute an arbitrary command, forwarding the process stdout to the Log info level * and the process stderr to the Java error level. * * @param command Command to execute/*from w ww .ja v a2 s . c o m*/ * @param workingDirectory Working directory * @throws IOException IO problem executing command */ private int runCommand(List<String> command, String workingDirectory) throws IOException { ProcessBuilder processBuilder = new ProcessBuilder(command); processBuilder.directory(new File(workingDirectory)); Process composerProcess = processBuilder.start(); // Link Maven stdout/stderr with process pipe(composerProcess.getInputStream(), System.out); pipe(composerProcess.getErrorStream(), System.err); while (true) { try { composerProcess.waitFor(); break; } catch (InterruptedException e) { // Do nothing, re-run loop } } return composerProcess.exitValue(); }
From source file:org.wso2.carbon.identity.authenticator.krb5.Krb5Authenticator.java
private boolean loginWithKrb5(String username, String password, String remoteAddress) throws AuthenticationException { //Proceed with Kerberos TGT request String uuid = UUID.randomUUID().toString(); ProcessBuilder procBldr = new ProcessBuilder("/usr/bin/kinit", "-l", "10d", "-r", "5d", "-c", tgtCachePrefix + uuid, username); procBldr.directory(new File(CARBON_HOME)); Map<String, String> env = procBldr.environment(); if (KRB5_CONFIG == null) KRB5_CONFIG = "/etc/krb5.conf"; env.put("KRB5_CONFIG", KRB5_CONFIG); log.info(env.get("KRB5_CONFIG")); HttpSession session = getHttpSession(); try {/*from www. ja v a2 s .c om*/ Process proc = procBldr.start(); InputStream procErr = proc.getErrorStream(); InputStream procOut = proc.getInputStream(); //Read the output from the program byte[] buffer = new byte[256]; BufferedWriter out = new BufferedWriter(new OutputStreamWriter(proc.getOutputStream())); BufferedReader err = new BufferedReader(new InputStreamReader(procErr)); boolean isError = (procErr.available() > 0) ? true : false; if (!isError) { out.write(password); out.newLine(); out.close(); if (proc.waitFor() != 0) { log.warn("Kinit Failed"); if (procErr.available() > 0) { String line = null; String msg = ""; while (err.ready() && (line = err.readLine()) != null) msg += line; if (!msg.equals("")) throw new AuthenticationException(msg); } } //Looks like all went well and we got the TGT, lets renew the TGT... procBldr = new ProcessBuilder("/usr/bin/kinit", "-R", "-c", tgtCachePrefix + uuid); proc = procBldr.start(); if (proc.waitFor() != 0) { log.warn("TGT Renewal Failed"); File tgt = new File(tgtCachePrefix + uuid); tgt.delete(); throw new AuthenticationException("TGT Renewal Failed"); } AuthenticationAdmin authAdmin = new AuthenticationAdmin(); boolean loggedIn = authAdmin.login(username, password, remoteAddress); if (loggedIn) { nameToUuidMap.put(username, uuid); session.setAttribute(Krb5AuthenticatorConstants.USER_TICKET_CACHE, tgtCachePrefix + uuid); } return loggedIn; } else { log.error("Incorrect kinit command: " + err.readLine()); throw new AuthenticationException("Incorrect kinit command"); } } catch (IOException ioe) { log.warn(ioe.getMessage()); ioe.printStackTrace(); throw new AuthenticationException(ioe.getMessage()); } catch (InterruptedException e) { e.printStackTrace(); throw new AuthenticationException(e.getMessage()); } }
From source file:org.efaps.wikiutil.export.latex.MakePDF.java
/** * Executes "<code>pdflatex</code>" from the Latex packages and * converts all Latex files to related PDF file <code>book.pdf</code>. * * @return <i>true</i> if the Latex to PDF convert was successfully; * otherwise <i>false</i> * @throws IOException if execute failed * @see #tempDir//from w ww. j a v a 2 s . c o m */ protected boolean executePDFLatex() throws IOException { final ProcessBuilder processBuilder = new ProcessBuilder(this.executablePdfLaTeX, "book.tex"); processBuilder.directory(this.tempDir); final Process process = processBuilder.start(); final Reader in = new InputStreamReader(process.getInputStream()); final Reader err = new InputStreamReader(process.getErrorStream()); // PrintStream out = new PrintStream(process.getOutputStream()); Integer exitCode = null; for (;;) { if (err.ready()) { System.err.print((char) err.read()); } else if (in.ready()) { System.out.print((char) in.read()); } else { try { exitCode = process.exitValue(); break; } catch (final IllegalThreadStateException e) { try { Thread.sleep(1000); } catch (final InterruptedException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } } return (exitCode != null) && (exitCode == 0); }
From source file:org.obiba.opal.server.UpgradeCommand.java
private ProcessBuilder getOpalMigratorProcessBuilder(String... args) { String dist = System.getenv("OPAL_DIST"); if (Strings.isNullOrEmpty(dist)) throw new RuntimeException("Cannot locate opal tools directory: OPAL_DIST is not defined."); File toolsDir = Paths.get(dist, "tools", "lib").toFile(); if (!toolsDir.exists() || !toolsDir.isDirectory()) throw new RuntimeException("No such directory: " + toolsDir.getAbsolutePath()); File[] jars = toolsDir.listFiles(new FilenameFilter() { @Override//w w w . ja va2 s . co m public boolean accept(File dir, String name) { return name.startsWith("opal-config-migrator-") && name.endsWith("-cli.jar"); } }); if (jars == null || jars.length == 0) throw new RuntimeException(String.format("Cannot find any opal-config-migrator-*-cli.jar file in '%s'", toolsDir.getAbsolutePath())); List<String> processArgs = Lists.newArrayList("java", "-jar", jars[0].getName()); processArgs.addAll(Arrays.asList(args)); log.info("Running Opal config migrator command: {}", Joiner.on(" ").join(processArgs)); ProcessBuilder pb = new ProcessBuilder(processArgs); pb.redirectErrorStream(true); pb.directory(toolsDir); return pb; }
From source file:net.sf.mavenjython.JythonMojo.java
public void runJythonScriptOnInstall(File outputDirectory, List<String> args) throws MojoExecutionException { getLog().info("running " + args + " in " + outputDirectory); ProcessBuilder pb = new ProcessBuilder(args); pb.directory(outputDirectory); final Process p; try {// www . jav a 2 s . c om p = pb.start(); } catch (IOException e) { throw new MojoExecutionException("Executing jython failed. tried to run: " + pb.command(), e); } copyIO(p.getInputStream(), System.out); copyIO(p.getErrorStream(), System.err); copyIO(System.in, p.getOutputStream()); try { if (p.waitFor() != 0) { throw new MojoExecutionException("Jython failed with return code: " + p.exitValue()); } } catch (InterruptedException e) { throw new MojoExecutionException("Python tests were interrupted", e); } }
From source file:runtime.daemon.ProcessLauncher.java
private void ExecuteJob() { if (DEBUG && logger.isDebugEnabled()) logger.debug("Job Started"); MPJProcessTicket pTicket = new MPJProcessTicket(); try {// w ww . j a v a2 s . co m String ticketString = getStringFromInputStream(sockserver.getInputStream()); if (ticketString != "") pTicket.FromXML(ticketString); if (DEBUG && logger.isDebugEnabled()) { logger.debug(pTicket.ToXML(false).toXmlString()); } } catch (IOException e3) { e3.printStackTrace(); return; } if (pTicket.getDeviceName().equals("niodev") || pTicket.getDeviceName().equals("mxdev")) { JvmProcessCount = pTicket.getProcessCount(); } else if (pTicket.getDeviceName().equals("hybdev")) { JvmProcessCount = 1; } OutputHandler[] outputThreads = new OutputHandler[JvmProcessCount]; p = new Process[JvmProcessCount]; argManager = new ProcessArgumentsManager(pTicket); String[] arguments = argManager.GetArguments(pTicket); for (int j = 0; j < JvmProcessCount; j++) { if (pTicket.getDeviceName().equals("niodev") || pTicket.getDeviceName().equals("mxdev")) { String rank = new String("" + (pTicket.getStartingRank() + j)); arguments[argManager.getRankArgumentIndex()] = rank; if (pTicket.isProfiler()) arguments[1] = "-tau:node=" + rank; } if (pTicket.isDebug() && (pTicket.getDeviceName().equals("niodev") || pTicket.getDeviceName().equals("mxdev"))) { arguments[argManager .getDebugArgumentIndex()] = "-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=" + (pTicket.getDebugPort() + j * 2); } else if (pTicket.isDebug() && pTicket.getDeviceName().equals("hybdev")) { arguments[argManager .getDebugArgumentIndex()] = "-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=" + (pTicket.getDebugPort()); } if (DEBUG && logger.isDebugEnabled()) { for (int i = 0; i < arguments.length; i++) { logger.debug("arguments[" + i + "] = " + arguments[i]); } } ProcessBuilder pb = new ProcessBuilder(arguments); pb.directory(new File(pTicket.getWorkingDirectory())); pb.redirectErrorStream(true); if (DEBUG && logger.isDebugEnabled()) { logger.debug("starting the process "); } try { p[j] = pb.start(); } catch (IOException e) { e.printStackTrace(); } /* * Step 4: Start a new thread to handle output from this particular JVM. * FIXME: Now this seems like a good amount of overhead. If we start 4 * JVMs on a quad-core CPU, we also start 4 additional threads to handle * I/O. Is it possible to get rid of this overhead? */ outputThreads[j] = new OutputHandler(p[j], sockserver); outputThreads[j].start(); if (DEBUG && logger.isDebugEnabled()) { logger.debug("started the process "); } } // end for loop. // Wait for the I/O threads to finish. They finish when // their corresponding JVMs finish. for (int j = 0; j < JvmProcessCount; j++) { try { outputThreads[j].join(); } catch (InterruptedException e) { e.printStackTrace(); } } if (DEBUG && logger.isDebugEnabled()) { logger.debug("Stopping the output"); } if (sockserver != null && !sockserver.isClosed() && !sockserver.isOutputShutdown()) { OutputStream outToServer = null; try { outToServer = sockserver.getOutputStream(); DataOutputStream out = new DataOutputStream(outToServer); out.write("EXIT".getBytes(), 0, "EXIT".getBytes().length); if (DEBUG && logger.isDebugEnabled()) logger.debug("Job Finished"); if (!DEBUG || !logger.isDebugEnabled()) { FileUtils.deleteDirectory(new File(argManager.getUsersDir())); } } catch (IOException e1) { e1.printStackTrace(); } finally { if (!sockserver.isClosed()) try { outToServer.close(); sockserver.close(); } catch (IOException e) { e.printStackTrace(); } } } try { killProcesses(); } catch (Exception e) { e.printStackTrace(); } MPJDaemon.servSockets.remove(sockserver); if (DEBUG && logger.isDebugEnabled()) { logger.debug("\n\n ** .. execution ends .. ** \n\n"); } }
From source file:org.zgis.wps.swat.AnnotatedSwatRunnerAlgorithm.java
@Execute public void runSwatProcess() throws IOException { logger.info("Trying to run SWAT model"); //TODO make a list of needed directories and create in loop String tempDirStr = ExecutionContextFactory.getContext().getTempDirectoryPath(); File tempDir = new File(tempDirStr + System.getProperty("file.separator")); File swatModelDir = new File(tempDirStr + System.getProperty("file.separator") + "swatmodel" + System.getProperty("file.separator")); logger.info("Temp dir is: " + tempDirStr); logger.info("Temp file is: " + tempDir.getAbsolutePath()); try {//from w w w . j a v a 2 s . co m if (!tempDir.isDirectory() && !tempDir.mkdirs()) { throw new IOException("Could not create temp dir " + tempDir); } if (!swatModelDir.isDirectory() && !swatModelDir.mkdirs()) { throw new IOException("Could not create swatmodel dir " + tempDir); } //unpack swat model if (swatInputZip == null) { logger.info("SwatInputZip was NULL"); } else if (swatInputZip.size() != 1) { logger.info("SwatInputZip size != 1 - " + swatInputZip.size()); } else { logger.info("Unpacking swatInputZip " + swatInputZip.get(0).getBaseFile(false).getAbsolutePath() + " to " + swatModelDir.getAbsolutePath()); net.lingala.zip4j.core.ZipFile zipFile = new net.lingala.zip4j.core.ZipFile( swatInputZip.get(0).getBaseFile(false)); zipFile.extractAll(swatModelDir.getAbsolutePath()); } URI jarUri = this.getJarURI(); logger.debug("Jar-File URI " + jarUri); //FIXME this is bullshit, make own jar for every OS and provide executable this way. String exeFilename = "swat/swat_rel64"; if (System.getProperty("os.name").toLowerCase().startsWith("windows")) { exeFilename = exeFilename.concat("_win.exe"); } else if (System.getProperty("os.name").toLowerCase().startsWith("mac")) { exeFilename = exeFilename.concat("_osx"); } else if (System.getProperty("os.name").toLowerCase().startsWith("linux")) { exeFilename = exeFilename.concat("_linux"); } else { logger.warn("Could not determine OS, trying generic executable name"); } URI exeFile = getFile(jarUri, exeFilename); new File(exeFile).setExecutable(true); ProcessBuilder pb = new ProcessBuilder(new File(exeFile).toString()); pb.redirectErrorStream(true); pb.directory(swatModelDir); Process process = pb.start(); InputStream stdOutStream = process.getInputStream(); InputStreamReader isr = new InputStreamReader(stdOutStream); BufferedReader br = new BufferedReader(isr); String line; logger.info(String.format("Output of running %s is:\n", Arrays.toString(pb.command().toArray()))); while ((line = br.readLine()) != null) { logger.info(line); this.swatConsoleOutput = this.swatConsoleOutput.concat(line).concat("\n"); } int exitValue = process.waitFor(); if (exitValue != 0) { throw new IOException("SWAT didn't complete successfully"); } Collection<File> outFiles = FileUtils.listFiles(swatModelDir, new WildcardFileFilter("output.*"), TrueFileFilter.TRUE); File outFilesZippend = org.n52.wps.io.IOUtils.zip(outFiles.toArray(new File[outFiles.size()])); this.swatOutputZipped = new GenericFileData(outFilesZippend, "application/zip"); } catch (URISyntaxException e) { logger.error("Could not determine uri of jar. ", e); throw new IOException("Could not determine uri of jar. ", e); } catch (InterruptedException e) { logger.error("Exception on running SWAT process.", e); throw new IOException("Exception on running SWAT process.", e); } catch (net.lingala.zip4j.exception.ZipException e) { logger.error("Could not extract swat input model.", e); throw new IOException("Could not extract swat input model.", e); } finally { //TODO FIXME is that really necessary? The Execution context should delete this? /* if (tempDir.isDirectory()) { FileUtils.deleteDirectory(tempDir); } */ } }