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.zilverline.web.HandlerValidator.java

/**
 * Validator for SearchForm. Validates name, maxResults, startAt and query
 * // ww  w  .j a v  a  2  s .  c  om
 * @see org.springframework.validation.Validator#validate(java.lang.Object, org.springframework.validation.Errors)
 */
public void validate(Object obj, Errors errors) {
    Handler handler = (Handler) obj;
    Map mappings = handler.getMappings();
    // convert the keys to lowercase
    Iterator mapping = mappings.entrySet().iterator();

    try {
        while (mapping.hasNext()) {
            Map.Entry element = (Map.Entry) mapping.next();
            String archiver = (String) element.getValue();
            log.debug("checking mappings: " + archiver);
            // can be empty: then java.util.Zip used
            if (StringUtils.hasLength(archiver)) {
                // the archiver is an external application with options,
                // check whether the application exists
                String exe = archiver.split(" ")[0];
                log.debug("checking mappings: " + exe);
                File exeFile = new File(exe);
                if (exeFile.exists()) {
                    log.debug("Can find " + exe);
                    continue;
                }

                // else try find the thing on the path
                Process proc = Runtime.getRuntime().exec(exe);
                // any error message?
                StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR");
                // any output?
                StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT");
                // kick them off
                errorGobbler.start();
                outputGobbler.start();

                proc.destroy();
                log.debug("Exit value: " + proc.exitValue());

                // everthing OK?
                if (proc.exitValue() != 0) {
                    // error executing proc
                    log.debug(" --> Can't execute: '" + exe + "'. Exit value: "
                            + SysUtils.getErrorTextById(proc.exitValue()));
                    log.debug("mappings must exist on disk: " + exe);
                    errors.rejectValue("mappings", null, null, "must exist on disk.");
                } else {
                    log.debug(" --> Can execute: '" + exe + "'. Exit value: "
                            + SysUtils.getErrorTextById(proc.exitValue()));
                }
            }
        }
    } catch (Exception e) {
        log.debug("Can not execute one of the mappings", e);
        errors.rejectValue("mappings", null, null, "must exist on disk.");
    }

}

From source file:org.jenkinsci.plugins.proccleaner.PsBasedUnixProcessTree.java

@Override
public PsBasedProcessTree createProcessTreeFor(String user) throws InterruptedException, IOException {
    String[] cmd = { "ps", "-u", user, "-o", "pid,ppid,args" };
    ProcessBuilder pb = new ProcessBuilder(cmd);
    pb.redirectErrorStream(true);/*w  ww.  j av a2  s  .  co  m*/
    final Process proc = pb.start();
    final StringWriter writer = new StringWriter();

    try {
        IOUtils.copy(proc.getInputStream(), writer);
    } catch (IOException e) {
        LOGGER.warning("'ps' command invocation IOException occurred!");
    }

    BufferedReader reader = new BufferedReader(new StringReader(writer.toString()));
    if (proc.waitFor() != 0) {
        LOGGER.warning("'ps' command invocation " + ArrayUtils.toString(cmd) + " failed! Return code: "
                + proc.exitValue());
        LOGGER.fine("Received output from 'ps' command invocation follows:");

        if (getLog() != null) {
            getLog().println("WARNING: 'ps' command invocation " + ArrayUtils.toString(cmd)
                    + " failed! Return code: " + proc.exitValue());
            getLog().println("DEBUG: Received output from 'ps' command invocation follows:");
        }

        String line;
        while ((line = reader.readLine()) != null) {
            LOGGER.fine(line);
            if (getLog() != null)
                getLog().println("DEBUG: '" + line + "'");
        }
        return null;
    }

    String line = reader.readLine(); // first line should be "PID  PPID COMMAND" - skip it
    if (StringUtils.isEmpty(line)) {
        LOGGER.fine("Unrecognized output from 'ps' command invocation! Output is empty!");
        if (getLog() != null) {
            getLog().println("DEBUG: Unrecognized output from 'ps' command invocation! Output is empty!");
        }
        return null;

    }
    if (!line.matches("^\\s*PID\\s*PPID\\s*(COMMAND|ARGS)\\s*$")) {
        LOGGER.fine("Unrecognized first output line from 'ps' command invocation! Was: '" + line + "'");
        if (getLog() != null) {
            getLog().println(
                    "DEBUG: Unrecognized first output line from 'ps' command invocation! Was: '" + line + "'");
        }
        return null;
    }

    PsBasedProcessTree ptree = new PsBasedUnixProcessTree();
    while ((line = reader.readLine()) != null) {
        if (getLog() != null)
            getLog().println("DEBUG: '" + line + "'");
        ptree.addProcess(line);
    }
    ptree.setLog(getLog());
    return ptree;
}

From source file:org.apache.slider.providers.agent.TestAgentClientProvider2.java

@Test
public void testRunCommand() throws Exception {
    AgentClientProvider provider = new AgentClientProvider(null);
    File appPkgDir = new File("/tmp/pkg");
    File agentPkgDir = new File("/tmp/agt");
    File cmdDir = new File("/tmp/cmd");
    String client_script = "scripts/abc.py";

    List<String> commands = Arrays.asList("python", "-S",
            new File("/tmp/pkg").getAbsolutePath() + File.separator + "package" + File.separator
                    + "scripts/abc.py",
            "INSTALL", new File("/tmp/cmd").getAbsolutePath() + File.separator + "command.json",
            new File("/tmp/pkg").getAbsolutePath() + File.separator + "package",
            new File("/tmp/cmd").getAbsolutePath() + File.separator + "command-out.json", "DEBUG");

    ProcessBuilder pbMock = PowerMock.createMock(ProcessBuilder.class);
    Process procMock = PowerMock.createMock(Process.class);
    PowerMock.expectNew(ProcessBuilder.class, commands).andReturn(pbMock);

    expect(pbMock.environment()).andReturn(new HashMap<String, String>()).anyTimes();
    expect(pbMock.start()).andReturn(procMock);
    expect(pbMock.command()).andReturn(new ArrayList<String>());
    expect(procMock.waitFor()).andReturn(0);
    expect(procMock.exitValue()).andReturn(0);
    expect(procMock.getErrorStream()).andReturn(IOUtils.toInputStream("stderr", "UTF-8"));
    expect(procMock.getInputStream()).andReturn(IOUtils.toInputStream("stdout", "UTF-8"));

    PowerMock.replayAll();/*w  w  w.  j a  va2s.  c  o m*/

    provider.runCommand(appPkgDir, agentPkgDir, cmdDir, client_script);
    PowerMock.verifyAll();
}

From source file:org.codelibs.fess.job.CrawlJob.java

protected void executeCrawler() {
    final List<String> cmdList = new ArrayList<>();
    final String cpSeparator = SystemUtils.IS_OS_WINDOWS ? ";" : ":";
    final ServletContext servletContext = ComponentUtil.getComponent(ServletContext.class);
    final SystemHelper systemHelper = ComponentUtil.getSystemHelper();
    final ProcessHelper processHelper = ComponentUtil.getProcessHelper();
    final FessConfig fessConfig = ComponentUtil.getFessConfig();

    cmdList.add(fessConfig.getJavaCommandPath());

    // -cp/*from   w  ww.jav  a 2 s .  c  om*/
    cmdList.add("-cp");
    final StringBuilder buf = new StringBuilder(100);
    ResourceUtil.getOverrideConfPath().ifPresent(p -> {
        buf.append(p);
        buf.append(cpSeparator);
    });
    final String confPath = System.getProperty(Constants.FESS_CONF_PATH);
    if (StringUtil.isNotBlank(confPath)) {
        buf.append(confPath);
        buf.append(cpSeparator);
    }
    // WEB-INF/env/crawler/resources
    buf.append("WEB-INF");
    buf.append(File.separator);
    buf.append("env");
    buf.append(File.separator);
    buf.append("crawler");
    buf.append(File.separator);
    buf.append("resources");
    buf.append(cpSeparator);
    // WEB-INF/classes
    buf.append("WEB-INF");
    buf.append(File.separator);
    buf.append("classes");
    // target/classes
    final String userDir = System.getProperty("user.dir");
    final File targetDir = new File(userDir, "target");
    final File targetClassesDir = new File(targetDir, "classes");
    if (targetClassesDir.isDirectory()) {
        buf.append(cpSeparator);
        buf.append(targetClassesDir.getAbsolutePath());
    }
    // WEB-INF/lib
    appendJarFile(cpSeparator, buf, new File(servletContext.getRealPath("/WEB-INF/lib")),
            "WEB-INF" + File.separator + "lib" + File.separator);
    // WEB-INF/env/crawler/lib
    appendJarFile(cpSeparator, buf, new File(servletContext.getRealPath("/WEB-INF/env/crawler/lib")), "WEB-INF"
            + File.separator + "env" + File.separator + "crawler" + File.separator + "lib" + File.separator);
    final File targetLibDir = new File(targetDir, "fess" + File.separator + "WEB-INF" + File.separator + "lib");
    if (targetLibDir.isDirectory()) {
        appendJarFile(cpSeparator, buf, targetLibDir, targetLibDir.getAbsolutePath() + File.separator);
    }
    cmdList.add(buf.toString());

    if (useLocalElasticsearch) {
        final String httpAddress = System.getProperty(Constants.FESS_ES_HTTP_ADDRESS);
        if (StringUtil.isNotBlank(httpAddress)) {
            cmdList.add("-D" + Constants.FESS_ES_HTTP_ADDRESS + "=" + httpAddress);
        }
    }

    final String systemLastaEnv = System.getProperty("lasta.env");
    if (StringUtil.isNotBlank(systemLastaEnv)) {
        if (systemLastaEnv.equals("web")) {
            cmdList.add("-Dlasta.env=crawler");
        } else {
            cmdList.add("-Dlasta.env=" + systemLastaEnv);
        }
    } else if (StringUtil.isNotBlank(lastaEnv)) {
        cmdList.add("-Dlasta.env=" + lastaEnv);
    }

    addSystemProperty(cmdList, Constants.FESS_CONF_PATH, null, null);
    cmdList.add("-Dfess.crawler.process=true");
    cmdList.add("-Dfess.log.path=" + (logFilePath != null ? logFilePath : systemHelper.getLogFilePath()));
    addSystemProperty(cmdList, "fess.log.name", "fess-crawler", "-crawler");
    if (logLevel == null) {
        addSystemProperty(cmdList, "fess.log.level", null, null);
    } else {
        cmdList.add("-Dfess.log.level=" + logLevel);
        if (logLevel.equalsIgnoreCase("debug")) {
            cmdList.add("-Dorg.apache.tika.service.error.warn=true");
        }
    }
    stream(fessConfig.getJvmCrawlerOptionsAsArray())
            .of(stream -> stream.filter(StringUtil::isNotBlank).forEach(value -> cmdList.add(value)));

    File ownTmpDir = null;
    final String tmpDir = System.getProperty("java.io.tmpdir");
    if (fessConfig.isUseOwnTmpDir() && StringUtil.isNotBlank(tmpDir)) {
        ownTmpDir = new File(tmpDir, "fessTmpDir_" + sessionId);
        if (ownTmpDir.mkdirs()) {
            cmdList.add("-Djava.io.tmpdir=" + ownTmpDir.getAbsolutePath());
            cmdList.add("-Dpdfbox.fontcache=" + ownTmpDir.getAbsolutePath());
        } else {
            ownTmpDir = null;
        }
    }

    cmdList.add(ComponentUtil.getThumbnailManager().getThumbnailPathOption());

    if (StringUtil.isNotBlank(jvmOptions)) {
        split(jvmOptions, " ").of(stream -> stream.filter(StringUtil::isNotBlank).forEach(s -> cmdList.add(s)));
    }

    cmdList.add(Crawler.class.getCanonicalName());

    cmdList.add("--sessionId");
    cmdList.add(sessionId);
    cmdList.add("--name");
    cmdList.add(namespace);

    if (webConfigIds != null && webConfigIds.length > 0) {
        cmdList.add("-w");
        cmdList.add(StringUtils.join(webConfigIds, ','));
    }
    if (fileConfigIds != null && fileConfigIds.length > 0) {
        cmdList.add("-f");
        cmdList.add(StringUtils.join(fileConfigIds, ','));
    }
    if (dataConfigIds != null && dataConfigIds.length > 0) {
        cmdList.add("-d");
        cmdList.add(StringUtils.join(dataConfigIds, ','));
    }
    if (documentExpires >= -1) {
        cmdList.add("-e");
        cmdList.add(Integer.toString(documentExpires));
    }

    File propFile = null;
    try {
        cmdList.add("-p");
        propFile = File.createTempFile("crawler_", ".properties");
        cmdList.add(propFile.getAbsolutePath());
        try (FileOutputStream out = new FileOutputStream(propFile)) {
            final Properties prop = new Properties();
            prop.putAll(ComponentUtil.getSystemProperties());
            prop.store(out, cmdList.toString());
        }

        final File baseDir = new File(servletContext.getRealPath("/WEB-INF")).getParentFile();

        if (logger.isInfoEnabled()) {
            logger.info("Crawler: \nDirectory=" + baseDir + "\nOptions=" + cmdList);
        }

        final JobProcess jobProcess = processHelper.startProcess(sessionId, cmdList, pb -> {
            pb.directory(baseDir);
            pb.redirectErrorStream(true);
        });

        final InputStreamThread it = jobProcess.getInputStreamThread();
        it.start();

        final Process currentProcess = jobProcess.getProcess();
        currentProcess.waitFor();
        it.join(5000);

        final int exitValue = currentProcess.exitValue();

        if (logger.isInfoEnabled()) {
            logger.info("Crawler: Exit Code=" + exitValue + " - Crawler Process Output:\n" + it.getOutput());
        }
        if (exitValue != 0) {
            throw new FessSystemException("Exit Code: " + exitValue + "\nOutput:\n" + it.getOutput());
        }
    } catch (final FessSystemException e) {
        throw e;
    } catch (final InterruptedException e) {
        logger.warn("Crawler Process interrupted.");
    } catch (final Exception e) {
        throw new FessSystemException("Crawler Process terminated.", e);
    } finally {
        try {
            processHelper.destroyProcess(sessionId);
        } finally {
            if (propFile != null && !propFile.delete()) {
                logger.warn("Failed to delete {}.", propFile.getAbsolutePath());
            }
            deleteTempDir(ownTmpDir);
        }
    }
}

From source file:org.jenkinsci.plugins.proccleaner.PsBasedHPUXProcessTree.java

@Override
public PsBasedProcessTree createProcessTreeFor(String user) throws InterruptedException, IOException {
    String[] cmd = { "ps", "-u", user, "-f" };
    ProcessBuilder pb = new ProcessBuilder(cmd);
    pb.redirectErrorStream(true);/*from   ww  w.ja  v a  2 s .  com*/
    Process proc = pb.start();
    final StringWriter writer = new StringWriter();

    try {
        IOUtils.copy(proc.getInputStream(), writer);
    } catch (IOException e) {
        LOGGER.warning("'ps' command invocation IOException occurred!");
    }

    BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
    if (proc.waitFor() != 0) {
        LOGGER.warning("'ps' command invocation " + ArrayUtils.toString(cmd) + " failed! Return code: "
                + proc.exitValue());
        LOGGER.fine("Received output from 'ps' command invocation follows:");

        if (getLog() != null) {
            getLog().println("WARNING: 'ps' command invocation " + ArrayUtils.toString(cmd)
                    + " failed! Return code: " + proc.exitValue());
            getLog().println("DEBUG: Received output from 'ps' command invocation follows:");
        }

        String line;
        while ((line = reader.readLine()) != null) {
            LOGGER.fine(line);
            if (getLog() != null)
                getLog().println("DEBUG: '" + line + "'");
        }
        return null;
    }

    String line = reader.readLine(); // first line should be "UID PID PPID C STIME TTY TIME COMMAND" - skip it
    if (StringUtils.isEmpty(line)) {
        LOGGER.fine("Unrecognized output from 'ps' command invocation! Output is empty!");
        if (getLog() != null) {
            getLog().println("DEBUG: Unrecognized output from 'ps' command invocation! Output is empty!");
        }
        return null;

    }
    if (!line.matches("^\\s*UID\\s*PID\\s*PPID\\s*C\\s*STIME\\s*TTY\\s*TIME\\s*COMMAND\\s*$")) {
        LOGGER.fine("Unrecognized first output line from 'ps' command invocation! Was: '" + line + "'");
        if (getLog() != null) {
            getLog().println(
                    "DEBUG: Unrecognized first output line from 'ps' command invocation! Was: '" + line + "'");
        }
        return null;
    }

    PsBasedProcessTree ptree = new PsBasedHPUXProcessTree();
    while ((line = reader.readLine()) != null) {
        String[] ps = line.trim().split(" +", 8);
        if (ps.length < 8) {
            LOGGER.fine("Unrecognized output line from 'ps' command invocation! Was: '" + line + "'");
            if (getLog() != null) {
                getLog().println(
                        "DEBUG: Unrecognized output line from 'ps' command invocation! Was '" + line + "'");
            }

            return null;
        }
        if (getLog() != null)
            getLog().println("DEBUG: '" + line + "'");
        ptree.addProcess(ps[1] + ' ' + ps[2] + ' ' + ps[7]);
    }
    ptree.setLog(getLog());
    return ptree;
}

From source file:org.obiba.opal.server.UpgradeCommand.java

private ProcessResult executeOpalMigrator(String... args) {
    ProcessBuilder pb = getOpalMigratorProcessBuilder(args);

    try {//from   w w  w .  ja  va 2s  .  com
        Process p = pb.start();
        p.waitFor();
        BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line;
        StringBuilder stringBuilder = new StringBuilder();

        while ((line = br.readLine()) != null) {
            stringBuilder.append(line + "\n");
        }

        return new ProcessResult(p.exitValue(), stringBuilder.toString());
    } catch (IOException | InterruptedException e) {
        throw Throwables.propagate(e);
    }
}

From source file:org.opf_labs.utils.ProcessRunnerImpl.java

private synchronized int execute(final Process p) {
    long startTime = System.currentTimeMillis();
    feedProcess(p, this.processInput);
    int return_value;

    while (true) {
        // is the thread finished?
        try {//from www  .ja v  a2  s . c o m
            // then return
            return_value = p.exitValue();
            break;
        } catch (IllegalThreadStateException e) {
            // not finished
        }
        // is the runtime exceeded?
        if (System.currentTimeMillis() - startTime > this.timeout) {
            // then return
            p.destroy();
            return_value = -1;
            this.timedOut = true;
        }
        // else sleep again
        try {
            wait(POLLING_INTERVAL);
        } catch (InterruptedException e) {
            // just go on.
        }

    }
    return return_value;

}

From source file:org.sipfoundry.sipxconfig.admin.localization.LocalizationContextImpl.java

private void applyLocalizationPackage(File fileToApply) {
    UserException installFailureException = new UserException("message.installError");
    try {/*from   w  w  w .j a  v  a 2  s  .c o m*/
        String[] cmd = new String[] { m_binDir + File.separator + "sipxlocalization", fileToApply.getPath(),
                m_promptsDir, m_regionDir, m_thirdPartyDir };
        Process p = Runtime.getRuntime().exec(cmd);
        BufferedReader scriptErrorReader = new BufferedReader(new InputStreamReader(p.getErrorStream()));
        String errorLine = scriptErrorReader.readLine();
        while (errorLine != null) {
            LOG.warn("sipxlocalization: " + errorLine);
            errorLine = scriptErrorReader.readLine();
        }

        p.waitFor();
        if (p.exitValue() != 0) {
            throw installFailureException;
        }
    } catch (InterruptedException ex) {
        LOG.error("Interrupted when waiting for sipxlocalization script.", ex);
        throw installFailureException;
    } catch (IOException ex) {
        LOG.error("Problems with executing sipxlocalization script.", ex);
        throw installFailureException;
    }
}

From source file:org.craftercms.deployer.git.processor.ShellProcessor.java

@Override
public void doProcess(SiteConfiguration siteConfiguration, PublishedChangeSet changeSet)
        throws PublishingException {
    checkConfiguration(siteConfiguration);
    LOGGER.debug("Starting Shell Processor");
    ProcessBuilder builder = new ProcessBuilder();
    builder.directory(getWorkingDir(workingDir, siteConfiguration.getSiteId()));
    LOGGER.debug("Working directory is " + workingDir);
    HashMap<String, String> argumentsMap = buildArgumentsMap(getFileList(changeSet));
    if (asSingleCommand) {
        StrSubstitutor substitutor = new StrSubstitutor(argumentsMap, "%{", "}");
        String execComand = substitutor.replace(command);
        LOGGER.debug("Command to be Executed is " + execComand);
        builder.command("/bin/bash", "-c", execComand);

    } else {/*from w w  w .  ja  v  a 2  s  .c o m*/
        Set<String> keys = argumentsMap.keySet();
        ArrayList<String> commandAsList = new ArrayList<String>();
        commandAsList.add(command.trim());
        for (String key : keys) {
            if (!key.equalsIgnoreCase(INCLUDE_FILTER_PARAM)) {
                commandAsList.add(argumentsMap.get(key));
            }
        }
        LOGGER.debug("Command to be Executed is " + StringUtils.join(commandAsList, " "));
        builder.command(commandAsList);
    }

    builder.environment().putAll(enviroment);
    builder.redirectErrorStream(true);
    try {
        Process process = builder.start();
        process.waitFor();
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String str;
        while ((str = reader.readLine()) != null) {
            LOGGER.info("PROCESS OUTPUT :" + str);
        }
        reader.close();
        LOGGER.info("Process Finish with Exit Code " + process.exitValue());
        LOGGER.debug("Process Output ");
    } catch (IOException ex) {
        LOGGER.error("Error ", ex);
    } catch (InterruptedException e) {
        LOGGER.error("Error ", e);
    } finally {
        LOGGER.debug("End of Shell Processor");
    }
}

From source file:org.apache.taverna.commandline.TavernaCommandLineTest.java

private synchronized int waitFor(Process process) throws IOException {
    while (true) {
        try {/*  ww  w. j av a  2 s . c  o m*/
            wait(500);
        } catch (InterruptedException e) {
        }
        IOUtils.copy(process.getInputStream(), System.out);
        try {
            return process.exitValue();
        } catch (IllegalThreadStateException e) {
        }
    }
}