Example usage for java.lang Process exitValue

List of usage examples for java.lang Process exitValue

Introduction

In this page you can find the example usage for java.lang Process exitValue.

Prototype

public abstract int exitValue();

Source Link

Document

Returns the exit value for the process.

Usage

From source file:org.knime.knip.ilastik.nodes.headless.IlastikHeadlessNodeModel.java

/**
 * @param exec//from  ww  w  .ja v  a2  s.c  om
 * @throws IOException
 * @throws InterruptedException
 * @throws CanceledExecutionException
 * @throws URISyntaxException
 */
private void runIlastik(final String tmpDirPath, final List<String> inFiles, final ExecutionContext exec)
        throws IOException, InterruptedException {

    // get path of ilastik
    final String path = IlastikPreferencePage.getPath();

    String outpath;
    try {
        outpath = FileUtil.resolveToPath(FileUtil.toURL(m_pathToIlastikProjectFileModel.getStringValue()))
                .toAbsolutePath().toString();
    } catch (InvalidPathException | URISyntaxException e) {
        throw new IllegalArgumentException("The Path to the project file could not be resolved: " + e, e);
    }
    if (outpath == null) {
        throw new IllegalArgumentException("The Path to the project file could not be resolved.");
    }

    // DO NOT TOUCH THIS ORDER!
    inFiles.add(0, path);
    inFiles.add(1, "--headless");
    inFiles.add(2, "--project=".concat(outpath));
    inFiles.add(3, "--output_format=multipage tiff");
    inFiles.add(4, "--output_filename_format=".concat(tmpDirPath).concat("{nickname}" + RESULT_IMG_SUFFIX));

    KNIPGateway.log().debug("Executing ilastik with " + String.join(", ", inFiles));

    // build process with project and images
    ProcessBuilder pB = new ProcessBuilder(inFiles);

    // limit cpu + memory usage
    final Map<String, String> env = pB.environment();
    env.put("LAZYFLOW_THREADS", String.valueOf(m_ilastikThreadCount.getIntValue()));
    env.put("LAZYFLOW_TOTAL_RAM_MB", String.valueOf(m_ilastikMaxMemory.getIntValue()));

    // run ilastik
    Process p = pB.start();

    // write ilastik output to knime console
    redirectToKnimeConsole(p.getInputStream(), DirectedLogServiceFactory.debug());
    redirectToKnimeConsole(p.getErrorStream(), DirectedLogServiceFactory.error());

    try {
        while (!p.waitFor(500, TimeUnit.MILLISECONDS)) {
            exec.checkCanceled();
        }
    } catch (CanceledExecutionException cee) {
        KNIPGateway.log().error("Execution canceled, closing Ilastik now.");
        p.destroy();
    }

    // 0 indicates successful execution
    if (p.exitValue() != 0) {
        throw new IllegalStateException("Execution of ilastik was not successful.");
    }
}

From source file:canreg.client.analysis.Tools.java

public static LinkedList<String> callR(String rScript, String rpath, String reportFileName)
        throws TableErrorException {
    LinkedList<String> filesCreated = new LinkedList<String>();
    Runtime rt = Runtime.getRuntime();
    ArrayList<String> commandList = new ArrayList<String>();
    commandList.add(rpath);//ww w . ja v  a 2  s.c o m
    commandList.add("CMD");
    commandList.add("BATCH");
    commandList.add("--vanilla");
    commandList.add("--slave");
    commandList.add(rScript);
    commandList.add(reportFileName);

    //String command = canreg.common.Tools.encapsulateIfNeeded(rpath)
    //        + " CMD BATCH --vanilla --slave "
    //        + canreg.common.Tools.encapsulateIfNeeded(rScript) + " "
    //        + canreg.common.Tools.encapsulateIfNeeded(reportFileName);
    System.out.println(commandList);
    Process pr = null;
    try {
        pr = rt.exec(commandList.toArray(new String[] {}));
        // collect the output from the R program in a stream
        // BufferedInputStream is = new BufferedInputStream(pr.getInputStream());
        pr.waitFor();
        BufferedInputStream is = new BufferedInputStream(new FileInputStream(reportFileName));
        // convert the output to a string
        String theString = convertStreamToString(is);
        Logger.getLogger(RTableBuilderGrouped.class.getName()).log(Level.INFO, "Messages from R: \n{0}",
                theString);
        // System.out.println(theString);
        // and add all to the list of files to return
        for (String fileName : theString.split("\n")) {
            if (fileName.startsWith("-outFile:")) {
                fileName = fileName.replaceFirst("-outFile:", "");
                if (new File(fileName).exists()) {
                    filesCreated.add(fileName);
                }
            }
        }
    } catch (InterruptedException ex) {
        Logger.getLogger(RTableBuilder.class.getName()).log(Level.SEVERE, null, ex);
    } catch (java.util.NoSuchElementException ex) {
        Logger.getLogger(RTableBuilder.class.getName()).log(Level.SEVERE, null, ex);
        if (pr != null) {
            BufferedInputStream errorStream = new BufferedInputStream(pr.getErrorStream());
            String errorMessage = convertStreamToString(errorStream);
            System.out.println(errorMessage);
            throw new TableErrorException("R says:\n \"" + errorMessage + "\"");
        }
    } catch (IOException ex) {
        Logger.getLogger(Tools.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        if (pr != null) {
            System.out.println(pr.exitValue());
        }
    }
    return filesCreated;
}

From source file:net.solarnetwork.node.setup.s3.S3SetupManager.java

private List<Path> extractTarball(File tarball) throws IOException {
    List<String> cmd = new ArrayList<>(tarCommand.size());
    String tarballPath = tarball.getAbsolutePath();
    for (String param : tarCommand) {
        param = param.replace(SOURCE_FILE_PLACEHOLDER, tarballPath);
        param = param.replace(DESTINATION_DIRECTORY_PLACEHOLDER, destinationPath);
        cmd.add(param);//from   www.ja v  a  2s . c  om
    }
    if (log.isDebugEnabled()) {
        StringBuilder buf = new StringBuilder();
        for (String p : cmd) {
            if (buf.length() > 0) {
                buf.append(' ');
            }
            buf.append(p);
        }
        log.debug("Tar command: {}", buf.toString());
    }
    log.info("Extracting S3 tar archive {}", tarball);
    List<Path> extractedPaths = new ArrayList<>();
    ProcessBuilder pb = new ProcessBuilder(cmd);
    pb.redirectErrorStream(true); // OS X tar output list to STDERR; Linux GNU tar to STDOUT
    Process pr = pb.start();
    try (BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream()))) {
        String line = null;
        while ((line = in.readLine()) != null) {
            Matcher m = TAR_LIST_PAT.matcher(line);
            if (m.matches()) {
                line = m.group(1);
            }
            Path path = FileSystems.getDefault().getPath(line).toAbsolutePath().normalize();
            extractedPaths.add(path);
            log.trace("Installed setup resource: {}", line);
        }
    }
    try {
        pr.waitFor();
    } catch (InterruptedException e) {
        log.warn("Interrupted waiting for tar command to complete");
    }
    if (pr.exitValue() != 0) {
        String output = extractedPaths.stream().map(p -> p.toString()).collect(Collectors.joining("\n")).trim();
        log.error("Tar command returned non-zero exit code {}: {}", pr.exitValue(), output);
        throw new IOException("Tar command returned non-zero exit code " + pr.exitValue() + ": " + output);
    }
    return extractedPaths;
}

From source file:de.uni_potsdam.hpi.asg.common.io.Invoker.java

private ProcessReturn invoke(String[] cmd, List<String> params, File folder, int timeout) {
    List<String> command = new ArrayList<String>();
    command.addAll(Arrays.asList(cmd));
    command.addAll(params);//from  w  w  w  .j a v a2 s .  c o m
    ProcessReturn retVal = new ProcessReturn(Arrays.asList(cmd), params);
    Process process = null;
    try {
        logger.debug("Exec command: " + command.toString());
        //System.out.println(timeout + ": " + command.toString());
        ProcessBuilder builder = new ProcessBuilder(command);
        builder.directory(folder);
        builder.environment(); // bugfix setting env in test-mode (why this works? i dont know..)
        process = builder.start();

        Thread timeoutThread = null;
        if (timeout > 0) {
            timeoutThread = new Thread(new Timeout(Thread.currentThread(), timeout));
            timeoutThread.setName("Timout for " + command.toString());
            timeoutThread.start();
        }
        IOStreamReader ioreader = new IOStreamReader(process);
        Thread streamThread = new Thread(ioreader);
        streamThread.setName("StreamReader for " + command.toString());
        streamThread.start();
        process.waitFor();
        streamThread.join();
        if (timeoutThread != null) {
            timeoutThread.interrupt();
        }
        String out = ioreader.getResult();
        //System.out.println(out);
        if (out == null) {
            //System.out.println("out = null");
            retVal.setStatus(Status.noio);
        }
        retVal.setCode(process.exitValue());
        retVal.setStream(out);
        retVal.setStatus(Status.ok);
    } catch (InterruptedException e) {
        process.destroy();
        retVal.setTimeout(timeout);
        retVal.setStatus(Status.timeout);
    } catch (IOException e) {
        logger.error(e.getLocalizedMessage());
        retVal.setStatus(Status.ioexception);
    }
    return retVal;
}

From source file:com.exlibris.dps.delivery.vpp.mirador.MiradorViewerPreProcessor.java

private void setsymboliclink(String filePath) {
    Process p;//from w  w w.j a  v a 2 s. com
    Process pp;
    Process ppp;
    String fileDir = filePath.substring(0, filePath.lastIndexOf("/"));
    String filename = filePath.substring(fileDir.length() + 1);
    String totalfiledir = iipservDir + fileDir;
    String totalfilename = totalfiledir + "/" + filename;

    try {
        p = Runtime.getRuntime().exec("mkdir -p " + totalfiledir);
        p.waitFor();
        p.destroy();
    } catch (Exception e) {
        logger.error(e.getMessage());
    }
    //        File newDirectory = new File(totalfiledir);
    //        if (!newDirectory.exists() || !newDirectory.isDirectory()) {
    //           logger.error(totalfiledir+ " bestaat niet.");
    //        } else {
    //           ProcessBuilder pb = new ProcessBuilder("cd");
    //           pb.directory(newDirectory);
    try {
        //                ppp = pb.start();
        //                ppp.waitFor();
        pp = Runtime.getRuntime().exec("ln -nfs " + filePath + " " + totalfilename);
        pp.waitFor();
        logger.info("exit: " + pp.exitValue());
        pp.destroy();
        //                ppp.destroy();
    } catch (Exception e) {
        logger.error(e.getMessage());
    }
    //        }
}

From source file:org.wso2.andes.test.utils.QpidBrokerTestCase.java

public void cleanBroker()
{
    if (_brokerClean != null)
    {// w  w w . j a  v  a2  s. c  o m
        _logger.info("clean: " + _brokerClean);

        try
        {
            ProcessBuilder pb = new ProcessBuilder(_brokerClean.split("\\s+"));
            pb.redirectErrorStream(true);
            Process clean = pb.start();
            new Piper(clean.getInputStream(),_brokerOutputStream).start();

            clean.waitFor();

            _logger.info("clean exited: " + clean.exitValue());
        }
        catch (IOException e)
        {
            throw new RuntimeException(e);
        }
        catch (InterruptedException e)
        {
            throw new RuntimeException(e);
        }
    }
}

From source file:net.sourceforge.atunes.kernel.modules.repository.RepositoryHandler.java

/**
 * Finish.//from  www  .  j ava  2s .  co m
 */
public void applicationFinish() {
    if (repositoryRefresher != null) {
        repositoryRefresher.interrupt();
    }
    ApplicationStateHandler.getInstance().persistRepositoryCache(repository, true);

    // Execute command after last access to repository
    String command = ApplicationState.getInstance().getCommandAfterAccessRepository();
    if (command != null && !command.trim().equals("")) {
        try {
            Process p = Runtime.getRuntime().exec(command);
            // Wait process to end
            p.waitFor();
            int rc = p.exitValue();
            getLogger().info(LogCategories.END,
                    StringUtils.getString("Command '", command, "' return code: ", rc));
        } catch (Exception e) {
            getLogger().error(LogCategories.END, e);
        }
    }
}

From source file:org.openbi.kettle.plugins.refreshtableauextract.RefreshTableauExtract.java

public Result execute(Result previousResult, int nr) throws KettleException {
    Result result = previousResult;
    result.setResult(validate());/*from  w  w w.  ja  v  a  2s  .  c  o m*/
    if (!result.getResult()) {
        return result;
    }
    String[] commands;
    String tableauCommand = getRealValue(getTableauClient()).trim();
    if (tableauCommand.toLowerCase().endsWith(".exe")) {
        tableauCommand = tableauCommand.substring(0, tableauCommand.length() - 4);
    }
    tableauCommand = "\"" + tableauCommand + "\"";
    if (getRefreshType() == 0 || getRefreshType() == 1) {
        tableauCommand += " refreshextract";
    } else if (getRefreshType() == 2) {
        tableauCommand += " addfiletoextract";
    } else {
        logError(BaseMessages.getString(PKG, "RefreshTableauExtract.Error.InvalidRefreshType"));
        result.setResult(false);
        return result;
    }

    tableauCommand += " --server " + protocolList[getProtocol()] + "://" + getRealValue(getServer());
    if (getRealValue(getServerPort()) != null && !getRealValue(getServerPort()).isEmpty()) {
        tableauCommand += ":" + getRealValue(getServerPort());
    }

    tableauCommand += " --username " + getRealValue(getServerUser());
    tableauCommand += " --password " + getRealValue(getServerPassword());
    tableauCommand += " --datasource \"" + getRealValue(getDataSource()) + "\"";

    if (getRealValue(getSiteName()) != null && !getRealValue(getSiteName()).isEmpty()) {
        tableauCommand += " --site \"" + getRealValue(getSiteName()) + "\"";
    }
    if (getRealValue(getProject()) != null && !getRealValue(getProject()).isEmpty()) {
        tableauCommand += " --project \"" + getRealValue(getProject()) + "\"";
    }
    if (getRealValue(getProxyUser()) != null && !getRealValue(getProxyUser()).isEmpty()) {
        tableauCommand += " --proxy-username " + getRealValue(getProxyUser());
    }
    if (getRealValue(getProxyPassword()) != null && !getRealValue(getProxyPassword()).isEmpty()) {
        tableauCommand += " --proxy-password " + getRealValue(getProxyPassword());
    }

    if (getRefreshType() == 0) {
        commands = new String[1];
        tableauCommand += " --original-file \"" + getRealValue(getExtractFile()) + "\"";
        commands[0] = new String(tableauCommand);
    } else if (getRefreshType() == 1) {
        commands = new String[1];
        if (getFullRefresh()) {
            tableauCommand += " --force-full-refresh";
        }
        if (getRealValue(getSourceUser()) != null && !getRealValue(getSourceUser()).isEmpty()) {
            tableauCommand += " --source-username " + getRealValue(getSourceUser());
        }
        if (getRealValue(getSourcePassword()) != null & !getRealValue(getSourcePassword()).isEmpty()) {
            tableauCommand += " --source-password " + getRealValue(getSourcePassword());
        }
        commands[0] = new String(tableauCommand);
    } else {
        String[] fileStrings = null;
        if (processResultFiles) {
            if (result != null && previousResult.getResultFiles().size() > 0) {

                int size = previousResult.getResultFiles().size();
                if (log.isBasic()) {
                    logBasic(BaseMessages.getString(PKG, "RefreshTableauExtract.FilesFound", "" + size));
                }
                try {
                    List<ResultFile> resultFiles = previousResult.getResultFilesList();
                    List<String> files = new ArrayList<String>();
                    Iterator<ResultFile> it = resultFiles.iterator();
                    while (it.hasNext()) {
                        ResultFile f = it.next();
                        FileObject o = f.getFile();
                        if (o.getType().equals(FileType.FILE)) {
                            if (o.exists()) {
                                files.add(o.getName().toString().startsWith("file:///")
                                        ? o.getName().toString().substring(8)
                                        : o.getName().toString());
                            } else {
                                logBasic(BaseMessages.getString(PKG, "RefreshTableauExtract.FileNotExist",
                                        "" + o.getName()));
                            }
                        } else {
                            logBasic(BaseMessages.getString(PKG, "RefreshTableauExtract.ResultNotFile",
                                    "" + o.getName()));
                        }
                    }
                    if (files.size() > 0) {
                        Iterator<String> ite = files.iterator();
                        fileStrings = new String[files.size()];
                        int i = 0;
                        while (ite.hasNext()) {
                            fileStrings[i] = ite.next();
                            i++;
                        }

                    } else {
                        logBasic(BaseMessages.getString(PKG, "RefreshTableauExtract.NoFilesOnResult"));
                        result.setResult(true);
                        return result;
                    }
                } catch (Exception ex) {
                    logError(ex.toString());
                    result.setResult(false);
                    return result;
                }
            } else {
                logBasic(BaseMessages.getString(PKG, "RefreshTableauExtract.NoFilesOnResult"));
                result.setResult(true);
                return result;
            }
        } else {
            // Get source and destination files, also wildcard
            String[] vFilePaths = filePaths;
            String[] vWildcards = wildcards;
            boolean[] includeSubfolders = new boolean[vFilePaths.length];
            String[] fileRequired = new String[vFilePaths.length];

            for (int i = 0; i < includeSubfolders.length; i++) {
                includeSubfolders[i] = false;
            }
            FileInputList files = FileInputList.createFileList(this, vFilePaths, vWildcards, fileRequired,
                    includeSubfolders);
            fileStrings = new String[files.getFileStrings().length];
            fileStrings = files.getFileStrings();
        }
        commands = new String[fileStrings.length];
        for (int i = 0; i < fileStrings.length; i++) {
            commands[i] = new String(tableauCommand + " --file \"" + fileStrings[i] + "\"");
        }
    }

    FileObject fileObject = null;
    String realScript = "";
    FileObject tempFile = null;

    for (int i = 0; i < commands.length; i++) {
        //    realScript+="echo Running: "+commands[i]+"\n";
        realScript += commands[i] + "\n";
        if (log.isDetailed()) {
            logDetailed(BaseMessages.getString(PKG, "RefreshTableauExtract.Commands", commands[i]));
        }
    }
    try {
        // What's the exact command?
        String[] command;

        if (log.isBasic()) {
            logBasic(BaseMessages.getString(PKG, "RefreshTableuaExtract.RunningOn", Const.getOS()));
        }

        if (Const.getOS().equals("Windows 95")) {
            //base = new String[] { "command.com", "/C" };
            tempFile = KettleVFS.createTempFile("kettle", "shell.bat", null, this);
            fileObject = createTemporaryShellFile(tempFile, realScript);
            command = new String[] { "command.com", "/C",
                    "\"" + Const.optionallyQuoteStringByOS(KettleVFS.getFilename(fileObject)) + "\"" };
        } else if (Const.getOS().startsWith("Windows")) {
            //base = new String[] { "cmd.exe", "/C" };
            tempFile = KettleVFS.createTempFile("kettle", "shell.bat", null, this);
            fileObject = createTemporaryShellFile(tempFile, realScript);
            command = new String[] { "cmd.exe", "/C",
                    "\"" + Const.optionallyQuoteStringByOS(KettleVFS.getFilename(fileObject)) + "\"" };
        } else {
            tempFile = KettleVFS.createTempFile("kettle", "shell", null, this);
            fileObject = createTemporaryShellFile(tempFile, realScript);
            command = new String[] { Const.optionallyQuoteStringByOS(KettleVFS.getFilename(fileObject)) };
        }

        ProcessBuilder pb = new ProcessBuilder(command);

        Map<String, String> env = pb.environment();
        String[] variables = listVariables();
        for (int i = 0; i < variables.length; i++) {
            env.put(variables[i], getVariable(variables[i]));
        }

        if (getWorkingDirectory() != null && !Const.isEmpty(Const.rtrim(getRealValue(getWorkingDirectory())))) {
            String vfsFilename = environmentSubstitute(getRealValue(getWorkingDirectory()));
            File file = new File(KettleVFS.getFilename(KettleVFS.getFileObject(vfsFilename, this)));
            pb.directory(file);
        }

        if (log.isDetailed()) {
            logDetailed(BaseMessages.getString(PKG, "RefreshTableauExtract.CommandStarted"));
        }
        Process proc = pb.start();
        // any error message?
        StreamLogger errorLogger = new StreamLogger(log, proc.getErrorStream(), "(stderr)");

        // any output?
        StreamLogger outputLogger = new StreamLogger(log, proc.getInputStream(), "(stdout)");

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

        proc.waitFor();

        if (log.isDetailed()) {
            logDetailed(BaseMessages.getString(PKG, "RefreshTableauExtract.CommandFinished"));
        }
        // What's the exit status?
        result.setExitStatus(proc.exitValue());
        if (result.getExitStatus() != 0) {
            logError(BaseMessages.getString(PKG, "RefreshTableauExtract.ExitStatus",
                    "" + result.getExitStatus()));
            result.setResult(false);
        }

        // close the streams
        // otherwise you get "Too many open files, java.io.IOException" after a lot of iterations
        proc.getErrorStream().close();
        proc.getOutputStream().close();

    } catch (Exception ex) {
        logError(ex.toString());
        result.setResult(false);
    } finally {
        // If we created a temporary file, remove it...
        //
        if (tempFile != null) {
            try {
                tempFile.delete();
            } catch (Exception e) {
                BaseMessages.getString(PKG, "RefreshTableauExtract.UnexpectedError", tempFile.toString(),
                        e.toString());
            }
        }
    }

    return result;

}

From source file:org.pentaho.di.job.entries.shell.JobEntryShell.java

private void executeShell(Result result, List<RowMetaAndData> cmdRows, String[] args) {
    FileObject fileObject = null;
    String realScript = null;//from   w  w  w .  j  a v  a  2 s .  c  om
    FileObject tempFile = null;

    try {
        // What's the exact command?
        String[] base = null;
        List<String> cmds = new ArrayList<String>();

        if (log.isBasic()) {
            logBasic(BaseMessages.getString(PKG, "JobShell.RunningOn", Const.getOS()));
        }

        if (insertScript) {
            realScript = environmentSubstitute(script);
        } else {
            String realFilename = environmentSubstitute(getFilename());
            fileObject = KettleVFS.getFileObject(realFilename, this);
        }

        if (Const.getOS().equals("Windows 95")) {
            base = new String[] { "command.com", "/C" };
            if (insertScript) {
                tempFile = KettleVFS.createTempFile("kettle", "shell.bat", environmentSubstitute(workDirectory),
                        this);
                fileObject = createTemporaryShellFile(tempFile, realScript);
            }
        } else if (Const.getOS().startsWith("Windows")) {
            base = new String[] { "cmd.exe", "/C" };
            if (insertScript) {
                tempFile = KettleVFS.createTempFile("kettle", "shell.bat", environmentSubstitute(workDirectory),
                        this);
                fileObject = createTemporaryShellFile(tempFile, realScript);
            }
        } else {
            if (insertScript) {
                tempFile = KettleVFS.createTempFile("kettle", "shell", environmentSubstitute(workDirectory),
                        this);
                fileObject = createTemporaryShellFile(tempFile, realScript);
            }
            base = new String[] { KettleVFS.getFilename(fileObject) };
        }

        // Construct the arguments...
        if (argFromPrevious && cmdRows != null) {
            // Add the base command...
            for (int i = 0; i < base.length; i++) {
                cmds.add(base[i]);
            }

            if (Const.getOS().equals("Windows 95") || Const.getOS().startsWith("Windows")) {
                // for windows all arguments including the command itself
                // need to be
                // included in 1 argument to cmd/command.

                StringBuffer cmdline = new StringBuffer(300);

                cmdline.append('"');
                cmdline.append(Const.optionallyQuoteStringByOS(KettleVFS.getFilename(fileObject)));
                // Add the arguments from previous results...
                for (int i = 0; i < cmdRows.size(); i++) {
                    // Normally just one row, but once in a while to remain compatible we have multiple.

                    RowMetaAndData r = cmdRows.get(i);
                    for (int j = 0; j < r.size(); j++) {
                        cmdline.append(' ');
                        cmdline.append(Const.optionallyQuoteStringByOS(r.getString(j, null)));
                    }
                }
                cmdline.append('"');
                cmds.add(cmdline.toString());
            } else {
                // Add the arguments from previous results...
                for (int i = 0; i < cmdRows.size(); i++) {
                    // Normally just one row, but once in a while to remain compatible we have multiple.

                    RowMetaAndData r = cmdRows.get(i);
                    for (int j = 0; j < r.size(); j++) {
                        cmds.add(Const.optionallyQuoteStringByOS(r.getString(j, null)));
                    }
                }
            }
        } else if (args != null) {
            // Add the base command...
            for (int i = 0; i < base.length; i++) {
                cmds.add(base[i]);
            }

            if (Const.getOS().equals("Windows 95") || Const.getOS().startsWith("Windows")) {
                // for windows all arguments including the command itself
                // need to be
                // included in 1 argument to cmd/command.

                StringBuffer cmdline = new StringBuffer(300);

                cmdline.append('"');
                cmdline.append(Const.optionallyQuoteStringByOS(KettleVFS.getFilename(fileObject)));

                for (int i = 0; i < args.length; i++) {
                    cmdline.append(' ');
                    cmdline.append(Const.optionallyQuoteStringByOS(args[i]));
                }
                cmdline.append('"');
                cmds.add(cmdline.toString());
            } else {
                for (int i = 0; i < args.length; i++) {
                    cmds.add(args[i]);
                }
            }
        }

        StringBuffer command = new StringBuffer();

        Iterator<String> it = cmds.iterator();
        boolean first = true;
        while (it.hasNext()) {
            if (!first) {
                command.append(' ');
            } else {
                first = false;
            }
            command.append(it.next());
        }
        if (log.isBasic()) {
            logBasic(BaseMessages.getString(PKG, "JobShell.ExecCommand", command.toString()));
        }

        // Build the environment variable list...
        ProcessBuilder procBuilder = new ProcessBuilder(cmds);
        Map<String, String> env = procBuilder.environment();
        String[] variables = listVariables();
        for (int i = 0; i < variables.length; i++) {
            env.put(variables[i], getVariable(variables[i]));
        }

        if (getWorkDirectory() != null && !Const.isEmpty(Const.rtrim(getWorkDirectory()))) {
            String vfsFilename = environmentSubstitute(getWorkDirectory());
            File file = new File(KettleVFS.getFilename(KettleVFS.getFileObject(vfsFilename, this)));
            procBuilder.directory(file);
        }
        Process proc = procBuilder.start();

        // any error message?
        StreamLogger errorLogger = new StreamLogger(log, proc.getErrorStream(), "(stderr)", true);

        // any output?
        StreamLogger outputLogger = new StreamLogger(log, proc.getInputStream(), "(stdout)");

        // kick them off
        Thread errorLoggerThread = new Thread(errorLogger);
        errorLoggerThread.start();
        Thread outputLoggerThread = new Thread(outputLogger);
        outputLoggerThread.start();

        proc.waitFor();
        if (log.isDetailed()) {
            logDetailed(BaseMessages.getString(PKG, "JobShell.CommandFinished", command.toString()));
        }

        // What's the exit status?
        result.setExitStatus(proc.exitValue());
        if (result.getExitStatus() != 0) {
            if (log.isDetailed()) {
                logDetailed(BaseMessages.getString(PKG, "JobShell.ExitStatus",
                        environmentSubstitute(getFilename()), "" + result.getExitStatus()));
            }

            result.setNrErrors(1);
        }

        // wait until loggers read all data from stdout and stderr
        errorLoggerThread.join();
        outputLoggerThread.join();

        // close the streams
        // otherwise you get "Too many open files, java.io.IOException" after a lot of iterations
        proc.getErrorStream().close();
        proc.getOutputStream().close();

    } catch (IOException ioe) {
        logError(BaseMessages.getString(PKG, "JobShell.ErrorRunningShell", environmentSubstitute(getFilename()),
                ioe.toString()), ioe);
        result.setNrErrors(1);
    } catch (InterruptedException ie) {
        logError(BaseMessages.getString(PKG, "JobShell.Shellinterupted", environmentSubstitute(getFilename()),
                ie.toString()), ie);
        result.setNrErrors(1);
    } catch (Exception e) {
        logError(BaseMessages.getString(PKG, "JobShell.UnexpectedError", environmentSubstitute(getFilename()),
                e.toString()), e);
        result.setNrErrors(1);
    } finally {
        // If we created a temporary file, remove it...
        //
        if (tempFile != null) {
            try {
                tempFile.delete();
            } catch (Exception e) {
                BaseMessages.getString(PKG, "JobShell.UnexpectedError", tempFile.toString(), e.toString());
            }
        }
    }

    if (result.getNrErrors() > 0) {
        result.setResult(false);
    } else {
        result.setResult(true);
    }
}

From source file:net.sourceforge.atunes.kernel.modules.repository.RepositoryHandler.java

@Override
protected Runnable getPreviousInitializationTask() {
    return new Runnable() {
        @Override/*w  w  w.j a va2 s.  c  o  m*/
        public void run() {
            // This is the first access to repository, so execute the command defined by user
            String command = ApplicationState.getInstance().getCommandBeforeAccessRepository();
            if (command != null && !command.trim().equals("")) {
                try {
                    Process p = Runtime.getRuntime().exec(command);
                    // Wait process to end
                    p.waitFor();
                    int rc = p.exitValue();
                    getLogger().info(LogCategories.START,
                            StringUtils.getString("Command '", command, "' return code: ", rc));
                } catch (Exception e) {
                    getLogger().error(LogCategories.START, e);
                }
            }
            repositoryRetrievedFromCache = ApplicationStateHandler.getInstance().retrieveRepositoryCache();
        }
    };
}