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:nl.nn.adapterframework.extensions.rekenbox.RekenBoxCaller.java

/**
 * positie 1 t/m 8 bepalen de naam van de executable, of tot aan de ':' (wat het eerst komt)
 *//*from  www.  ja  va2  s.co  m*/
public PipeRunResult doPipe(Object input, IPipeLineSession session) throws PipeRunException {
    if (!(input instanceof String))
        throw new PipeRunException(this, getLogPrefix(session) + "expected java.lang.String, got ["
                + input.getClass().getName() + "], value [" + input + "]");
    String sInput = (String) input;
    //   log.debug("Pipe ["+name+"] got input ["+sInput+"]");

    String rekenboxName = getRekenBoxName();
    if (StringUtils.isEmpty(rekenboxName)) {
        rekenboxName = sInput;
        if (rekenboxName.length() >= 8)
            rekenboxName = rekenboxName.substring(0, 8);
        // find end or position of first colon.
        rekenboxName = (rekenboxName + ":").substring(0, (rekenboxName + ":").indexOf(":")).trim();
    }

    if (rekenboxName.equals("")) {
        throw new PipeRunException(this,
                getLogPrefix(session) + "cannot determine rekenboxName from [" + sInput + "]");
    }

    int i = rekenboxName.length();
    int n = sInput.length();
    while (i < n && " :;".indexOf(sInput.charAt(i)) >= 0) {
        i++;
    }
    String rekenboxInput = sInput.substring(i);

    String exeName = runPath + rekenboxName + "." + executableExtension;
    if (!(new File(exeName).exists())) {
        throw new PipeRunException(this, getLogPrefix(session) + "executable file [" + exeName
                + "] does not exist; requestmessage: [" + sInput + "]");
    }

    if (getRekenboxSessionKey() != null) {
        session.put(getRekenboxSessionKey(), rekenboxName);
    }

    String baseFileName = getBaseFileName();
    String inputFileName = inputOutputDirectory + baseFileName + ".INV";
    String outputFileName = inputOutputDirectory + baseFileName + ".UIT";

    String callAndArgs;
    String callType = getCommandLineType();
    if ((callType == null) || (callType.equals("switches"))) {
        callAndArgs = exeName + " /I" + inputFileName + " /U" + outputFileName + " /P" + templateDir;
    } else if (callType.equals("straight")) {
        callAndArgs = exeName + " " + inputFileName + " " + outputFileName + " " + templateDir;
    } else if (callType.equals("redirected")) {
        callAndArgs = exeName + " " + inputFileName + " " + templateDir;
    } else
        throw new PipeRunException(this, getLogPrefix(session) + "unknown commandLineType: " + callType);

    try {
        // put input in a file
        Misc.stringToFile(rekenboxInput, inputFileName);

        // precreating outputfile is necessary for L76HB000
        log.debug(getLogPrefix(session) + " precreating outputfile [" + outputFileName + "]");
        new File(outputFileName).createNewFile();

        log.debug(getLogPrefix(session) + " will issue command [" + callAndArgs + "]");

        // execute 
        Runtime rt = Runtime.getRuntime();

        Process child = rt.exec(callAndArgs);
        String result;

        if (callType.equals("redirected")) {
            result = Misc.streamToString(child.getInputStream(), "\n", true);

        } else {
            child.waitFor();

            // read output
            result = Misc.fileToString(outputFileName, "\n", true);
        }
        log.debug(getLogPrefix(session) + " completed call. Process exit code is: " + child.exitValue());

        //      log.debug("Pipe ["+name+"] retrieved result ["+result+"]");
        return new PipeRunResult(getForward(), result);

    } catch (Exception e) {
        throw new PipeRunException(this, getLogPrefix(session) + "got Exception executing rekenbox", e);
    } finally {
        // cleanup
        if (isCleanup()) {
            new File(inputFileName).delete();
            new File(outputFileName).delete();
        }
    }

}

From source file:com.netscape.cmstools.cli.CLI.java

public void runExternal(String[] command) throws CLIException, IOException, InterruptedException {

    if (verbose) {

        System.out.print("External command:");

        for (String c : command) {

            boolean quote = c.contains(" ");

            System.out.print(" ");

            if (quote)
                System.out.print("\"");
            System.out.print(c);/*  w  w w . j a v  a2s. c o m*/
            if (quote)
                System.out.print("\"");
        }

        System.out.println();
    }

    Runtime rt = Runtime.getRuntime();
    Process p = rt.exec(command);
    int rc = p.waitFor();

    if (rc != 0) {
        throw new CLIException("External command failed. RC: " + rc, rc);
    }
}

From source file:bdManager.DBConnectionManager.java

public String doDatabaseDump(String filePath) throws Exception {
    PrintWriter out = null;/*ww w  .  j a  v a2 s  .c  o  m*/
    Properties properties = new Properties();
    properties.load(new FileReader(data_location + "/db_config.properties"));

    //        String dumpCommand = "mysqldump  "
    //                + "--complete-insert --insert-ignore --force "
    //                + "--single-transaction --no-create-info --skip-comments "
    //                + "--user=" + properties.getProperty("username")
    //                + " --password=" + properties.getProperty("password")
    //                + " " + properties.getProperty("databasename");
    String dumpCommand = "mysqldump  " + " --host " + properties.getProperty("host")
            + " --complete-insert --insert-ignore --force"
            + " --single-transaction --add-drop-table --skip-comments" + " --user="
            + properties.getProperty("username") + " --password="
            + new String(Base64.decodeBase64(properties.getProperty("password"))) + " "
            + properties.getProperty("databasename");
    Runtime rt = Runtime.getRuntime();
    //        dumpCommand+= " >> " + filePath;
    //        System.out.println(dumpCommand);
    Process dumpProcess = rt.exec(dumpCommand);

    BufferedReader br = new BufferedReader(new InputStreamReader(dumpProcess.getInputStream()));
    String line = br.readLine();
    String output = "";
    // Mientras se haya leido alguna linea 
    while (line != null) {
        output += "\n" + line;
        line = br.readLine();
    }
    int exitCode = dumpProcess.waitFor();

    if (exitCode != 0) {
        throw new Exception("Failed while executing mysql dump commands. Error: " + output);
    }

    String fileHeader = "USE " + properties.getProperty("databasename") + ";";
    fileHeader += "\nSTART TRANSACTION;";
    fileHeader += "\nBEGIN;";
    fileHeader += "\n    set FOREIGN_KEY_CHECKS = 1;\n";

    String fileFooter = "\n    set FOREIGN_KEY_CHECKS = 0;";
    fileFooter += "\nCOMMIT;";

    out = new PrintWriter(new BufferedWriter(new FileWriter(filePath, true)));
    out.println(fileHeader);
    out.println(output);
    //        BufferedReader br = new BufferedReader(new InputStreamReader(dumpProcess.getInputStream()));
    //        String line = br.readLine();
    //        while (line != null) {
    //            out.println(line);
    //            line = br.readLine();
    //        }
    out.println(fileFooter);
    out.close();

    return filePath;
}

From source file:br.unb.cic.bionimbuz.services.storage.bucket.methods.CloudMethodsAmazonGoogle.java

@Override
public void CheckStorageLatency(BioBucket bucket) throws Exception {

    if (!bucket.isMounted()) {
        throw new Exception("Cant check latency! Bucket not mounted: " + bucket.getName());
    }//from   w w  w. j  a v a2 s.  c o  m

    float latency = 0;
    int i;

    for (i = 0; i < this.LATENCY_CHECKS; i++) {
        // Upload
        final String command = "/bin/dd if=/dev/zero of=" + bucket.getMountPoint() + "/pingfile-" + myId
                + " bs=64 count=1 oflag=dsync";

        final Runtime rt = Runtime.getRuntime();
        final Process proc = rt.exec(command);
        // System.out.println("\nRunning command: " + command);
        final InputStream stderr = proc.getErrorStream();
        final InputStreamReader isr = new InputStreamReader(stderr);

        final List<String> output = new ArrayList<>();
        try (BufferedReader br = new BufferedReader(isr)) {
            String line;
            while ((line = br.readLine()) != null) {
                output.add(line);
                // System.out.println("[command] " + line);
            }
        }

        final int exitVal = proc.waitFor();
        // System.out.println("[command] Process exitValue: " + exitVal);

        if (exitVal != 0) {
            throw new Exception("Error in command: " + command);
        }
        int pos1, pos2;

        pos1 = output.get(output.size() - 1).indexOf(" copied, ");
        pos1 += 9;

        pos2 = output.get(output.size() - 1).indexOf(" s, ");

        String aux;

        aux = output.get(output.size() - 1).substring(pos1, pos2);
        aux = aux.replace(',', '.');

        final float value = Float.parseFloat(aux);

        latency += value;
        // System.out.println("[current] Latency: " + (latency / (i + 1)));

        final File faux = new File(bucket.getMountPoint() + "/pingfile-" + myId);
        faux.delete();
    }

    bucket.setLatency(latency / (i + 1));
}

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

public void copyKeyAndCertificate() {
    File sourceCertificate = getCRTFile();
    if (!sourceCertificate.exists()) {
        return;// w  w w  . ja va  2 s  . c o m
    }

    File sourceKey = new File(m_certDirectory, getPrimaryServerFqdn() + "-web.key");
    if (!sourceKey.exists()) {
        return;
    }

    try {
        Runtime runtime = Runtime.getRuntime();
        String[] cmdLine = new String[] { m_binDirectory + 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());
        }
        File destinationCertificate = new File(m_sslDirectory, "ssl-web.crt");
        File destinationKey = new File(m_sslDirectory, "ssl-web.key");
        FileUtils.copyFile(sourceCertificate, destinationCertificate);
        FileUtils.copyFile(sourceKey, destinationKey);
        File sourceKeyStore = new File(m_certDirectory, getPrimaryServerFqdn() + "-web.keystore");
        File destinationKeyStore = new File(m_sslDirectory, "ssl-web.keystore");
        FileUtils.copyFile(sourceKeyStore, destinationKeyStore);
        File sourcePkcsKeyStore = new File(m_certDirectory, getPrimaryServerFqdn() + "-web.p12");
        File destinationPkcsKeyStore = new File(m_sslDirectory, "ssl-web.p12");
        FileUtils.copyFile(sourcePkcsKeyStore, destinationPkcsKeyStore);
    } catch (Exception e) {
        throw new UserException("&msg.copyError");
    }
}

From source file:hydrograph.ui.perspective.dialog.PreStartActivity.java

private void restartHydrograph() {
    logger.info("Starting New Hydrograph");
    String path = Platform.getInstallLocation().getURL().getPath();
    if ((StringUtils.isNotBlank(path)) && (StringUtils.startsWith(path, "/")) && (OSValidator.isWindows())) {
        path = StringUtils.substring(path, 1);
    }// w  ww  .  j  ava  2  s  . c o m
    String command = path + HYDROGRAPH_EXE;
    Runtime runtime = Runtime.getRuntime();
    try {
        if (OSValidator.isWindows()) {
            String[] commandArray = { "cmd.exe", "/c", command };
            runtime.exec(commandArray);
        }
    } catch (IOException ioException) {
        logger.error("Exception occurred while starting hydrograph" + ioException);
    }
    System.exit(0);
}

From source file:kaleidoscope.server.UploadHandler.java

public UploadHandler(final RestRequestHandler handler, final HttpServerRequest req,
        final Set<String> supportImageFormat) throws URISyntaxException {
    this.handler = handler;
    this.req = req;
    this.rootPath = handler.getRootPath();
    final String defaultOutfileExt = handler.getDefaultOutfileExt();
    final String defaultResize = handler.getDefaultResize();
    final int maxUploadFileSize = handler.getMaxUploadFileSize();
    final int maxThumbnailCount = handler.getMaxThumbnailCount();
    final int expireSec = handler.getExpireSec();
    final String readUrl = handler.getReadUrl();
    this.supportImageFormat = supportImageFormat;
    final String realCmd = Paths.get(getClass().getClassLoader().getResource(handler.getCmd()).toURI())
            .toString();/*www  . ja  v  a 2 s  .c  o m*/

    req.endHandler(new Handler<Void>() {
        @Override
        public void handle(Void event) {
            try {
                if (file == null) {
                    handler.requestEnd(req, HttpResponseStatus.BAD_REQUEST,
                            new Object[] { "required.param.file" });
                    return;
                } else if (FileUtils.getSize(file) > maxUploadFileSize) {
                    handler.requestEnd(req, HttpResponseStatus.BAD_REQUEST,
                            new Object[] { "max.upload.file.size", maxUploadFileSize });
                    return;
                } else if (supportImageFormat.contains(ext) != true) {
                    handler.requestEnd(req, HttpResponseStatus.BAD_REQUEST,
                            new Object[] { "invalid.image.format", supportImageFormat });
                    return;
                }

                String resizes = req.formAttributes().get("resizes");
                if ((resizes == null) || ((resizes = resizes.trim()).length() == 0)) {
                    resizes = defaultResize;
                }

                String[] resizeList = resizes.split(",");
                if (resizeList.length > maxThumbnailCount) {
                    handler.requestEnd(req, HttpResponseStatus.BAD_REQUEST,
                            new Object[] { "max.thumbnail.count", maxThumbnailCount });
                    return;
                }

                String outfilePrefix = path + "/" + basename;
                String outfileExt = req.formAttributes().get("outfileExt");
                if (StringUtils.isEmpty(outfileExt) == true) {
                    outfileExt = defaultOutfileExt;
                }

                Runtime runtime = Runtime.getRuntime();
                String command = realCmd + " " + Paths.get(file) + " " + Paths.get(outfilePrefix) + " "
                        + outfileExt + " " + resizes;
                Process process = runtime.exec(command);
                process.waitFor();

                log.debug("cmd=[{}], exitValue=[{}]", command, process.exitValue());

                JsonArray arr = new JsonArray();
                for (int i = 0; i < resizeList.length; i++) {
                    arr.add(readUrl + outfilePrefix.replaceAll(rootPath, "") + "_" + resizeList[i] + "."
                            + outfileExt);
                }

                Calendar expireDate = DateUtils.getCalendar(expireSec);
                expireDate.set(Calendar.SECOND, 0);
                JsonObject json = JsonUtils.getJson(HttpResponseStatus.OK).putArray("thumbnails", arr)
                        .putString("expireDate", DateUtils.DATE_FORMAT_ISO8601FMT.format(expireDate.getTime()));

                handler.requestEnd(req, HttpResponseStatus.OK, json);

                FileUtils.rmdir(file);
            } catch (Exception e) {
                log.error("e={}", e.getMessage(), e);
                handler.requestEnd(req, HttpResponseStatus.INTERNAL_SERVER_ERROR, e.getMessage());
            }
        }
    });

    log.debug(
            "rootPath={}, cmd={}, defaultOutfileExt={}, defaultResize={}"
                    + ", maxUploadFileSize={}, maxThumbnailCount={}"
                    + ", expireSec={}, readUrl={}, supportImageFormat={}",
            new Object[] { rootPath, realCmd, defaultOutfileExt, defaultResize, maxUploadFileSize,
                    maxThumbnailCount, expireSec, readUrl, supportImageFormat });
}

From source file:org.uoa.eolus.template.Nest.java

public void copyUserTemplate(String user, String template, String target, boolean move)
        throws DirectoryException {
    String cmd = "mv";
    if (move)//from  w  w w  . j  a  v a  2  s  .  c om
        cmd = "mv " + repo + "/" + user + "/" + template + " " + repo + "/" + user + "/" + target
                + "; exit; \n";
    else
        cmd = "cp -r " + repo + "/" + user + "/" + template + " " + repo + "/" + user + "/." + target + "; mv "
                + repo + "/" + user + "/." + target + " " + repo + "/" + user + "/" + target + "; exit; \n";

    System.out.println("CMD: " + cmd);

    Runtime run = Runtime.getRuntime();
    try {
        Process child = run.exec("/bin/bash");
        BufferedWriter outCommand = new BufferedWriter(new OutputStreamWriter(child.getOutputStream()));
        outCommand.write(cmd);
        outCommand.flush();
        //         InputStream out = child.getInputStream();
        //         InputStreamReader isr = new InputStreamReader(out);
        //         BufferedReader output = new BufferedReader(isr);
        //         InputStream err = child.getErrorStream();
        //         InputStreamReader eisr = new InputStreamReader(err);
        //         BufferedReader error = new BufferedReader(eisr);
        //         System.out.println("Waiting for");         
        child.waitFor();
        //         String o = "";
        //         String s;
        //         while ((s = output.readLine()) != null) {
        //            o += s + "\n";
        //         }
        //         System.out.println("stdout: " + o);
        //         String e = "";
        //         s = error.readLine(); // First line is a warning: Warning:
        //         // Permanently added 'XX.XX.XX.XX' (RSA) to
        //         // the list of known hosts.
        //         while ((s = error.readLine()) != null) {
        //            e += s + "\n";
        //         }
        //         System.out.println("stderr: " + e);

        if (child.exitValue() != 0)
            throw new InternalErrorException("Copy process failed.");
        else {
            System.out.println("Returning.");
        }
    } catch (Exception e) {
        throw new DirectoryException("Cannot execute rm command.", e);
    }
}

From source file:org.silena.main.RegistrationOld.java

public boolean isOnline() {

    Runtime runtime = Runtime.getRuntime();
    try {/*from  w  w  w . j  av  a  2s. c  om*/

        Process ipProcess = runtime.exec("/system/bin/ping -c 1 78.46.251.139");
        int exitValue = ipProcess.waitFor();
        return (exitValue == 0);

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

    return false;
}

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

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

    try {//from w  w  w .j  av a  2s  . c o m

        checkConfig();

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

        if (osName.startsWith("Windows")) {

            String command[] = { "cmd.exe", "/C",
                    "cd " + glassfishHomeDir.getAbsolutePath() + "\\bin & " + fName + ".bat " + " " + params };

            runtime.exec(command);

        } else {

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

        }

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