Example usage for java.lang Runtime exec

List of usage examples for java.lang Runtime exec

Introduction

In this page you can find the example usage for java.lang Runtime exec.

Prototype

public Process exec(String cmdarray[]) throws IOException 

Source Link

Document

Executes the specified command and arguments in a separate process.

Usage

From source file:org.pentaho.di.trans.steps.orabulkloader.OraBulkLoader.java

public boolean execute(OraBulkLoaderMeta meta, boolean wait) throws KettleException {
    Runtime rt = Runtime.getRuntime();

    try {//from  w w w  .ja  v  a2s.co m
        sqlldrProcess = rt.exec(createCommandLine(meta, true));
        // any error message?
        StreamLogger errorLogger = new StreamLogger(sqlldrProcess.getErrorStream(), "ERROR");

        // any output?
        StreamLogger outputLogger = new StreamLogger(sqlldrProcess.getInputStream(), "OUTPUT");

        // kick them off
        errorLogger.start();
        outputLogger.start();

        if (wait) {
            // any error???
            int exitVal = sqlldrProcess.waitFor();
            sqlldrProcess = null;
            logBasic(BaseMessages.getString(PKG, "OraBulkLoader.Log.ExitValueSqlldr", "" + exitVal));
            checkExitVal(exitVal);
        }
    } catch (Exception ex) {
        // Don't throw the message upwards, the message contains the password.
        throw new KettleException("Error while executing sqlldr \'" + createCommandLine(meta, false) + "\'");
    }

    return true;
}

From source file:com.gnuroot.debian.GNURootMain.java

private void exec(String command, boolean setError) {
    Runtime runtime = Runtime.getRuntime();
    Process process;/*  w  w  w  .j  ava2 s .  co  m*/
    try {
        process = runtime.exec(command);
        try {
            String str;
            process.waitFor();
            BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            while ((str = stdError.readLine()) != null) {
                Log.e("Exec", str);
                if (setError)
                    errOcc = true;
            }
            process.getInputStream().close();
            process.getOutputStream().close();
            process.getErrorStream().close();
        } catch (InterruptedException e) {
            if (setError)
                errOcc = true;
        }
    } catch (IOException e1) {
        errOcc = true;
    }
}

From source file:Enrichissement.GraphViz.java

/**
 * It will call the external dot program, and return the image in
 * binary format.//  w w  w  .j  a va2  s  .c o 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.
 * @param representationType Type of how you want to represent the graph:
 * <ul>
 *    <li>dot</li>
 *    <li>neato</li>
 *    <li>fdp</li>
 *    <li>sfdp</li>
 *    <li>twopi</li>
 *    <li>circo</li>
 * </ul>
 * @see http://www.graphviz.org under the Roadmap title
 * @return The image of the graph in .gif format.
 */
private byte[] get_img_stream(File dot, String type, String representationType) {
    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
        // representation type with -K argument by Olivier Duplouy
        String[] args = { DOT, "-T" + type, "-K" + representationType, "-Gdpi=" + dpiSizes[this.currentDpiPos],
                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)
            System.err.println("Warning: " + img.getAbsolutePath() + " could not be deleted!");
    } catch (java.io.IOException ioe) {
        System.err.println("Error:    in I/O processing of tempfile in dir " + GraphViz.TEMP_DIR + "\n");
        System.err.println("       or in calling external command");
        ioe.printStackTrace();
    } catch (java.lang.InterruptedException ie) {
        System.err.println("Error: the execution of the external program was interrupted");
        ie.printStackTrace();
    }

    return img_stream;
}

From source file:com.xpn.xwiki.plugin.graphviz.GraphVizPlugin.java

/**
 * Executes GraphViz, writes the resulting image (in the requested format) in a temporary file on disk, and returns
 * the generated content from that file.
 * /*  w  w  w  . j a va2  s  .c  om*/
 * @param hashCode the hascode of the content, to be used as the temporary file name
 * @param content the dot source code
 * @param extension the output file extension
 * @param dot which engine to execute: {@code dot} if {@code true}, {@code neato} if {@code false}
 * @return the content of the generated file
 * @throws IOException if writing the input or output files to the disk fails, or if writing the response body fails
 */
private byte[] getDotImage(int hashCode, String content, String extension, boolean dot) throws IOException {
    File dfile = getTempFile(hashCode, "input.dot", dot);
    if (!dfile.exists()) {
        FileUtils.write(dfile, content, XWiki.DEFAULT_ENCODING);
    }

    File ofile = getTempFile(hashCode, extension, dot);
    if (!ofile.exists()) {
        Runtime rt = Runtime.getRuntime();
        String[] command = new String[5];
        command[0] = dot ? this.dotPath : this.neatoPath;
        command[1] = "-T" + extension;
        command[2] = dfile.getAbsolutePath();
        command[3] = "-o";
        command[4] = ofile.getAbsolutePath();
        Process p = rt.exec(command);
        int exitValue = -1;
        final Thread thisThread = Thread.currentThread();
        Thread t = new Thread(new Hangcheck(thisThread), "dot-hangcheck");
        t.run();
        try {
            exitValue = p.waitFor();
            t.interrupt();
        } catch (InterruptedException ex) {
            p.destroy();
            LOGGER.error("Timeout while generating image from dot", ex);
        }

        if (exitValue != 0) {
            LOGGER.error("Error while generating image from dot: "
                    + IOUtils.toString(p.getErrorStream(), XWiki.DEFAULT_ENCODING));
        }
    }
    return FileUtils.readFileToByteArray(ofile);
}

From source file:org.openmeetings.app.data.flvrecord.converter.FlvInterviewConverter.java

public HashMap<String, String> processImageWindows(String file1, String file2, String file3) {
    HashMap<String, String> returnMap = new HashMap<String, String>();
    returnMap.put("process", "processImageWindows");
    try {/*from   w w  w.  j  ava 2  s.c  o m*/

        // Init variables
        String[] cmd;
        String executable_fileName = "";
        String pathToIMagick = this.getPathToImageMagick();

        Date tnow = new Date();
        String runtimeFile = "interviewMerge" + tnow.getTime() + ".bat";

        // String runtimeFile = "interviewMerge.bat";
        executable_fileName = ScopeApplicationAdapter.batchFileDir + runtimeFile;

        cmd = new String[1];
        cmd[0] = executable_fileName;

        // Create the Content of the Converter Script (.bat or .sh File)
        String fileContent = pathToIMagick + " " + file1 + " " + file2 + " " + "+append" + " " + file3
                + ScopeApplicationAdapter.lineSeperator + "";

        File previous = new File(executable_fileName);
        if (previous.exists()) {
            previous.delete();
        }

        // execute the Script
        FileOutputStream fos = new FileOutputStream(executable_fileName);
        fos.write(fileContent.getBytes());
        fos.close();

        File now = new File(executable_fileName);
        now.setExecutable(true);

        Runtime rt = Runtime.getRuntime();
        returnMap.put("command", cmd.toString());
        Process proc = rt.exec(cmd);

        InputStream stderr = proc.getErrorStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(stderr));
        String line = null;
        String error = "";
        while ((line = br.readLine()) != null) {
            error += line;
        }
        br.close();
        returnMap.put("error", error);
        int exitVal = proc.waitFor();
        returnMap.put("exitValue", "" + exitVal);

        if (now.exists()) {
            now.delete();
        }

        return returnMap;
    } catch (Throwable t) {
        t.printStackTrace();
        returnMap.put("error", t.getMessage());
        returnMap.put("exitValue", "-1");
        return returnMap;
    }
}

From source file:com.flyhz.avengers.framework.application.AnalyzeApplication.java

/**
 * Dump out contents of $CWD and the environment to stdout for debugging
 *//*from w ww .j  a  v  a 2s. c  o  m*/
@SuppressWarnings("unused")
private void dumpOutDebugInfo() {

    LOG.info("Dump debug output");
    Map<String, String> envs = System.getenv();
    for (Map.Entry<String, String> env : envs.entrySet()) {
        LOG.info("System env: key=" + env.getKey() + ", val=" + env.getValue());
        System.out.println("System env: key=" + env.getKey() + ", val=" + env.getValue());
    }

    String cmd = "ls -al";
    Runtime run = Runtime.getRuntime();
    Process pr = null;
    try {
        pr = run.exec(cmd);
        pr.waitFor();

        BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));
        String line = "";
        while ((line = buf.readLine()) != null) {
            LOG.info("System CWD content: " + line);
            System.out.println("System CWD content: " + line);
        }
        buf.close();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

From source file:com.redpill_linpro.libreoffice.LibreOfficeLauncherMacOSXImpl.java

@Override
public void launchLibreOffice(String cmisUrl, String repositoryId, String filePath, String webdavUrl) {

    Runtime rt = Runtime.getRuntime();
    try {/*  w  w  w .  j a  va  2s  .  c o m*/
        String params;
        if (null != webdavUrl && webdavUrl.length() > 0) {
            params = LibreOfficeLauncherHelper.generateLibreOfficeWebdavOpenUrl(webdavUrl);
        } else {
            params = LibreOfficeLauncherHelper.generateLibreOfficeCmisOpenUrl(cmisUrl, repositoryId, filePath);
        }
        StringBuffer cmd = new StringBuffer();
        try {
            String[] binaryLocations = { "/Applications/LibreOffice.app/Contents/MacOS/soffice" };
            cmd.append(binaryLocations[0] + " " + params);
            System.out.println("Command: " + cmd.toString());
            rt.exec(cmd.toString());

            System.out.println("Process started");
        } catch (IOException e) {
            JOptionPane.showMessageDialog(null, "Failed to start LibreOffice, commandline: " + cmd.toString(),
                    "Error", JOptionPane.ERROR_MESSAGE);
            e.printStackTrace();
        }

    } catch (UnsupportedEncodingException e1) {
        JOptionPane.showMessageDialog(null, "Invalid URL for LibreOffice", "Error", JOptionPane.ERROR_MESSAGE);
        e1.printStackTrace();
    }
}

From source file:com.persistent.cloudninja.service.impl.ProvisioningServiceImpl.java

/**
 * Returns the thumbprint of the certificate.
 * // w w  w  .j a va2 s  . c  om
 * @param tenantId
 * @return the thumbprint.
 * @throws IOException
 * @throws InterruptedException
 */
private String getThumbprint(String tenantId) throws IOException, InterruptedException {
    String destination = "";

    // Creating a Self Signed Certificate
    StringBuffer keytoolPath = new StringBuffer();
    keytoolPath.append(System.getProperty("java.home"));
    if (keytoolPath.length() == 0) {
        keytoolPath.append(System.getenv("JRE_HOME"));
    }

    destination = keytoolPath.toString();
    destination = destination + File.separator + "lib" + File.separator + "security" + File.separator;

    keytoolPath.append(File.separator).append("bin");
    keytoolPath.append(File.separator);

    Runtime runtime = Runtime.getRuntime();

    String getThumbprint = "cmd /c cd /d \"" + keytoolPath.toString() + "\" && keytool.exe -list -keystore \""
            + destination + tenantId + "_keystore.pfx\" -storepass " + String.format(passwordPrefix, tenantId)
            + " -storetype pkcs12";
    Process p = runtime.exec(getThumbprint);
    p.waitFor();

    BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String line = null;
    while ((line = in.readLine()) != null) {
        if (line.contains("Certificate fingerprint (SHA1)")) {
            break;
        }
    }
    String thumbprint = line.replace("Certificate fingerprint (SHA1)", "");
    thumbprint = thumbprint.trim();
    thumbprint = thumbprint.replaceAll(":", "");
    return thumbprint.trim();
}

From source file:br.com.thinkti.android.filechooserfrag.fragFileChooser.java

@Override
public boolean onContextItemSelected(MenuItem item) {
    AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
    View v = info.targetView;/*w w w.  j  a v  a  2 s  .  c om*/
    final Option o = adapter.getItem((int) info.id);
    switch (item.getItemId()) {
    case R.id.mnuDelete:
        String msg = String.format(getString(R.string.txtReallyDelete), o.getName());
        if (lib.ShowMessageYesNo(_main, msg, _main.getString(R.string.question)) == lib.yesnoundefined.yes) {
            try {
                File F = new File(o.getPath());
                boolean delete = false;
                if (F.exists()) {
                    if (F.isDirectory()) {
                        String[] deleteCmd = { "rm", "-r", F.getPath() };
                        Runtime runtime = Runtime.getRuntime();
                        runtime.exec(deleteCmd);
                        delete = true;
                    } else {
                        delete = F.delete();
                    }
                }

                if (delete)
                    adapter.remove(o);

            } catch (Exception ex) {
                lib.ShowMessage(_main, ex.getMessage(), getString((R.string.Error)));
            }
        }
        //lib.ShowToast(_main,"delete " + t1.getText().toString() + " " + t2.getText().toString() + " " + o.getData() + " "  + o.getPath() + " " + o.getName());
        //editNote(info.id);
        return true;
    case R.id.mnuRename:
        String msg2 = String.format(getString(R.string.txtRenameFile), o.getName());
        AlertDialog.Builder A = new AlertDialog.Builder(_main);
        final EditText inputRename = new EditText(_main);
        A.setMessage(msg2);
        A.setTitle(getString(R.string.rename));

        // Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
        inputRename.setInputType(InputType.TYPE_CLASS_TEXT);
        inputRename.setText(o.getName());
        A.setView(inputRename);
        A.setPositiveButton(_main.getString(R.string.ok), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String name = inputRename.getText().toString();
                final String pattern = ".+\\.(((?i)v.{2})|((?i)k.{2})|((?i)dic))$";
                Pattern vok = Pattern.compile(pattern);
                if (lib.libString.IsNullOrEmpty(name))
                    return;
                if (vok.matcher(name).matches()) {
                    try {

                        File F = new File(o.getPath());
                        File F2 = new File(F.getParent(), name);
                        if (!F2.exists()) {
                            final boolean b = F.renameTo(F2);
                            if (b) {
                                o.setName(name);
                                o.setPath(F2.getPath());
                                adapter.notifyDataSetChanged();
                            }
                        } else {
                            lib.ShowMessage(_main, getString(R.string.msgFileExists), "");
                        }

                    } catch (Exception ex) {
                        lib.ShowMessage(_main, ex.getMessage(), getString((R.string.Error)));
                    }
                } else {
                    AlertDialog.Builder A = new AlertDialog.Builder(_main);
                    A.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    });
                    A.setMessage(getString(R.string.msgWrongExt2));
                    A.setTitle(getString(R.string.message));
                    AlertDialog dlg = A.create();
                    dlg.show();

                }
            }
        });
        A.setNegativeButton(_main.getString(R.string.cancel), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        AlertDialog dlg = A.create();
        dlg.show();
        return true;
    case R.id.mnuCopy:
        _copiedFile = (o.getPath());
        _cutFile = null;
        return true;
    case R.id.mnuCut:
        _cutFile = (o.getPath());
        _cutOption = o;
        _copiedFile = null;
        return true;
    case R.id.mnuPaste:
        if (_cutFile != null && _copiedFile != null)
            return true;
        String path;
        File F = new File(o.getPath());
        if (F.isDirectory()) {
            path = F.getPath();
        } else {
            path = F.getParent();
        }
        if (_copiedFile != null) {
            File source = new File(_copiedFile);
            File dest = new File(path, source.getName());
            if (dest.exists()) {
                lib.ShowMessage(_main, getString(R.string.msgFileExists), "");
                return true;
            }
            String[] copyCmd;
            if (source.isDirectory()) {
                copyCmd = new String[] { "cp", "-r", _copiedFile, path };
            } else {
                copyCmd = new String[] { "cp", _copiedFile, path };
            }
            Runtime runtime = Runtime.getRuntime();
            try {
                runtime.exec(copyCmd);
                Option newOption;
                if (dest.getParent().equalsIgnoreCase(currentDir.getPath())) {
                    if (dest.isDirectory() && !dest.isHidden()) {
                        adapter.add(new Option(dest.getName(), getString(R.string.folder),
                                dest.getAbsolutePath(), true, false, false));
                    } else {
                        if (!dest.isHidden())
                            adapter.add(new Option(dest.getName(),
                                    getString(R.string.fileSize) + ": " + dest.length(), dest.getAbsolutePath(),
                                    false, false, false));
                    }
                }
            } catch (Exception ex) {
                lib.ShowMessage(_main, ex.getMessage(), getString((R.string.Error)));
            }

        } else if (_cutFile != null) {
            File source = new File(_cutFile);
            File dest = new File(path, source.getName());
            if (dest.exists()) {
                lib.ShowMessage(_main, getString(R.string.msgFileExists), "");
                return true;
            }
            String[] copyCmd;
            if (source.isDirectory()) {
                copyCmd = new String[] { "mv", "-r", _cutFile, path };
            } else {
                copyCmd = new String[] { "mv", _cutFile, path };
            }
            Runtime runtime = Runtime.getRuntime();
            _cutFile = null;
            try {
                runtime.exec(copyCmd);
                Option newOption;
                try {
                    adapter.remove(_cutOption);
                    _cutOption = null;
                } catch (Exception e) {

                }
                if (dest.getParent().equalsIgnoreCase(currentDir.getPath())) {
                    if (dest.isDirectory() && !dest.isHidden()) {
                        adapter.add(new Option(dest.getName(), getString(R.string.folder),
                                dest.getAbsolutePath(), true, false, false));
                    } else {
                        if (!dest.isHidden())
                            adapter.add(new Option(dest.getName(),
                                    getString(R.string.fileSize) + ": " + dest.length(), dest.getAbsolutePath(),
                                    false, false, false));
                    }
                }
            } catch (Exception ex) {
                lib.ShowMessage(_main, ex.getMessage(), getString((R.string.Error)));
            }
        }
        return true;
    case R.id.mnuNewFolder:
        A = new AlertDialog.Builder(_main);
        //final EditText input = new EditText(_main);
        final EditText inputNF = new EditText(_main);
        A.setMessage(getString(R.string.msgEnterNewFolderName));
        A.setTitle(getString(R.string.cmnuNewFolder));

        // Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
        inputNF.setInputType(InputType.TYPE_CLASS_TEXT);
        inputNF.setText("");
        A.setView(inputNF);
        A.setPositiveButton(_main.getString(R.string.ok), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String name = inputNF.getText().toString();
                if (lib.libString.IsNullOrEmpty(name))
                    return;
                String NFpath;
                File NF = new File(o.getPath());
                if (NF.isDirectory()) {
                    NFpath = NF.getPath();
                } else {
                    NFpath = NF.getParent();
                }
                try {
                    File NewFolder = new File(NFpath, name);
                    NewFolder.mkdir();
                    adapter.add(new Option(NewFolder.getName(), getString(R.string.folder),
                            NewFolder.getAbsolutePath(), true, false, false));

                } catch (Exception ex) {
                    lib.ShowException(_main, ex);
                }
            }
        });
        A.setNegativeButton(_main.getString(R.string.cancel), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        dlg = A.create();
        dlg.show();
        return true;
    default:
        return super.onContextItemSelected(item);
    }
}

From source file:de.unibi.cebitec.bibiserv.web.beans.runinthecloud.BashExecutor.java

/**
 * Creates the bibigrid-starter-script which is needed to execute the
 * bibigrid binaries correctly./*  www.j  ava 2  s .c  o m*/
 *
 * @param tempDirectoryPath
 * @param bashFile
 */
private void createGridStartScript(final Path tempDirectoryPath, final File bashFile) {
    final String username = user.getId();
    Thread gridCreatorThread = new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                try (BufferedWriter output = new BufferedWriter(new FileWriter(bashFile))) {
                    output.write("#!" + BiBiTools.getProperties().getProperty("batchfile.shell") + " \n");
                    // set classpath
                    output.write("CLASSPATH=" + BiBiTools.getProperties().getProperty("bibigrid.bin") + " ");
                    // added -gpf to obtain the grid.properties file at the end
                    output.write(BiBiTools.getProperties().getProperty("bibigrid.bin") + "bibigrid -o "
                            + bibigridPropertiesFile + " -gpf " + gridPropertiesFile + " -c ");
                    output.close();
                }
                Runtime rr = Runtime.getRuntime();
                // setting access
                rr.exec("chmod u+x " + bashFile.getAbsolutePath());
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }

    });
    gridCreatorThread.start();
}