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:fr.inria.oak.paxquery.common.xml.navigation.NavigationTreePattern.java

public void draw(boolean query, String backgroundColor, String foregroundColor) {
    if (printGraphics == false)
        return;//  w w w.  j  a  v a2 s .c  o  m

    String fileName;
    /*Calendar cal = new GregorianCalendar();
    if(givenFilename == null) {
       if(query)
    fileName = "xam-" + "-" + cal.get(Calendar.HOUR_OF_DAY) + ":" + cal.get(Calendar.MINUTE) + ":" + cal.get(Calendar.SECOND) + "-Query";
       else
    fileName = "xam-" + "-" + cal.get(Calendar.HOUR_OF_DAY) + ":" + cal.get(Calendar.MINUTE) + ":" + cal.get(Calendar.SECOND);
    } else {
       if(query)
    fileName = givenFilename + "-Query";
       else
    fileName = givenFilename;
    }*/
    if (graphicsPath.endsWith("/") == true)
        fileName = graphicsPath + "tp" + printCardinal;
    else
        fileName = graphicsPath + "/tp" + printCardinal;

    String sb = getDotString("tp" + printCardinal, backgroundColor, foregroundColor);
    printCardinal++;

    try {
        String fileNameDot = new String(fileName + ".dot");
        String fileNamePNG = new String(fileName + ".png");
        /*String fileNamePNG;
        if(fileName.contains("/"))
           //fileNamePNG = new String(fileName + ".pdf");
           fileNamePNG = new String(fileName + ".png");
        else
           //fileNamePNG = new String(imagesPath + File.separator + fileName + ".pdf");
           fileNamePNG = new String(imagesPath + File.separator + fileName + ".png");*/
        FileWriter file = new FileWriter(fileNameDot);

        // writing the  .dot file to disk
        file.write(sb);
        file.close();

        // calling GraphViz
        Runtime r = Runtime.getRuntime();
        //String com = new String("/usr/local/bin/dot -Tpdf " + fileNameDot + " -o " + fileNamePNG);
        String com = new String("dot -Tpng " + fileNameDot + " -o " + fileNamePNG);
        Process p = r.exec(com);
        p.waitFor();
        // removing the .dot file
        //Process p2=r.exec("rm "+fileNameDot+"\n");
        //p2.waitFor();
    } catch (IOException e) {
        logger.error("IOException: ", e);
    } catch (InterruptedException e) {
        logger.error("InterruptedException: ", e);
    }
}

From source file:ch.puzzle.itc.mobiliar.business.shakedown.control.ShakedownTestRunner.java

private List<String> copySTMtoRemoteServerAndGetMissingSTPs(String bundle, STS sts)
        throws ShakedownTestException {
    List<String> result = new ArrayList<String>();
    Runtime r = Runtime.getRuntime();
    File f = new File(bundle);
    if (!f.exists()) {
        throw new ShakedownTestException("The STM bundle file " + f.getAbsolutePath() + " does not exist!");
    }/*from  ww w .  java  2  s  . c  om*/
    // Create folder if it does not yet exist
    String createRemoteSTMFolderIfNotExists = "ssh " + sts.getUser() + "@" + sts.getRemoteHost() + " mkdir -p "
            + sts.getRemoteSTPPath() + File.separator + "stms";
    log.info("EXECUTE: " + createRemoteSTMFolderIfNotExists);
    try {
        Process createRemoteSTMFolder = r.exec(createRemoteSTMFolderIfNotExists);
        if (createRemoteSTMFolder.waitFor() != 0) {
            throw new ShakedownTestException("Was not able to create STM folder on remote site: "
                    + sts.getRemoteHost() + File.separator + "stms with user " + sts.getUser());
        }
        String copySTMcommand = "scp " + bundle + " " + sts.getUser() + "@" + sts.getRemoteHost() + ":"
                + sts.getRemoteSTPPath() + File.separator + "stms" + File.separator + f.getName();
        log.info("EXECUTE: " + copySTMcommand);
        Process p = r.exec(copySTMcommand);
        if (p.waitFor() == 0) {
            log.info("Copied STM bundle " + bundle + " to host " + sts.getRemoteHost());
            String launchDepMgmtCommand = "ssh " + sts.getUser() + "@" + sts.getRemoteHost() + " java -jar "
                    + sts.getRemoteSTPPath() + File.separator + "stms" + File.separator + f.getName() + " "
                    + sts.getRemoteSTPPath() + " dependencyManagement";
            log.info("EXECUTE: " + launchDepMgmtCommand);
            Process dependencyMgmt = r.exec(launchDepMgmtCommand);
            BufferedReader bufferedreader = null;
            try {
                bufferedreader = new BufferedReader(
                        new InputStreamReader(new BufferedInputStream(dependencyMgmt.getErrorStream())));
                String errorline;
                while ((errorline = bufferedreader.readLine()) != null) {
                    if (errorline.startsWith("@{") && errorline.trim().endsWith("}")) {
                        result.add(errorline.trim().substring(2, errorline.trim().length() - 1));
                    }
                }
            } finally {
                if (bufferedreader != null) {
                    bufferedreader.close();
                }
            }
        } else {
            throw new ShakedownTestException("Was not able to copy STP " + bundle + " to host "
                    + sts.getRemoteHost() + " with ssh user " + sts.getUser());
        }
    } catch (IOException e) {
        throw new ShakedownTestException("Was not able to copy STM to remote server ", e);
    } catch (InterruptedException e) {
        throw new ShakedownTestException("Was not able to copy STM to remote server ", e);
    }
    return result;
}

From source file:org.pentaho.di.trans.steps.gpload.GPLoad.java

public boolean execute(GPLoadMeta meta, boolean wait) throws KettleException {
    String commandLine = null;//ww  w .j  a  v a2s . c  om
    Runtime rt = Runtime.getRuntime();
    int gpLoadExitVal = 0;

    try {

        commandLine = createCommandLine(meta, true);
        logBasic("Executing: " + commandLine);

        gploadProcess = rt.exec(commandLine);

        // any error message?
        StreamLogger errorLogger = new StreamLogger(gploadProcess.getErrorStream(), "ERROR");

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

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

        if (wait) {
            // any error???
            gpLoadExitVal = gploadProcess.waitFor();
            logBasic(BaseMessages.getString(PKG, "GPLoad.Log.ExitValuePsqlPath", "" + gpLoadExitVal));
            if (gpLoadExitVal != -0) {
                throw new KettleException(
                        BaseMessages.getString(PKG, "GPLoad.Log.ExitValuePsqlPath", "" + gpLoadExitVal));
            }
        }
    } catch (KettleException ke) {
        throw ke;
    } catch (Exception ex) {
        // Don't throw the message upwards, the message contains the password.
        throw new KettleException(
                "Error while executing \'" + commandLine + "\'. Exit value = " + gpLoadExitVal);
    }

    return true;
}

From source file:fastcall.FastCallSNP.java

private void performPileup(int currentChr, int startPos, int endPos, String referenceFileS) {
    System.out.println("Pileup is being performed on chromosome " + String.valueOf(currentChr) + " from "
            + String.valueOf(startPos) + " to " + String.valueOf(endPos));
    long timeStart = System.nanoTime();
    List<String> bamList = Arrays.asList(bamPaths);
    LongAdder counter = new LongAdder();
    bamList.parallelStream().forEach(bamFileS -> {
        String pileupFileS = this.bamPathPileupPathMap.get(bamFileS);
        StringBuilder sb = new StringBuilder();
        sb.append("samtools mpileup -A -B -q 30 -Q 10 -f ").append(referenceFileS).append(" ").append(bamFileS)
                .append(" -r ");
        sb.append(currentChr).append(":").append(startPos).append("-").append(endPos).append(" -o ")
                .append(pileupFileS);/*from   ww  w. ja v a 2s  . c o m*/
        String command = sb.toString();
        try {
            Runtime rt = Runtime.getRuntime();
            Process p = rt.exec(command);
            p.waitFor();
        } catch (Exception e) {
            e.printStackTrace();
        }
        counter.increment();
        int cnt = counter.intValue();
        if (cnt % 10 == 0)
            System.out.println("Pileuped " + String.valueOf(cnt) + " bam files. Total: "
                    + String.valueOf(this.bamPaths.length));
    });
    System.out.println("Pileup is finished. Time took " + Benchmark.getTimeSpanMinutes(timeStart) + " mins");
}

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

/**
 * Creates a self signed certificate for tenant.
 * /*  www  .  j  a v  a  2 s . c om*/
 * @param tenantId
 * @throws IOException
 * @throws InterruptedException
 */
private void createCertificate(String tenantId) throws IOException, InterruptedException {
    String certificateValidity = "365";
    String destination = "";

    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 genCertCommand = "cmd /c cd /d \"" + keytoolPath.toString() + "\" && keytool.exe -genkeypair -alias "
            + tenantId + " -keystore \"" + destination + tenantId + "_keystore.pfx\" -storepass "
            + String.format(passwordPrefix, tenantId) + " -validity " + certificateValidity
            + " -keyalg RSA -keysize 2048 -storetype pkcs12 -dname \"cn=" + "tnt_" + tenantId + "\"";
    // Creating a Self Signed Certificate
    Process p = runtime.exec(genCertCommand);
    p.waitFor();
}

From source file:com.cloud.test.regression.ApiCommand.java

public void sendCommand(HttpClient client, Connection conn) {
    if (TestCaseEngine._printUrl == true) {
        s_logger.info("url is " + this.command);
    }/*from www  . j av  a 2 s  .co m*/

    if (this.getCommandType() == CommandType.SCRIPT) {
        try {
            s_logger.info("Executing command " + this.command);
            Runtime rtime = Runtime.getRuntime();
            Process child = rtime.exec(this.command);
            Thread.sleep(10000);
            int retCode = child.waitFor();
            if (retCode != 0) {
                this.responseCode = retCode;
            } else {
                this.responseCode = 200;
            }

        } catch (Exception ex) {
            s_logger.error("Unable to execute a command " + this.command, ex);
        }
    } else if (this.getCommandType() == CommandType.MYSQL) {
        try {
            Statement stmt = conn.createStatement();
            this.result = stmt.executeQuery(this.command);
            this.responseCode = 200;
        } catch (Exception ex) {
            this.responseCode = 400;
            s_logger.error("Unable to execute mysql query " + this.command, ex);
        }
    } else {
        HttpMethod method = new GetMethod(this.command);
        try {
            this.responseCode = client.executeMethod(method);

            if (this.responseCode == 200) {
                InputStream is = method.getResponseBodyAsStream();
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                DocumentBuilder builder = factory.newDocumentBuilder();
                Document doc = builder.parse(is);
                doc.getDocumentElement().normalize();

                if (!(this.isAsync)) {
                    this.responseBody = doc.getDocumentElement();
                } else {
                    // get async job result
                    Element jobTag = (Element) doc.getDocumentElement().getElementsByTagName("jobid").item(0);
                    String jobId = jobTag.getTextContent();
                    Element responseBodyAsyncEl = queryAsyncJobResult(jobId);
                    if (responseBodyAsyncEl == null) {
                        s_logger.error("Can't get a async result");
                    } else {
                        this.responseBody = responseBodyAsyncEl;
                        // get status of the job
                        Element jobStatusTag = (Element) responseBodyAsyncEl.getElementsByTagName("jobstatus")
                                .item(0);
                        String jobStatus = jobStatusTag.getTextContent();
                        if (!jobStatus.equals("1")) { // Need to modify with different error codes for jobAsync
                            // results
                            // set fake response code by now
                            this.responseCode = 400;
                        }
                    }
                }
            }

            if (TestCaseEngine._printUrl == true) {
                s_logger.info("Response code is " + this.responseCode);
            }
        } catch (Exception ex) {
            s_logger.error("Command " + command + " failed with exception " + ex.getMessage());
        } finally {
            method.releaseConnection();
        }
    }
}

From source file:localization.SplitterUI.java

public boolean checkLicense() throws IOException, InterruptedException {
    boolean psllicense = false;
    String pslcmd = Passolo.substring(0, Passolo.lastIndexOf("\\") + 1) + "pslcmd.exe\"";
    String cmd = "cmd.exe /C " + pslcmd + "/output";
    Runtime rt = Runtime.getRuntime();
    Process proc = rt.exec(cmd);
    int exitVal = proc.waitFor();
    if (exitVal == 99 || exitVal == 98) {
        psllicense = true;/*from  w  w w  . j  ava2  s .co m*/
    }
    return psllicense;
}

From source file:org.sonatype.flexmojos.asdoc.AsDocMojo.java

@FlexCompatibility(maxVersion = "4.0.0.3127")
private void makeHelperExecutable(File templates) throws MojoExecutionException {
    if (!MavenUtils.isWindows()) {
        getLog().info("Making asdoc helper executable due to Flex SDK: " + getCompilerVersion());

        Runtime runtime = Runtime.getRuntime();
        String pathname = String.format("%s/%s", templates.getAbsolutePath(),
                "asDocHelper" + (MavenUtils.isLinux() ? ".linux" : ""));
        String[] statements = new String[] { "chmod", "u+x", pathname };
        try {/*from  w w  w  . j  a  v a2s  .  c  om*/
            Process p = runtime.exec(statements);
            int result = p.waitFor();
            if (0 != result) {
                throw new MojoExecutionException(String.format("Unable to execute %s. Return value = %d",
                        Arrays.asList(statements), result));
            }
        } catch (Exception e) {
            throw new MojoExecutionException(String.format("Unable to execute %s", Arrays.asList(statements)));
        }
    }
}

From source file:san.FileSystemImpl.java

/**
* deleteRoot() - deletes the entire directory including subdirs, files
* @param filePath - filePath //from   ww  w  . ja v  a  2 s. c o  m
* @param path - path
* @param fileName - fileName
* @throws - error when the File object is null
*/
public void deleteAll(String filePath, String path, String fileName) throws SanException {

    logger.info("filePath = " + filePath + " path = " + path + " fileName = " + fileName);

    StringBuffer srcdir = new StringBuffer(path);
    srcdir.append(filePath);
    logger.info("srcdir= " + srcdir.toString());

    try {
        Runtime runtime = Runtime.getRuntime();

        // It is important to break up the command into a String[] array
        //  Process proc = runtime.exec(new String[] {"/bin/rm -f", srcdir.toString() + fileName, newdir.toString()});

        Process proc = runtime.exec(new String[] { SanConstants.sanRemove, SanConstants.sanRemoveOption,
                srcdir.toString() + fileName });

        // Very important to check errors returned by the process as
        // the java program will not print out the error that is output by
        // the child process unless you do this
        InputStream stdin = proc.getErrorStream();
        InputStreamReader isr = new InputStreamReader(stdin);
        BufferedReader br = new BufferedReader(isr);
        String line = null;
        while ((line = br.readLine()) != null)
            throw new SanException("error " + line);
    } catch (Exception e) {
        throw new SanException("deleteAll() using sanConstants.sanRemove, error " + e.getMessage());
    }
}

From source file:com.loy.MicroServiceConsole.java

@SuppressWarnings("rawtypes")
static void init() {

    ClassPathResource classPathResource = new ClassPathResource("application.yml");
    Yaml yaml = new Yaml();
    Map result = null;// ww w. j a  v  a 2s  .c o  m
    try {
        result = (Map) yaml.load(classPathResource.getInputStream());
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    String platformStr = result.get("platform").toString();
    String version = result.get("version").toString();
    String jvmOption = result.get("jvmOption").toString();
    @SuppressWarnings("unchecked")
    List<String> projects = (List<String>) result.get("projects");
    platform = Platform.valueOf(platformStr);

    final Runtime runtime = Runtime.getRuntime();
    File pidsForder = new File("./pids");
    if (!pidsForder.exists()) {
        pidsForder.mkdir();
    } else {
        File[] files = pidsForder.listFiles();
        if (files != null) {
            for (File f : files) {
                f.deleteOnExit();
                String pidStr = f.getName();
                try {
                    Long pid = new Long(pidStr);
                    if (Processes.isProcessRunning(platform, pid)) {
                        if (Platform.Windows == platform) {
                            Processes.tryKillProcess(null, platform, new NullProcessor(), pid);
                        } else {
                            Processes.killProcess(null, platform, new NullProcessor(), pid);
                        }

                    }
                } catch (Exception ex) {
                }
            }
        }
    }

    File currentForder = new File("");
    String root = currentForder.getAbsolutePath();
    root = root.replace(File.separator + "build" + File.separator + "libs", "");
    root = root.replace(File.separator + "e-example-ms-start", "");
    final String rootPath = root;
    new Thread(new Runnable() {
        @Override
        public void run() {
            int size = projects.size();
            int index = 1;
            for (String value : projects) {
                String path = value;
                String[] values = value.split("/");
                value = values[values.length - 1];
                value = rootPath + "/" + path + "/build/libs/" + value + "-" + version + ".jar";
                final String command = value;
                try {
                    Process process = runtime
                            .exec("java " + jvmOption + " -Dfile.encoding=UTF-8 -jar " + command);
                    Long pid = Processes.processId(process);
                    pids.add(pid);
                    File pidsFile = new File("./pids", pid.toString());
                    pidsFile.createNewFile();
                    new WriteLogThread(process.getInputStream()).start();

                } catch (IOException e) {
                    e.printStackTrace();
                }
                synchronized (lock) {
                    try {
                        if (index < size) {
                            lock.wait();
                        } else {
                            index++;
                        }

                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }).start();
}