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, String[] envp) throws IOException 

Source Link

Document

Executes the specified command and arguments in a separate process with the specified environment.

Usage

From source file:org.smartfrog.avalanche.client.sf.apps.gt4.javawscore.DeployToTomcat.java

public void undeployFrmTomcat(String version, String webAppName) throws WSCoreException {
    String dirName = tomcatDirectory + File.separatorChar + "webapps" + File.separatorChar + webAppName;

    File dir = new File(dirName);
    if (!dir.exists()) {
        log.error("The directory " + dirName + " does not exist.");
        log.error("The webapp name " + webAppName + " is wrong or " + "it is not deployed");
        throw new WSCoreException("The webapp name " + webAppName + " is wrong or it is not deployed");
    }/*from ww w . j ava 2s  .  co m*/

    Runtime rt = Runtime.getRuntime();
    try {
        log.debug("Deleting the web application " + webAppName + " from Tomcat...");
        //Stop Tomcat
        String envp[] = { "JAVA_HOME=" + System.getProperty("java.home") };
        log.info("Shutting down Tomcat...");
        rt.exec(tomcatDirectory + File.separatorChar + "bin" + File.separatorChar + "shutdown.sh", envp);
        DiskUtils.forceDelete(dir);

        // clean xml files
        cleanXMLFiles(version);
        rt.exec(tomcatDirectory + File.separatorChar + "bin" + File.separatorChar + "startup.sh", envp);
        log.info("Started Tomcat....");
    } catch (IOException ioe) {
        log.error("Error in deleting directory " + dirName);
        log.error("Failed to undeploy " + webAppName);
        throw new WSCoreException(ioe.toString());
    }
    log.info("Successfully undeployed " + webAppName);
}

From source file:org.wso2.carbon.registry.app.test.FileSystemImportExportTestCase.java

@Test(groups = { "wso2.greg" }, dependsOnMethods = { "FileImportTest" })
public void FileExportTest() throws RegistryException, FileNotFoundException {
    Process process;//w w w.  j  a va2 s  .  co  m
    Runtime runTime = Runtime.getRuntime();
    String fileExportPath = EXPORT_PATH + "/target/export";

    File file = new File(fileExportPath);
    String osName = "";
    try {
        osName = System.getProperty("os.name");
    } catch (Exception e) {
        log.error("Exception caught =" + e.getMessage());
    }

    if (osName.startsWith("Windows")) {
        try {
            process = runTime.exec("cmd.exe /C" + "" + "mkdir" + "" + fileExportPath, null);
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else {
        try {
            process = runTime.exec("mkdir" + " " + fileExportPath, null);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    RegistryClientUtils.exportFromRegistry(file, "/framework/", registry);

    File f = new File(fileExportPath + "/apptestresources/mssql.sql");
    assertTrue(f.exists(), "File doesn't exist at the location");

    File f1 = new File(fileExportPath + "/apptestresources/mysql.sql");
    assertTrue(f1.exists(), "File doesn't exist at the location");

    assertTrue(fileContainString(fileExportPath + "/apptestresources/oracle.sql", "CREATE"),
            "Resource contain not found");
    assertTrue(fileContainString(fileExportPath + "/apptestresources/mssql.sql", "CREATE"),
            "Resource contain not found");

    if (osName.startsWith("Windows")) {
        try {
            process = runTime.exec("cmd.exe /C" + "" + "del" + "" + fileExportPath, null);
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else {
        try {
            process = runTime.exec("rm -rf" + " " + fileExportPath, null);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:io.fabric8.elasticsearch.ElasticsearchIntegrationTest.java

protected void seedSearchGuardAcls() throws Exception {
    log.info("Starting seeding of SearchGuard ACLs...");
    String configdir = basedir + "/src/it/resources/sgconfig";
    String[] cmd = { basedir + "/tools/sgadmin.sh", "-cd", configdir, "-ks", keystore, "-kst", "JKS", "-kspass",
            password, "-ts", truststore, "-tst", "JKS", "-tspass", password, "-nhnv", "-nrhn", "-icl" };
    String[] envvars = { "CONFIG_DIR=" + configdir,
            "SCRIPT_CP=" + System.getProperty("surefire.test.class.path") };
    log.debug("Seeding ACLS with: {}, {}", cmd, envvars);
    Runtime rt = Runtime.getRuntime();
    Process process = rt.exec(cmd, envvars);
    if (0 != process.waitFor()) {
        log.error("Stdout of seeding SearchGuard ACLs:\n{}", IOUtils.toString(process.getInputStream()));
        fail("Error seeding SearchGuard ACLs:\n{}" + IOUtils.toString(process.getErrorStream()));
    } else {//from   w w w  .  j  a v a 2 s .co m
        log.debug("Stdout of seeding SearchGuard ACLs:\n{}", IOUtils.toString(process.getInputStream()));
    }
    log.info("Completed seeding SearchGuard ACL");
}

From source file:plugin.games.data.trans.step.fileoutput.TextFileOutput.java

public void openNewFile(String baseFilename) throws KettleException {
    if (baseFilename == null) {
        throw new KettleFileException(BaseMessages.getString(PKG, "TextFileOutput.Exception.FileNameNotSet")); //$NON-NLS-1$
    }/*from ww w . j a  v a  2  s  .c o m*/

    data.writer = null;

    ResultFile resultFile = null;

    String filename = buildFilename(environmentSubstitute(baseFilename), true);

    try {
        if (meta.isServletOutput()) {
            Writer writer = getTrans().getServletPrintWriter();
            if (Const.isEmpty(meta.getEncoding())) {
                data.writer = new WriterOutputStream(writer);
            } else {
                data.writer = new WriterOutputStream(writer, meta.getEncoding());
            }

        } else if (meta.isFileAsCommand()) {
            if (log.isDebug())
                logDebug("Spawning external process");
            if (data.cmdProc != null) {
                logError("Previous command not correctly terminated");
                setErrors(1);
            }
            String cmdstr = environmentSubstitute(meta.getFileName());
            if (Const.getOS().equals("Windows 95")) {
                cmdstr = "command.com /C " + cmdstr;
            } else {
                if (Const.getOS().startsWith("Windows")) {
                    cmdstr = "cmd.exe /C " + cmdstr;
                }
            }
            if (isDetailed())
                logDetailed("Starting: " + cmdstr);
            Runtime r = Runtime.getRuntime();
            data.cmdProc = r.exec(cmdstr, EnvUtil.getEnvironmentVariablesForRuntimeExec());
            data.writer = data.cmdProc.getOutputStream();
            StreamLogger stdoutLogger = new StreamLogger(log, data.cmdProc.getInputStream(), "(stdout)");
            StreamLogger stderrLogger = new StreamLogger(log, data.cmdProc.getErrorStream(), "(stderr)");
            new Thread(stdoutLogger).start();
            new Thread(stderrLogger).start();
        } else {

            // Check for parent folder
            createParentFolder(filename);

            // Add this to the result file names...
            resultFile = new ResultFile(ResultFile.FILE_TYPE_GENERAL,
                    KettleVFS.getFileObject(filename, getTransMeta()), getTransMeta().getName(), getStepname());
            resultFile.setComment("This file was created with a text file output step");
            addResultFile(resultFile);

            OutputStream outputStream;

            if (!Const.isEmpty(meta.getFileCompression())
                    && !meta.getFileCompression().equals(FILE_COMPRESSION_TYPE_NONE)) {
                if (meta.getFileCompression().equals(FILE_COMPRESSION_TYPE_ZIP)) {
                    if (log.isDetailed())
                        logDetailed("Opening output stream in zipped mode");

                    if (checkPreviouslyOpened(filename)) {
                        data.fos = KettleVFS.getOutputStream(filename, getTransMeta(), true);
                    } else {
                        data.fos = KettleVFS.getOutputStream(filename, getTransMeta(), meta.isFileAppended());
                    }
                    data.zip = new ZipOutputStream(data.fos);
                    File entry = new File(filename);
                    ZipEntry zipentry = new ZipEntry(entry.getName());
                    zipentry.setComment("Compressed by Kettle");
                    data.zip.putNextEntry(zipentry);
                    outputStream = data.zip;
                } else if (meta.getFileCompression().equals(FILE_COMPRESSION_TYPE_GZIP)) {
                    if (log.isDetailed())
                        logDetailed("Opening output stream in gzipped mode");
                    if (checkPreviouslyOpened(filename)) {
                        data.fos = KettleVFS.getOutputStream(filename, getTransMeta(), true);
                    } else {
                        data.fos = KettleVFS.getOutputStream(filename, getTransMeta(), meta.isFileAppended());
                    }
                    data.gzip = new GZIPOutputStream(data.fos);
                    outputStream = data.gzip;
                } else {
                    throw new KettleFileException("No compression method specified!");
                }
            } else {
                if (log.isDetailed())
                    logDetailed("Opening output stream in nocompress mode");
                if (checkPreviouslyOpened(filename)) {
                    data.fos = KettleVFS.getOutputStream(filename, getTransMeta(), true);
                } else {
                    data.fos = KettleVFS.getOutputStream(filename, getTransMeta(), meta.isFileAppended());
                }
                outputStream = data.fos;
            }

            if (!Const.isEmpty(meta.getEncoding())) {
                if (log.isDetailed())
                    logDetailed("Opening output stream in encoding: " + meta.getEncoding());
                data.writer = new BufferedOutputStream(outputStream, 5000);
            } else {
                if (log.isDetailed())
                    logDetailed("Opening output stream in default encoding");
                data.writer = new BufferedOutputStream(outputStream, 5000);
            }

            if (log.isDetailed())
                logDetailed("Opened new file with name [" + filename + "]");
        }
    } catch (Exception e) {
        throw new KettleException("Error opening new file : " + e.toString());
    }
    // System.out.println("end of newFile(), splitnr="+splitnr);

    data.splitnr++;

    if (resultFile != null && meta.isAddToResultFiles()) {
        // Add this to the result file names...
        addResultFile(resultFile);
    }
}

From source file:org.pentaho.di.trans.steps.textfileoutput.TextFileOutput.java

public void openNewFile(String baseFilename) throws KettleException {
    if (baseFilename == null) {
        throw new KettleFileException(BaseMessages.getString(PKG, "TextFileOutput.Exception.FileNameNotSet"));
    }// w w  w. j  a v  a2 s  . c om

    data.writer = null;

    String filename = buildFilename(environmentSubstitute(baseFilename), true);

    try {
        if (meta.isServletOutput()) {
            Writer writer = getTrans().getServletPrintWriter();
            if (Const.isEmpty(meta.getEncoding())) {
                data.writer = new WriterOutputStream(writer);
            } else {
                data.writer = new WriterOutputStream(writer, meta.getEncoding());
            }

        } else if (meta.isFileAsCommand()) {
            if (log.isDebug()) {
                logDebug("Spawning external process");
            }
            if (data.cmdProc != null) {
                logError("Previous command not correctly terminated");
                setErrors(1);
            }
            String cmdstr = environmentSubstitute(meta.getFileName());
            if (Const.getOS().equals("Windows 95")) {
                cmdstr = "command.com /C " + cmdstr;
            } else {
                if (Const.getOS().startsWith("Windows")) {
                    cmdstr = "cmd.exe /C " + cmdstr;
                }
            }
            if (isDetailed()) {
                logDetailed("Starting: " + cmdstr);
            }
            Runtime r = Runtime.getRuntime();
            data.cmdProc = r.exec(cmdstr, EnvUtil.getEnvironmentVariablesForRuntimeExec());
            data.writer = data.cmdProc.getOutputStream();
            StreamLogger stdoutLogger = new StreamLogger(log, data.cmdProc.getInputStream(), "(stdout)");
            StreamLogger stderrLogger = new StreamLogger(log, data.cmdProc.getErrorStream(), "(stderr)");
            new Thread(stdoutLogger).start();
            new Thread(stderrLogger).start();
        } else {

            // Check for parent folder creation only if the user asks for it
            //
            if (meta.isCreateParentFolder()) {
                createParentFolder(filename);
            }

            String compressionType = meta.getFileCompression();

            // If no file compression is specified, use the "None" provider
            if (Const.isEmpty(compressionType)) {
                compressionType = FILE_COMPRESSION_TYPE_NONE;
            }

            CompressionProvider compressionProvider = CompressionProviderFactory.getInstance()
                    .getCompressionProviderByName(compressionType);

            if (compressionProvider == null) {
                throw new KettleException("No compression provider found with name = " + compressionType);
            }

            if (!compressionProvider.supportsOutput()) {
                throw new KettleException(
                        "Compression provider " + compressionType + " does not support output streams!");
            }

            if (log.isDetailed()) {
                logDetailed("Opening output stream using provider: " + compressionProvider.getName());
            }

            if (checkPreviouslyOpened(filename)) {
                data.fos = getOutputStream(filename, getTransMeta(), true);
            } else {
                data.fos = getOutputStream(filename, getTransMeta(), meta.isFileAppended());
            }

            data.out = compressionProvider.createOutputStream(data.fos);

            // The compression output stream may also archive entries. For this we create the filename
            // (with appropriate extension) and add it as an entry to the output stream. For providers
            // that do not archive entries, they should use the default no-op implementation.
            data.out.addEntry(filename + "." + meta.getExtension());

            if (!Const.isEmpty(meta.getEncoding())) {
                if (log.isDetailed()) {
                    logDetailed("Opening output stream in encoding: " + meta.getEncoding());
                }
                data.writer = new BufferedOutputStream(data.out, 5000);
            } else {
                if (log.isDetailed()) {
                    logDetailed("Opening output stream in default encoding");
                }
                data.writer = new BufferedOutputStream(data.out, 5000);
            }

            if (log.isDetailed()) {
                logDetailed("Opened new file with name [" + filename + "]");
            }
        }
    } catch (Exception e) {
        throw new KettleException("Error opening new file : " + e.toString());
    }

    data.splitnr++;

    if (meta.isAddToResultFiles()) {
        // Add this to the result file names...
        ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_GENERAL,
                getFileObject(filename, getTransMeta()), getTransMeta().getName(), getStepname());
        if (resultFile != null) {
            resultFile.setComment(BaseMessages.getString(PKG, "TextFileOutput.AddResultFile"));
            addResultFile(resultFile);
        }
    }
}

From source file:TestFuseDFS.java

/**
 * Run a fuse-dfs process to mount the given DFS
 *///from ww  w.j  a va 2 s.  c o  m
private static Process establishMount(URI uri) throws IOException {
    Runtime r = Runtime.getRuntime();
    String cp = System.getProperty("java.class.path");

    String buildTestDir = System.getProperty("build.test");
    String fuseCmd = buildTestDir + "/../fuse_dfs";
    String libHdfs = buildTestDir + "/../../../c++/lib";

    String arch = System.getProperty("os.arch");
    String jvm = System.getProperty("java.home") + "/lib/" + arch + "/server";
    String lp = System.getProperty("LD_LIBRARY_PATH") + ":" + libHdfs + ":" + jvm;
    LOG.debug("LD_LIBRARY_PATH=" + lp);

    String nameNode = "dfs://" + uri.getHost() + ":" + String.valueOf(uri.getPort());

    // NB: We're mounting via an unprivileged user, therefore
    // user_allow_other needs to be set in /etc/fuse.conf, which also
    // needs to be world readable.
    String mountCmd[] = { fuseCmd, nameNode, mountPoint,
            // "-odebug",              // Don't daemonize
            "-obig_writes", // Allow >4kb writes
            "-oentry_timeout=0.1", // Don't cache dents long
            "-oattribute_timeout=0.1", // Don't cache attributes long
            "-ononempty", // Don't complain about junk in mount point
            "-f", // Don't background the process
            "-ordbuffer=32768", // Read buffer size in kb
            "rw" };

    String[] env = { "CLASSPATH=" + cp, "LD_LIBRARY_PATH=" + lp, "PATH=/usr/bin:/bin" };

    execWaitRet("fusermount -u " + mountPoint);
    execAssertSucceeds("rm -rf " + mountPoint);
    execAssertSucceeds("mkdir -p " + mountPoint);

    // Mount the mini cluster
    String cmdStr = "";
    for (String c : mountCmd) {
        cmdStr += (" " + c);
    }
    LOG.info("now mounting with:" + cmdStr);
    Process fuseProcess = r.exec(mountCmd, env);
    RedirectToStdoutThread stdoutThread = new RedirectToStdoutThread(fuseProcess.getInputStream());
    RedirectToStdoutThread stderrThread = new RedirectToStdoutThread(fuseProcess.getErrorStream());
    stdoutThread.start();
    stderrThread.start();
    // Wait for fusermount to start up, so that we know we're operating on the
    // FUSE FS when we run the tests.
    try {
        Thread.sleep(50000);
    } catch (InterruptedException e) {
    }
    return fuseProcess;
}

From source file:org.smartfrog.avalanche.client.sf.apps.gt4.security.GridSecurity.java

public String getUserSubject(String certFilePath) throws GT4SecurityException {
    String subject = null;//from  w  w w .  java  2s . co m

    Runtime rt = Runtime.getRuntime();
    String cmd = globusLoc + File.separatorChar + "bin" + File.separatorChar + "grid-cert-info";
    //cmd = cmd + " -subject -file " + userCert;
    cmd = cmd + " -subject -file " + certFilePath;

    //File uCert = new File(userCert);
    File uCert = new File(certFilePath);
    if (!uCert.exists()) {
        log.error("Cannot get user subject... " + certFilePath + " does not exist");
        throw new GT4SecurityException("Cannot get user subject... " + certFilePath + " does not exist");
    }
    if (!uCert.canRead()) {
        log.error("Cannot get user subject... " + certFilePath + " does not have read permissions");
        throw new GT4SecurityException(
                "Cannot get user subject... " + certFilePath + " does not have read permissions");
    }

    Process p;
    BufferedReader cmdError = null;
    BufferedReader cmdOutput = null;
    int exitVal = 0;
    try {
        p = rt.exec(cmd, new String[] { "GLOBUS_LOCATION=" + globusLoc });
        cmdOutput = new BufferedReader(new InputStreamReader(p.getInputStream()));
        cmdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
        exitVal = p.waitFor();

        if (exitVal != 0) {
            log.error("Error in getting user subject");
            String err = "Error in getting user subject";
            String line = null;
            while ((line = cmdError.readLine()) != null) {
                err = err + line;
            }
            throw new GT4SecurityException(err);
        }

        subject = cmdOutput.readLine();
    } catch (IOException ioe) {
        log.error("Error in getting user subject", ioe);
        throw new GT4SecurityException("Error in getting user subject", ioe);
    } catch (InterruptedException ie) {
        log.error("Error in getting user subject", ie);
        throw new GT4SecurityException("Error in getting user subject", ie);
    }

    if (null == subject) {
        log.error("Error in getting user subject.... " + " User subject is null");
        throw new GT4SecurityException("Error in getting user subject.... " + " User subject is null");
    }

    return subject;

}