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:com.redpill_linpro.libreoffice.LibreOfficeLauncherWindowsImpl.java

@Override
public void launchLibreOffice(String cmisUrl, String repositoryId, String filePath, String webdavUrl) {
    Runtime rt = Runtime.getRuntime();
    try {/*from  w w w .j ava  2  s  .co  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 = { "start soffice.exe" };

            for (int i = 0; i < binaryLocations.length; i++) {
                cmd.append((i == 0 ? "" : " || ") + binaryLocations[i] + " \"" + params + "\" ");
            }

            System.out.println("Command: cmd.exe /C " + cmd);

            rt.exec(new String[] { "cmd.exe", "/C", cmd.toString() });

            System.out.println("Process started");
        } catch (IOException e) {
            JOptionPane.showMessageDialog(null,
                    "Failed to start LibreOffice, commandline: " + cmd.toString() + "" + e.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.lenox.common.exec.ManagedProcess.java

public void startWithThread() throws IOException, InterruptedException {

    StringBuilder builder = new StringBuilder();
    for (String arg : commandLine.getArguments()) {
        if (builder.length() > 0) {
            builder.append(" ");
        }//  www . j a v a 2 s .  c o m
        builder.append(arg);
    }

    String args = builder.toString().replaceAll("\"", "");
    try {
        Runtime runtime = Runtime.getRuntime();

        if (workingDir == null) {
            logger.debug("Starting Process with no working dir : {} ",
                    commandLine.getExecutable() + " " + args);
            argsAsString = commandLine.getExecutable() + " " + args;
            process = runtime.exec(argsAsString);
            logger.debug("Started Process with no working dir : {} ", commandLine.getExecutable() + " " + args);
        } else {
            try {
                logger.debug("Changing permissions on process with  working dir : {} ",
                        workingDir.getAbsolutePath() + File.separator + commandLine.getExecutable());
                runtime.exec("chmod +rx " + workingDir.getAbsolutePath() + File.separator
                        + commandLine.getExecutable());
            } catch (Exception e) {
                logger.error("Error changing permissions on process : ", e);
                throw e;
            }

            try {
                logger.debug("Starting Process with  working dir : {}",
                        commandLine.getExecutable() + " " + args);
                process = runtime.exec(commandLine.getExecutable() + " " + args, null, workingDir);
            } catch (Exception e) {
                logger.error("Error starting process with working dir : ", e);
                throw e;
            }
            logger.debug("Started Process: {} ",
                    workingDir.getAbsolutePath() + File.separator + commandLine.getExecutable());
        }
    } catch (Exception e) {
        logger.error("Error starting process : ", e);
        throw e;
    }
}

From source file:org.kchine.rpf.PoolUtils.java

public static String currentWinProcessID() throws Exception {

    String pslistpath = System.getProperty("java.io.tmpdir") + "/rpf/WinTools/" + "ps.exe";
    System.out.println(pslistpath);
    File pslistFile = new File(pslistpath);
    if (!pslistFile.exists()) {
        pslistFile.getParentFile().mkdirs();
        InputStream is = PoolUtils.class.getResourceAsStream("/wintools/ps.exe");
        RandomAccessFile raf = new RandomAccessFile(pslistFile, "rw");
        raf.setLength(0);// ww  w  .  j a va  2 s  .c  o  m
        int b;
        while ((b = is.read()) != -1)
            raf.write((byte) b);
        raf.close();
    }
    String[] command = new String[] { pslistpath };
    Runtime rt = Runtime.getRuntime();
    final Process proc = rt.exec(command);
    final StringBuffer psPrint = new StringBuffer();
    final StringBuffer psError = new StringBuffer();
    new Thread(new Runnable() {
        public void run() {
            try {
                InputStream is = proc.getInputStream();
                int b;
                while ((b = is.read()) != -1) {
                    psPrint.append((char) b);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }).start();
    new Thread(new Runnable() {
        public void run() {
            try {
                InputStream is = proc.getErrorStream();
                int b;
                while ((b = is.read()) != -1) {
                    psError.append((char) b);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }).start();

    int exitVal = proc.waitFor();
    if (exitVal != 0)
        throw new Exception("ps exit code : " + exitVal);

    BufferedReader reader = new BufferedReader(new StringReader(psPrint.toString()));
    String line;
    int i = 0;
    while (!(line = reader.readLine()).startsWith("PID  PPID  THR PR NAME"))
        ++i;
    ++i;
    while ((line = reader.readLine()) != null) {
        StringTokenizer st = new StringTokenizer(line, " ");
        st.nextElement();
        String PPID = (String) st.nextElement();
        st.nextElement();
        st.nextElement();
        if (line.endsWith("\\ps.exe"))
            return PPID;
        ++i;
    }
    return null;
}

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

/**
 * Creates execScript which will be only executed on the EC2 instance to
 * install the base environment to use and install the bibiserv-clone. It
 * also installs the parsed tool on the BiBiServ.
 *
 * @param execScript//from w w w  . ja v  a  2s  .c  o  m
 */
private void createExecScript(final File execScript) {
    // e.g. toolID = 'dialign'
    Thread execScriptCreatorThread = new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                try (BufferedWriter output = new BufferedWriter(new FileWriter(execScript))) {
                    output.write("#!/bin/bash \n");

                    output.write("#if run as early shell script we have to set some things manually \n");
                    output.write("export SGE_ROOT=/var/lib/gridengine \n");

                    output.write("# change into instantbibi base dir \n");
                    output.write("cd /home/ubuntu/instantbibi \n");

                    output.write("# init .antlibs \n");
                    output.write("/usr/bin/ant install.antlib \n");

                    output.write("# check for updates \n");
                    output.write("/usr/bin/ant .get \n");

                    output.write("# setup and configure domain, deploy bibimainapp \n");
                    output.write("mkdir -p /vol/spool/bibiserv \n");
                    output.write(
                            "/usr/bin/ant -Dbase.dir=/vol/spool/bibiserv -Dglassfish4=true -Duse.min.module.set=true -Denable.docker=true -Dconfig.64=true -Dconfig.oge=true -Ddrmaa.jar=/usr/share/java/drmaa.jar -Ddrmaa.library.path=/usr/lib/ instant \n");

                    output.write("# deploy application \n");
                    // parsd toolID
                    output.write("/usr/bin/ant deploy.app -Dapp=" + toolID + "\n");

                    output.write("# finished");
                    output.write("/usr/bin/date");
                    output.close();
                }

                Runtime r = Runtime.getRuntime();
                /**
                 * Modify Script to be executeable.
                 */
                r.exec("chmod u+x " + execScript.getAbsolutePath());
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }
    });
    execScriptCreatorThread.start();
}

From source file:org.pentaho.di.trans.steps.monetdbbulkloader.MonetDBBulkLoader.java

protected ProcessHolder startMClient(Runtime rt, String command) {
    ProcessHolder holder = new ProcessHolder();
    holder.isRunning = true;/*  w  w w.  j  a v a2s .c  om*/
    try {

        holder.process = rt.exec(command);
        holder.stdIn = holder.process.getOutputStream();
        holder.stdOut = holder.process.getInputStream();
        holder.stdErr = holder.process.getErrorStream();

        try {
            int exitValue = holder.process.exitValue();
            // if we get here, mclient has terminated
            byte buffer[] = new byte[4096];
            holder.stdErr.read(buffer);
            holder.message = new String(buffer);
            holder.isRunning = false;
        } catch (Exception e) {
            // mclient is still running, this is a good thing
        }
    } catch (Exception e) {
        log.logError("Could not execute MonetDB mclient command: " + command);
    }
    return holder;
}

From source file:org.sipfoundry.sipxconfig.admin.CertificateManagerImpl.java

public void importKeyAndCertificate(String server, boolean isCsrBased) {
    File newCertificate = isCsrBased ? getCRTFile(server) : getExternalCRTFile();
    if (!newCertificate.exists()) {
        throw new UserException(ERROR_VALID);
    }/*from   w w  w. j a v a2  s  .c  o m*/

    File newKey = isCsrBased ? getKeyFile(server) : getExternalKeyFile();
    if (!newKey.exists()) {
        throw new UserException(ERROR_VALID);
    }

    if (!validateCertificate(newCertificate)) {
        throw new UserException(ERROR_VALID);
    }

    File oldCertificate = new File(m_sslDirectory, "ssl-web.crt");
    File oldKey = new File(m_sslDirectory, "ssl-web.key");

    File backupCertificate = new File(m_sslDirectory, "ssl-web.oldcrt");
    File backupKey = new File(m_sslDirectory, "ssl-web.oldkey");

    try {
        if (isCsrBased) {
            Runtime runtime = Runtime.getRuntime();
            String[] cmdLine = new String[] { m_binCertDirectory + GEN_SSL_KEYS_SH, WORKDIR_FLAG,
                    m_certDirectory, "--pkcs", WEB_ONLY, DEFAULTS_FLAG, PARAMETERS_FLAG, PROPERTIES_FILE, };
            Process proc = runtime.exec(cmdLine);
            LOG.debug(RUNNING + StringUtils.join(cmdLine, BLANK));
            proc.waitFor();
            if (proc.exitValue() != 0) {
                throw new UserException(SCRIPT_ERROR, SCRIPT_EXCEPTION_MESSAGE + proc.exitValue());
            }
        }

        FileUtils.copyFile(oldCertificate, backupCertificate);
        FileUtils.copyFile(oldKey, backupKey);

        FileUtils.copyFile(newCertificate, oldCertificate);
        FileUtils.copyFile(newKey, oldKey);
    } catch (Exception ex) {
        throw new UserException(ERROR_MSG_COPY);
    }

    try {
        generateKeyStores();
    } catch (UserException userException) {
        try {
            FileUtils.copyFile(backupCertificate, oldCertificate);
            FileUtils.copyFile(backupKey, oldKey);

            backupCertificate.delete();
            backupKey.delete();

        } catch (Exception ex) {
            throw new UserException(ERROR_MSG_COPY);
        }

        throw userException;
    }

    backupCertificate.delete();
    backupKey.delete();
}

From source file:it.illinois.adsc.ema.softgrid.monitoring.ui.SPMainFrame.java

public Process startPythonThread(String batfilePath) throws Exception {

    File file = new File("state.file");
    file.createNewFile();//  ww w .ja  v a  2  s .  c  o  m
    try {
        ClassLoader cl = ClassLoader.getSystemClassLoader();
        URL[] urls = ((URLClassLoader) cl).getURLs();
        for (URL url : urls) {
            System.out.println(url.getFile());
        }

        Runtime runTime = Runtime.getRuntime();
        pythonProcess = runTime.exec("cmd.exe /k " + batfilePath);
        InputStream inputStream = pythonProcess.getInputStream();
        InputStreamReader isr = new InputStreamReader(inputStream);
        BufferedReader reader = new BufferedReader(isr);
        InputStream errorStream = pythonProcess.getErrorStream();
        InputStreamReader esr = new InputStreamReader(errorStream);

        String n1 = "";
        StringBuffer standardOutput = new StringBuffer();
        while ((n1 = reader.readLine()) != null) {
            System.out.println(n1);
        }
        //          System.out.println("Standard Output: " + standardOutput.toString());
        int n2;
        char[] c2 = new char[1024];
        StringBuffer standardError = new StringBuffer();
        while ((n2 = esr.read(c2)) > 0) {
            standardError.append(c2, 0, n2);
        }
        System.out.println("Standard Error: " + standardError.toString());
        return pythonProcess;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:it.iit.genomics.cru.bridges.liftover.ws.LiftOverRun.java

public static Mapping runLiftOver(String genome, String fromAssembly, String toAssembly, String chromosome,
        int start, int end) {

    String liftOverCommand = RESOURCE_BUNDLE.getString("liftOverCommand");

    String liftOverPath = RESOURCE_BUNDLE.getString("liftOverPath");

    String mapChainDir = RESOURCE_BUNDLE.getString("mapChainDir");

    String tmpDir = RESOURCE_BUNDLE.getString("tmpDir");

    Mapping mapping = null;/*from  w ww  .j  a v  a  2s.  c  om*/

    Runtime r = Runtime.getRuntime();

    String rootFilename = String.format("%s", RandomStringUtils.randomAlphanumeric(8));

    String inputFilename = rootFilename + "-" + fromAssembly + ".bed";
    String outputFilename = rootFilename + "-" + toAssembly + ".bed";
    String unmappedFilename = rootFilename + "-" + "unmapped.bed";

    String mapChain = fromAssembly.toLowerCase() + "To" + toAssembly.toUpperCase().charAt(0)
            + toAssembly.toLowerCase().substring(1) + ".over.chain.gz";

    try {

        File tmpDirFile = new File(tmpDir);

        // if the directory does not exist, create it
        if (false == tmpDirFile.exists()) {
            System.out.println("creating directory: " + tmpDir);
            boolean result = tmpDirFile.mkdir();

            if (result) {
                System.out.println("DIR created");
            }
        }

        // Write input bed file
        File inputFile = new File(tmpDir + inputFilename);
        // if file doesnt exists, then create it
        if (!inputFile.exists()) {
            inputFile.createNewFile();
        }

        FileWriter fw = new FileWriter(inputFile.getAbsoluteFile());
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write(chromosome + "\t" + start + "\t" + end + "\n");
        bw.close();

        String commandArgs = String.format("%s %s %s %s %s", liftOverPath + "/" + liftOverCommand,
                tmpDir + inputFilename, mapChainDir + mapChain, tmpDir + outputFilename,
                tmpDir + unmappedFilename);
        System.out.println(commandArgs);

        Process p = r.exec(commandArgs);

        p.waitFor();

        BufferedReader b = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line = "";

        while ((line = b.readLine()) != null) {
            System.out.println(line);
        }
        b.close();

        b = new BufferedReader(new FileReader(tmpDir + outputFilename));

        while ((line = b.readLine()) != null) {
            String[] cells = line.split("\t");
            String newChromosome = cells[0];
            int newStart = Integer.parseInt(cells[1]);
            int newEnd = Integer.parseInt(cells[2]);
            mapping = new Mapping(genome, toAssembly, newChromosome, newStart, newEnd);
        }
        b.close();

        // delete
        File delete = new File(tmpDir + inputFilename);
        delete.delete();

        delete = new File(tmpDir + outputFilename);
        delete.delete();

        delete = new File(tmpDir + unmappedFilename);
        delete.delete();

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InterruptedException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    return mapping;
}

From source file:fr.inria.oak.paxquery.common.xml.navigation.NavigationTreePattern.java

/**
 * Method that creates an image representation of the pattern and stores it to a file
 * @param givenFilename the name of the file where the image will be saved
 * @param query true if the pattern that we want to draw is a query or false otherwise.
 * Query nodes will be filled in yellow and view nodes will be filled in blue
 *//*w ww.  jav a2  s . c o  m*/
public void draw(String imagesPath, String givenFilename, boolean query, String backgroundColor,
        String foregroundColor) {
    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;
    }

    String sb = getDotString(fileName, backgroundColor, foregroundColor);

    try {
        String fileNameDot = new String(fileName + ".dot");
        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:eu.planets_project.tb.gui.backing.admin.wsclient.faces.WSClientBean.java

/**
 * runs the WSI Check using the official WS-I Testing Tool (and runs
 * this tool via Runtime.exec(..))/*  w w w.j ava  2  s  .  c  o  m*/
 * @param configFile - the path to the confguration file used by the 
 *                     official WS-I Testing Tool
 */
private void runWSICheck(String configFile) {
    String[] args;
    log.debug("WSI_HOME = " + System.getenv("WSI_HOME"));
    log.debug("os.name = " + System.getProperty("os.name"));
    if (System.getProperty("os.name").contains("indows")) {
        args = new String[5];
        args[0] = "cmd.exe";
        args[1] = "/C";
        args[2] = "%WSI_HOME%/java/bin/Analyzer.bat";
        args[3] = "-config";
        args[4] = configFile;
    } else {
        args = new String[4];
        args[0] = "sh";
        //args[1] = "-c";
        //args[1] = "$WSI_HOME/java/bin/Analyzer.sh";
        args[1] = System.getenv("WSI_HOME") + "/java/bin/Analyzer.sh";
        args[2] = "-config";
        args[3] = configFile;
    }

    log.debug("Execution stmt: ");
    for (int i = 0; i < args.length; i++) {
        log.debug(args[i] + " ");
    }

    try {
        Runtime rt = Runtime.getRuntime();
        Process proc = rt.exec(args);
        StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR");
        StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT");
        errorGobbler.start();
        outputGobbler.start();

        try {
            if (proc.waitFor() != 0) {
                log.error("exit value = " + proc.exitValue());
            } else
                log.debug("Terminated gracefully");
        } catch (InterruptedException e) {
            log.error(e);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}