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:Interfaz.adminZone.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    Runtime aplicacion = Runtime.getRuntime();
    try {//from   w w w.j  a v a  2s  . c om
        aplicacion.exec("C:/Program Files (x86)/Skype/Phone/Skype.exe");
    } catch (Exception e) {
    }
}

From source file:eu.itool.glassfishmavenplugin.AbstractGlassfishMojo.java

protected void launch(String fName, String params) throws MojoExecutionException {

    try {//from   w  w w  .  j a v  a2  s  .co  m

        checkConfig();

        String osName = System.getProperty("os.name");
        Runtime runtime = Runtime.getRuntime();

        Process p = null;
        if (osName.startsWith("Windows")) {
            String command[] = { "cmd.exe", "/C",
                    "cd " + glassfishHomeDir.getAbsolutePath() + "\\bin & " + fName + ".bat " + " " + params };

            p = runtime.exec(command);

            InputStream is = p.getErrorStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String line = "";
            String ln;
            while ((ln = br.readLine()) != null) {
                line += ln;
                getLog().info(ln);

            }
            if (line.contains("failed"))
                throw new MojoFailureException(line);

        } else {
            String command[] = { "sh", "-c",
                    "cd " + glassfishHomeDir.getAbsolutePath() + "/bin; ./" + fName + " " + params };
            p = runtime.exec(command);

            InputStream is = p.getErrorStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String line = "";
            String ln;
            while ((ln = br.readLine()) != null) {
                line += ln;
                getLog().info(ln);
            }
            if (line.contains("failed"))
                throw new MojoFailureException(line);
        }

    } catch (Exception e) {
        throw new MojoExecutionException("Mojo error occurred: " + e.getMessage(), e);
    }
}

From source file:com.longevitysoft.java.bigslice.server.SlicerSlic3r.java

@Override
public void slice(@Header(value = Constants.MSG_HEADER_SLICE_CONFIG_ARRAY_LIST) String configList,
        @Header(value = Constants.MSG_HEADER_CAMEL_FILE_ABSOLUTE_PATH) String filePath,
        @Header(value = Constants.MSG_HEADER_OUTPUT_PATH) String headerOutputFilename) {
    Endpoint epSlice = camel.getEndpoint(Constants.EP_NAME_JMS_QUEUE_PENDINGSTL);
    Exchange inEx = epSlice.createExchange(ExchangePattern.InOnly);
    // check if output filename header present
    StringBuilder configFileParam = new StringBuilder();
    if (null != configList) {
        configList = configList.trim();/*from   ww  w.ja  v  a2s  .  c  o m*/
        String[] configs = configList.split(",");
        LOG.debug("configs received in msg header");
        configFileParam.append(Constants.SPACE);
        for (String configName : configs) {
            configFileParam.append(Constants.SLIC3R_PARAM_NAME_LOAD).append(Constants.SPACE).append(configName);
        }
    }
    // check if output filename header present
    try {
        StringBuilder gcodeOutputFilename = new StringBuilder().append(Constants.PARENT_DIR)
                .append(Constants.FILEPATH_GCODEOUT); // slic3r
        // uses
        // STL
        // folder
        // by
        // default
        if (null != headerOutputFilename) {
            gcodeOutputFilename.append(Constants.SLASH)
                    .append(headerOutputFilename.replace(Constants.TILDE_BANG_TILDE,
                            Constants.SLIC3R_PARAM_VAL_INPUT_FILENAME_BASE + Constants.UNDERSCORE));
            // init directory-tree in output filename
            int lastSlash = headerOutputFilename.lastIndexOf("/");
            if (0 < lastSlash) {
                String outputTree = headerOutputFilename.substring(0, lastSlash);
                outputTree = outputTree.replace("/./", "/");
                File outDir = new File(buildOutputPath() + Constants.SLASH + outputTree);
                outDir.mkdirs();
            }
        } else {
            gcodeOutputFilename.append(Constants.SLASH).append(Constants.SLIC3R_PARAM_VAL_INPUT_FILENAME_BASE);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-dd-MM__HH-mm-ss");
            gcodeOutputFilename.append("_TS").append(sdf.format(Calendar.getInstance().getTime()));
        }
        if (null == pathToExecutable) {
            throw new InterruptedException("no exec path found");
        }
        for (int i = 0; i < pathToExecutable.size(); i++) {
            String execPath = pathToExecutable.get(i);
            // inject executable name into gcode output filename
            String insToken = null;
            int insertPos = gcodeOutputFilename.indexOf(Constants.SLIC3R_PARAM_VAL_INPUT_FILENAME_BASE);
            if (0 < insertPos) {
                insertPos += Constants.SLIC3R_PARAM_VAL_INPUT_FILENAME_BASE.length();
                if (null != execOutputFilenameFilter) {
                    insToken = execOutputFilenameFilter.get(i);
                }
                if (null == insToken) {
                    insToken = sanitizeFilename(execPath);
                }
                insToken = Constants.UNDERSCORE + insToken;
            }
            // build exec string
            final StringBuilder execStr = new StringBuilder(execPath).append(configFileParam)
                    .append(Constants.SPACE).append(Constants.SLIC3R_CLI_PARAM_OUTPUT_FILENAME_FORMAT)
                    .append(gcodeOutputFilename.substring(0, insertPos)).append(insToken)
                    .append(gcodeOutputFilename.substring(insertPos, gcodeOutputFilename.length()))
                    .append(Constants.EXT_GCODE).append(Constants.SPACE).append(filePath);
            LOG.debug("executing-slic3r: " + execStr + Constants.NEWLINE);
            final String fPath = filePath;
            final StringBuilder gcodeOutFName = gcodeOutputFilename;
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        Runtime rt = Runtime.getRuntime();
                        RuntimeExec rte = new RuntimeExec();
                        StreamWrapper error, output;
                        Process proc = rt.exec(execStr.toString());
                        error = rte.getStreamWrapper(proc.getErrorStream(), Constants.STREAM_NAME_ERROR);
                        output = rte.getStreamWrapper(proc.getInputStream(), Constants.STREAM_NAME_OUTPUT);
                        int exitVal = 0;
                        error.start();
                        output.start();
                        error.join(3000);
                        output.join(3000);
                        exitVal = proc.waitFor();
                        // TODO process exitVal for caller - decide what to
                        // do in
                        // http://camel.apache.org/exception-clause.html
                        LOG.info(new StringBuilder().append("stl-file-path: ").append(fPath)
                                .append(", output-file-path:").append(gcodeOutFName).append(Constants.NEWLINE)
                                .append(", proc-output: ").append(output.getMessage()).append(Constants.NEWLINE)
                                .append(", proc-error: ").append(error.getMessage()).toString());
                    } catch (Exception e) {
                        LOG.trace(e.toString());
                    }
                }
            });
        }
    } catch (InterruptedException e) {
        LOG.trace(e.toString());
    }
}

From source file:org.openmicroscopy.shoola.env.ui.UserNotifierImpl.java

/**
 * Implemented as specified by {@link UserNotifier}.
 * /*from  w w w .  ja v  a 2s.  c  o  m*/
 * @see UserNotifier#openApplication(Object)
 */
public void openApplication(ApplicationData data, String path) {

    if (data == null && path == null)
        return;

    Logger logger = manager.getRegistry().getLogger();
    try {
        String[] commandLineElements = ApplicationData.buildCommand(data, new File(path));

        logger.info(this, "Executing command & args: " + Arrays.toString(commandLineElements));

        Runtime runtime = Runtime.getRuntime();
        runtime.exec(commandLineElements);
    } catch (Exception e) {
        logger.error(this, e.getMessage());
    }
}

From source file:com.SecUpwN.AIMSICD.smsdetection.SmsDetector.java

@Override
public void run() {

    setSmsDetectionState(true);/*from  www  .  jav  a  2  s . c  om*/

    try {

        try {
            new Thread().sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try {
            String MODE = "logcat -b radio\n";// default
            Runtime r = Runtime.getRuntime();
            Process process = r.exec("su");
            dos = new DataOutputStream(process.getOutputStream());

            dos.writeBytes(MODE);
            dos.flush();

            dis = new DataInputStream(process.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }

        while (getSmsDetectionState()) {
            try {

                int bufferlen = dis.available();
                //System.out.println("DEBUG>> Buff Len " +bufferlen);

                if (bufferlen != 0) {
                    byte[] b = new byte[bufferlen];
                    dis.read(b);

                    String split[] = new String(b).split("\n");
                    checkForSilentSms(split);

                } else {

                    Thread.sleep(1000);
                }

            } catch (IOException e) {
                if (e.getMessage() != null)
                    System.out.println(e.getMessage());
                e.printStackTrace();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {

    }
}

From source file:gov.nih.nci.sdk.example.generator.WebServiceGenerator.java

public void runCommand(String _command) {
    try {//from  ww w.  ja v  a2s .  co  m
        StringBuffer input = new StringBuffer();

        input.setLength(0); // erase input StringBuffer
        String s;

        if (_command != null) {
            Runtime a = Runtime.getRuntime();
            java.lang.Process p = a.exec(_command);

            BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));

            BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));

            // read the output from the command

            // System.out.println("Here is the standard output of the command:\n");
            while ((s = stdInput.readLine()) != null) {
                input.append(s);
            }

            // read any errors from the attempted command
            while ((s = stdError.readLine()) != null) {
                getScriptContext().logInfo(s);
            }

        }
    } catch (Throwable t) {
        t.printStackTrace();
        getScriptContext().logError(t);
    }
}

From source file:at.alladin.rmbt.android.impl.TracerouteAndroidImpl.java

public List<HopDetail> call() throws Exception {
    isRunning.set(true);/*ww w. ja v  a 2 s. com*/
    List<HopDetail> pingDetailList = new ArrayList<HopDetail>();
    final Runtime runtime = Runtime.getRuntime();

    for (int i = 1; i <= maxHops; i++) {
        if (Thread.interrupted() || !isRunning.get()) {
            throw new InterruptedException();
        }
        final long ts = System.nanoTime();
        final Process mIpAddrProcess = runtime.exec("/system/bin/ping -c 1 -t " + i + " -W2 " + host);
        final String proc = readFromProcess(mIpAddrProcess);
        final PingDetailImpl pingDetail = new PingDetailImpl(proc, System.nanoTime() - ts);
        pingDetailList.add(pingDetail);
        if (pingDetail.getReceived() > 0) {
            hasMaxHopsExceeded = false;
            break;
        }
    }

    return pingDetailList;
}

From source file:org.quartz.ui.example.NativeJob.java

private Integer runNativeCommand(String command, String parameters, boolean wait, boolean consumeStreams)
        throws JobExecutionException {

    String[] cmd = null;/*from   w ww  .j  a v  a2 s  .com*/
    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");

        //only will work with Windows NT
        if (osName.equals("Windows NT")) {
            if (cmd == null) {
                cmd = new String[args.length + 2];
            }
            cmd[0] = "cmd.exe";
            cmd[1] = "/C";
            for (int i = 0; i < args.length; i++) {
                cmd[i + 2] = args[i];
            }
        } else if (osName.equals("Windows 95")) { //only will work with Windows 95
            if (cmd == null) {
                cmd = new String[args.length + 2];
            }
            cmd[0] = "command.com";
            cmd[1] = "/C";
            for (int i = 0; i < args.length; i++) {
                cmd[i + 2] = args[i];
            }
        } else if (osName.equals("Windows 2003")) { //only will work with Windows 2003
            if (cmd == null) {
                cmd = new String[args.length + 2];
            }
            cmd[0] = "cmd.exe";
            cmd[1] = "/C";

            for (int i = 0; i < args.length; i++) {
                cmd[i + 2] = args[i];
            }
        } else if (osName.equals("Windows 2000")) { //only will work with Windows 2000
            if (cmd == null) {
                cmd = new String[args.length + 2];
            }
            cmd[0] = "cmd.exe";
            cmd[1] = "/C";

            for (int i = 0; i < args.length; i++) {
                cmd[i + 2] = args[i];
            }
        } else if (osName.equals("Windows XP")) { //only will work with Windows XP
            if (cmd == null) {
                cmd = new String[args.length + 2];
            }
            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:net.kyllercg.acms.ACMgen.java

/**
 * System call to the pep2smv program to generate the SMV model from the
 * PEP model.//from  w w w. ja va  2s  . co m
 * @param pepcode - the PEP model
 * @return - a vector with the SMV model
 */
protected Vector<String> genPEPfromSMV(Vector<String> pepcode) {

    FileUtils f = new FileUtils();
    String pep_file = ACMgenOptions.tmp_dir + "/" + ACMgenOptions.output_file + ACMgenOptions.llnet_ext;
    String smv_file = ACMgenOptions.tmp_dir + "/" + ACMgenOptions.output_file + ACMgenOptions.smv_ext;
    String cmdline = ACMgenOptions.pep2smv_file + " " + pep_file;
    Vector<String> v = null;

    f.writeTextFile(pep_file, pepcode);

    try {

        Runtime r = Runtime.getRuntime();
        r.exec(cmdline).waitFor();

        FileUtils inf = new FileUtils();
        v = inf.readTextFile(smv_file);

        File f1 = new File(pep_file);
        File f2 = new File(smv_file);

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

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

        if (v == null) {

            this.printErrorMsg(ACMgen.msg.getMessage("smvcode_error_msg"));
            System.exit(-1);
        }
    } catch (IOException e) {

        this.printErrorMsg(ACMgen.msg.getMessage("smvcode_error_msg") + e.getMessage());
        e.printStackTrace();
        System.exit(-1);
    } catch (InterruptedException e) {

        this.printErrorMsg(ACMgen.msg.getMessage("pep2smv_term__error_msg") + e.getMessage());
        e.printStackTrace();
        System.exit(-1);
    }

    return v;
}

From source file:ch.kostceco.tools.siardexcerpt.excerption.moduleexcerpt.impl.ExcerptBSearchModuleImpl.java

@Override
public boolean validate(File siardDatei, File outFileSearch, String searchString)
        throws ExcerptBSearchException {
    boolean isValid = true;

    File fGrepExe = new File("resources" + File.separator + "grep" + File.separator + "grep.exe");
    String pathToGrepExe = fGrepExe.getAbsolutePath();
    if (!fGrepExe.exists()) {
        // grep.exe existiert nicht --> Abbruch
        getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_B)
                + getTextResourceService().getText(ERROR_XML_C_MISSINGFILE, fGrepExe.getAbsolutePath()));
        return false;
    } else {// w w  w  .  ja  va2s .com
        File fMsys10dll = new File("resources" + File.separator + "grep" + File.separator + "msys-1.0.dll");
        if (!fMsys10dll.exists()) {
            // msys-1.0.dll existiert nicht --> Abbruch
            getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_B)
                    + getTextResourceService().getText(ERROR_XML_C_MISSINGFILE, fMsys10dll.getAbsolutePath()));
            return false;
        }
    }

    File tempOutFile = new File(outFileSearch.getAbsolutePath() + ".tmp");
    String content = "";
    String contentAll = "";

    // Records aus table herausholen
    try {
        if (tempOutFile.exists()) {
            Util.deleteDir(tempOutFile);
        }

        /* Nicht vergessen in "src/main/resources/config/applicationContext-services.xml" beim
         * entsprechenden Modul die property anzugeben: <property name="configurationService"
         * ref="configurationService" /> */

        String name = getConfigurationService().getSearchtableName();
        String folder = getConfigurationService().getSearchtableFolder();

        File fSearchtable = new File(siardDatei.getAbsolutePath() + File.separator + "content" + File.separator
                + "schema0" + File.separator + folder + File.separator + folder + ".xml");

        searchString = searchString.replaceAll("\\.", "\\.*");

        try {
            // grep -E "REGEX-Suchbegriff" table13.xml >> output.txt
            String command = "cmd /c \"" + pathToGrepExe + " -E \"" + searchString + "\" "
                    + fSearchtable.getAbsolutePath() + " >> " + tempOutFile.getAbsolutePath() + "\"";
            /* Das redirect Zeichen verunmglicht eine direkte eingabe. mit dem geschachtellten Befehl
             * gehts: cmd /c\"urspruenlicher Befehl\" */

            // System.out.println( command );

            Process proc = null;
            Runtime rt = null;

            getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_ELEMENT_OPEN, name));

            try {
                Util.switchOffConsole();
                rt = Runtime.getRuntime();
                proc = rt.exec(command.toString().split(" "));
                // .split(" ") ist notwendig wenn in einem Pfad ein Doppelleerschlag vorhanden ist!

                // Fehleroutput holen
                StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR");

                // Output holen
                StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT");

                // Threads starten
                errorGobbler.start();
                outputGobbler.start();

                // Warte, bis wget fertig ist
                proc.waitFor();

                Util.switchOnConsole();

            } catch (Exception e) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_B)
                        + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage()));
                return false;
            } finally {
                if (proc != null) {
                    closeQuietly(proc.getOutputStream());
                    closeQuietly(proc.getInputStream());
                    closeQuietly(proc.getErrorStream());
                }
            }

            Scanner scanner = new Scanner(tempOutFile);
            contentAll = "";
            content = "";
            contentAll = scanner.useDelimiter("\\Z").next();
            scanner.close();
            content = contentAll;
            /* im contentAll ist jetzt der Gesamtstring, dieser soll anschliessend nur noch aus den 4
             * Such-Zellen und den weiteren 4 ResultateZellen bestehen -> content */
            String nr1 = getConfigurationService().getcellNumber1();
            String nr2 = getConfigurationService().getcellNumber2();
            String nr3 = getConfigurationService().getcellNumber3();
            String nr4 = getConfigurationService().getcellNumber4();
            String nr5 = getConfigurationService().getcellNumberResult1();
            String nr6 = getConfigurationService().getcellNumberResult2();
            String nr7 = getConfigurationService().getcellNumberResult3();
            String nr8 = getConfigurationService().getcellNumberResult4();

            String cellLoop = "";
            // Loop von 1, 2, 3 ... bis 499999.
            for (int i = 1; i < 500000; i++) {
                cellLoop = "";
                cellLoop = "c" + i;
                if (cellLoop.equals(nr1) || cellLoop.equals(nr2) || cellLoop.equals(nr3) || cellLoop.equals(nr4)
                        || cellLoop.equals(nr5) || cellLoop.equals(nr6) || cellLoop.equals(nr7)
                        || cellLoop.equals(nr8)) {
                    // wird behalten
                } else {
                    String deletString = "<c" + i + ">" + ".*" + "</c" + i + ">";
                    content = content.replaceAll(deletString, "");
                }
            }

            getMessageService()
                    .logError(getTextResourceService().getText(MESSAGE_XML_ELEMENT_CONTENT, content));
            getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_ELEMENT_CLOSE, name));

            if (tempOutFile.exists()) {
                Util.deleteDir(tempOutFile);
            }
            contentAll = "";
            content = "";

            // Ende Grep

        } catch (Exception e) {
            getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_B)
                    + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage()));
            return false;
        }

    } catch (Exception e) {
        getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_B)
                + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage()));
        return false;
    }

    return isValid;
}