List of usage examples for java.lang Runtime exec
public Process exec(String cmdarray[]) throws IOException
From source file:org.quartz.jobs.NativeJob.java
private Integer runNativeCommand(String command, String parameters, boolean wait, boolean consumeStreams) throws JobExecutionException { String[] cmd = null;// w w w . j ava 2 s. co m String[] args = new String[2]; Integer result = null; args[0] = command; args[1] = parameters; try { //with this variable will be done the swithcing String osName = System.getProperty("os.name"); // specific for Windows if (osName.startsWith("Windows")) { cmd = new String[args.length + 2]; if (osName.equals("Windows 95")) { // windows 95 only cmd[0] = "command.com"; } else { cmd[0] = "cmd.exe"; } cmd[1] = "/C"; for (int i = 0; i < args.length; i++) { cmd[i + 2] = args[i]; } } else if (osName.equals("Linux")) { if (cmd == null) { cmd = new String[3]; } cmd[0] = "/bin/sh"; cmd[1] = "-c"; cmd[2] = args[0] + " " + args[1]; } else { // try this... cmd = args; } Runtime rt = Runtime.getRuntime(); // Executes the command getLog().info("About to run " + cmd[0] + " " + cmd[1] + " " + (cmd.length > 2 ? cmd[2] : "") + " ..."); Process proc = rt.exec(cmd); // Consumes the stdout from the process StreamConsumer stdoutConsumer = new StreamConsumer(proc.getInputStream(), "stdout"); // Consumes the stderr from the process if (consumeStreams) { StreamConsumer stderrConsumer = new StreamConsumer(proc.getErrorStream(), "stderr"); stdoutConsumer.start(); stderrConsumer.start(); } if (wait) { result = new Integer(proc.waitFor()); } // any error message? } catch (Exception x) { throw new JobExecutionException("Error launching native command: ", x, false); } return result; }
From source file:com.alfaariss.oa.authentication.password.digest.HtPasswdMD5Digest.java
private void testCommand() throws OAException { Runtime r = Runtime.getRuntime(); Thread t = null;/* w ww . ja v a2 s . co m*/ String[] saCommand = null; try { saCommand = resolveCommand(_sCommand, "salt", "password"); _systemLogger.debug("Executing test command: " + resolveCommand(saCommand)); final Process p = r.exec(saCommand); t = new Thread(new Runnable() { public void run() { try { Thread.sleep(3000); p.destroy(); _systemLogger.warn("Destroyed process"); } catch (InterruptedException e) { _systemLogger.debug("Thread interrupted"); } } }); t.start(); int exitCode = p.waitFor(); if (exitCode != 0) { StringBuffer sbError = new StringBuffer("Configured command returned exit code '"); sbError.append(exitCode); sbError.append("': "); sbError.append(resolveCommand(saCommand)); _systemLogger.error(sbError.toString()); throw new OAException(SystemErrors.ERROR_INIT); } } catch (OAException e) { throw e; } catch (Exception e) { _systemLogger.error("Could not execute command: " + resolveCommand(saCommand), e); throw new OAException(SystemErrors.ERROR_INIT); } finally { if (t != null) t.interrupt(); } }
From source file:fish.payara.maven.plugins.micro.StartMojo.java
public void execute() throws MojoExecutionException { if (copySystemProperties) { getLog().warn(//from w w w . j a v a2 s . c om "copySystemProperties is deprecated. " + "System properties of the regarding maven execution " + "will be passed to the payara-micro automatically."); } if (skip) { getLog().info("Start mojo execution is skipped"); return; } toolchain = getToolchain(); final String path = decideOnWhichMicroToUse(); microProcessorThread = new Thread(threadGroup, () -> { final List<String> actualArgs = new ArrayList<>(); getLog().info("Starting payara-micro from path: " + path); int indice = 0; actualArgs.add(indice++, evaluateJavaPath()); if (javaCommandLineOptions != null) { for (Option option : javaCommandLineOptions) { if (option.getKey() != null && option.getValue() != null) { String systemProperty = String.format("%s=%s", option.getKey(), option.getValue()); actualArgs.add(indice++, systemProperty); } else if (option.getValue() != null) { actualArgs.add(indice++, option.getValue()); } } } String execArgs = mavenSession.getRequest().getUserProperties().getProperty("exec.args"); if (execArgs != null && !execArgs.trim().isEmpty()) { for (String execArg : execArgs.split("\\s+")) { actualArgs.add(indice++, execArg); } } actualArgs.add(indice++, "-Dgav=" + getProjectGAV()); actualArgs.add(indice++, "-jar"); actualArgs.add(indice++, path); if (deployWar && WAR_EXTENSION.equalsIgnoreCase(mavenProject.getPackaging())) { actualArgs.add(indice++, "--deploy"); actualArgs.add(indice++, evaluateProjectArtifactAbsolutePath(false)); } if (commandLineOptions != null) { for (Option option : commandLineOptions) { if (option.getKey() != null) { actualArgs.add(indice++, option.getKey()); } if (option.getValue() != null) { actualArgs.add(indice++, option.getValue()); } } } try { getLog().debug("Starting Payara Micro with the these arguments: " + actualArgs); final Runtime re = Runtime.getRuntime(); microProcess = re.exec(actualArgs.toArray(new String[actualArgs.size()])); if (daemon) { redirectStream(microProcess.getInputStream(), System.out); redirectStream(microProcess.getErrorStream(), System.err); } else { redirectStreamToGivenOutputStream(microProcess.getInputStream(), System.out); redirectStreamToGivenOutputStream(microProcess.getErrorStream(), System.err); } int exitCode = microProcess.waitFor(); if (exitCode != 0) { throw new MojoFailureException(ERROR_MESSAGE); } } catch (InterruptedException ignored) { } catch (Exception e) { throw new RuntimeException(ERROR_MESSAGE, e); } finally { if (!daemon) { closeMicroProcess(); } } }); final Thread shutdownHook = new Thread(threadGroup, () -> { if (microProcess != null && microProcess.isAlive()) { try { microProcess.destroy(); microProcess.waitFor(1, TimeUnit.MINUTES); } catch (InterruptedException ignored) { } finally { microProcess.destroyForcibly(); } } }); if (daemon) { microProcessorThread.setDaemon(true); microProcessorThread.start(); if (!immediateExit) { try { microProcessorThread.join(); } catch (InterruptedException e) { e.printStackTrace(); } } } else { Runtime.getRuntime().addShutdownHook(shutdownHook); microProcessorThread.run(); } }
From source file:com.emergya.persistenceGeo.importer.shp.ShpImporterImpl.java
private void checkForCommandLineUtils() { Runtime runtime = Runtime.getRuntime(); Process proc;//from w w w . j a v a 2 s.c o m try { if (LOG.isTraceEnabled()) { LOG.trace("Checking psql command line tool existence"); } proc = runtime.exec(new String[] { "psql", "--help" }); int returnValue = proc.waitFor(); if (returnValue != 0) { throw new ShpImporterException("psql command line tool not found" + "Please, check if postgresql-client package is installed."); } } catch (Exception e) { throw new ShpImporterException("psql command line tool not found. " + "Please, check if postgresql-client package is installed.", e); } try { if (LOG.isTraceEnabled()) { LOG.trace("Checking shp2pgsql command line tool existence"); } proc = runtime.exec("shp2pgsql"); int returnValue = proc.waitFor(); if (returnValue != 0) { throw new ShpImporterException( "shp2pgsql command line tool not found" + "Please, check if postgis package is installed."); } } catch (Exception e) { throw new ShpImporterException( "shp2pgsql command line tool not found. " + "Please, check if postgis package is installed.", e); } }
From source file:com.mindquarry.desktop.client.dialog.conflict.ContentConflictDialog.java
private void mergeWordDocumentsManually(Status status, String basePath) throws IOException { File localVersion = new File(status.getPath()); File serverVersion = new File(basePath, status.getConflictNew()); log.debug("merge: serverVersion: " + serverVersion); log.debug("merge: localVersion: " + localVersion); // use the correct filename suffix: String suffix = FilenameUtils.getExtension(localVersion.getName()); File tmpServerVersion = File.createTempFile("mindquarry-merge-server", "." + suffix); FileUtils.copyFile(serverVersion, tmpServerVersion); tempFiles.add(tmpServerVersion);// w w w. jav a2 s. com mergedVersion = File.createTempFile("mindquarry-merge-local", "." + suffix); FileUtils.copyFile(localVersion, mergedVersion); tempFiles.add(mergedVersion); File tmpScriptFile = File.createTempFile("mindquarry-merge-script", ".js"); tempFiles.add(tmpScriptFile); // // FIXME: delete temp files also in case of 'cancel' // // load script from JAR and save as temp file to avoid path problems: InputStream is = getClass().getResourceAsStream("/scripts/merge-doc.js"); String script = loadInputStream(is); FileWriter fw = new FileWriter(tmpScriptFile); fw.write(script); fw.close(); String mergeScript = tmpScriptFile.getAbsolutePath(); String[] cmdArray = new String[] { "wscript", mergeScript, mergedVersion.getAbsolutePath(), tmpServerVersion.getAbsolutePath() }; log.debug("Calling merge script: " + Arrays.toString(cmdArray)); Runtime rt = Runtime.getRuntime(); Process proc = rt.exec(cmdArray); int exitValue = -1; try { exitValue = proc.waitFor(); } catch (InterruptedException e) { throw new RuntimeException(e.toString(), e); } log.debug("Exit value " + exitValue); if (exitValue != 0) { mergeOptionButton.setEnabled(false); mergeButton.setEnabled(false); okButton.setEnabled(true); // let user continue with other option MessageDialog .openError( getShell(), I18N.getString("Error executing MS Word"), I18N .getString("The script used to merge documents " + "using MS Word could not be started. The exit " + "code was ") + exitValue); } }
From source file:com.epam.controllers.pages.graphviz.GraphViz.java
/** * It will call the external dot program, and return the image in * binary format./*from ww w . j a v a 2 s . co m*/ * @param dot Source of the graph (in dot language). * @param type Type of the output image to be produced, e.g.: gif, dot, fig, pdf, ps, svg, png. * @return The image of the graph in .gif format. */ private byte[] get_img_stream(File dot, String type) { File img; byte[] img_stream = null; try { img = File.createTempFile("graph_", "." + type, new File(GraphViz.TEMP_DIR)); Runtime rt = Runtime.getRuntime(); // patch by Mike Chenault String[] args = { DOT, "-T" + type, dot.getAbsolutePath(), "-o", img.getAbsolutePath() }; Process p = rt.exec(args); p.waitFor(); FileInputStream in = new FileInputStream(img.getAbsolutePath()); img_stream = new byte[in.available()]; in.read(img_stream); // Close it if we need to if (in != null) in.close(); if (img.delete() == false) log.warn("Warning: " + img.getAbsolutePath() + " could not be deleted!"); } catch (java.io.IOException ioe) { log.warn("Error: in I/O processing of tempfile in dir " + GraphViz.TEMP_DIR + "\n"); log.warn(" or in calling external command"); log.error("stacktrace", ioe); } catch (java.lang.InterruptedException ie) { log.error("Error: the execution of the external program was interrupted", ie); } return img_stream; }
From source file:com.ichi2.libanki.Exporter.java
private JSONObject exportFiltered(ZipFile z, String path) throws IOException, JSONException { // export into the anki2 file String colfile = path.replace(".apkg", ".anki2"); super.exportInto(colfile); z.write(colfile, "collection.anki2"); // and media// ww w. j a va2s . c o m prepareMedia(); JSONObject media = new JSONObject(); File mdir = new File(mCol.getMedia().dir()); if (mdir.exists() && mdir.isDirectory()) { int c = 0; for (String file : mMediaFiles) { File mpath = new File(mdir, file); if (mpath.exists()) { z.write(mpath.getPath(), Integer.toString(c)); } try { media.put(Integer.toString(c), file); c++; } catch (JSONException e) { e.printStackTrace(); } } } // tidy up intermediate files new File(colfile).delete(); String p = path.replace(".apkg", ".media.ad.db2"); if (new File(p).exists()) { new File(p).delete(); } String tempPath = path.replace(".apkg", ".media"); File file = new File(tempPath); if (file.exists()) { String deleteCmd = "rm -r " + tempPath; Runtime runtime = Runtime.getRuntime(); try { runtime.exec(deleteCmd); } catch (IOException e) { } } return media; }
From source file:edu.harvard.mcz.imagecapture.TesseractOCR.java
@Override public String getOCRText() throws OCRReadException { StringBuffer result = new StringBuffer(); BufferedReader resultReader = null; try {//ww w . ja v a2 s . c o m Runtime r = Runtime.getRuntime(); // Run tesseract to OCR the target file. String runCommand = Singleton.getSingletonInstance().getProperties().getProperties().getProperty( ImageCaptureProperties.KEY_TESSERACT_EXECUTABLE) + target + " " + tempFileBase + " " + language; Process proc = r.exec(runCommand); System.out.println(runCommand); // Create and start a reader for the error stream StreamReader errorReader = new StreamReader(proc.getErrorStream(), "ERROR"); errorReader.run(); // run the process and wait for the exit value int exitVal = proc.waitFor(); System.out.println("Tesseract Exit Value: " + exitVal); if (exitVal == 0) { resultReader = new BufferedReader( new InputStreamReader(new FileInputStream(tempFileBase + ".txt"), "UTF-8")); String s; while ((s = resultReader.readLine()) != null) { result.append(s); result.append("\n"); } resultReader.close(); } else { throw new OCRReadException("OCR process failed (exit value>0)."); } if (result.length() > 0) { String resString = result.toString(); // $ is returned by tesseract to indicate italics // @ is returned by tesseract to indicate bold // | and _ are common interpretations of QR barcode blocks result = new StringBuffer(); result.append(resString.replaceAll("[|@\\$_]", "")); } } catch (IOException eio) { log.error(eio); throw new OCRReadException("OCR process failed with IO Exception."); } catch (InterruptedException ei) { log.error(ei); throw new OCRReadException("OCR process failed with Interrupted Exception."); } finally { if (resultReader != null) { try { resultReader.close(); } catch (IOException e) { log.debug(e); } } } log.debug(result.toString()); return result.toString(); }
From source file:nl.mvdr.umvc3replayanalyser.ocr.TesseractOCREngine.java
/** * Executes the given command.//from ww w .ja va 2 s.c om * * @param command * command to be executed * @throws OCRException * if the command returns a nonzero exit code, the command is interrupted or there is an unexpected I/O * exception * @return the first line of the command's output */ private String execute(String command) throws OCRException { if (log.isDebugEnabled()) { log.debug("Executing command: " + command); } String firstLine; try { Runtime runtime = Runtime.getRuntime(); Process process = runtime.exec(command); // Log the process's output and capture the first line. try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getErrorStream()))) { String line = reader.readLine(); firstLine = line; if (log.isDebugEnabled()) { while (line != null) { log.debug("tesseract: " + line); line = reader.readLine(); } } } int exitCode = process.waitFor(); if (exitCode != 0) { throw new OCRException("Command failed, exit code: " + exitCode + ", command: " + command); } } catch (IOException | InterruptedException e) { throw new OCRException(e); } return firstLine; }
From source file:com.doomy.padlock.MainFragment.java
public void superUserReboot(String mCommand) { Runtime mRuntime = Runtime.getRuntime(); Process mProcess = null;//from w w w. j a v a2 s . c o m OutputStreamWriter mWrite = null; try { mProcess = mRuntime.exec("su"); mWrite = new OutputStreamWriter(mProcess.getOutputStream()); mWrite.write(mCommand + "\n"); mWrite.flush(); mWrite.close(); } catch (IOException e) { e.printStackTrace(); } }