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.ednovo.gooru.application.converter.GooruImageUtil.java

public void scaleImageUsingImageMagick(String srcFilePath, int width, int height, String destFilePath)
        throws Exception {
    try {/*w w  w  . j  av  a2 s.com*/
        String resizeCommand = new String(
                "/usr/bin/gm@convert@" + srcFilePath + "@-resize@" + width + X + height + "@" + destFilePath);
        String cmdArgs[] = resizeCommand.split("@");
        Process thumsProcess = Runtime.getRuntime().exec(cmdArgs);
        thumsProcess.waitFor();

        String line;
        StringBuffer sb = new StringBuffer();

        BufferedReader in = new BufferedReader(new InputStreamReader(thumsProcess.getInputStream()));
        while ((line = in.readLine()) != null) {
            sb.append(line).append("\n");
        }
        in.close();

        logger.info("output : {} -  Status : {} - Command : " + StringUtils.join(cmdArgs, " "), sb.toString(),
                thumsProcess.exitValue() + "");

    } catch (Exception e) {
        logger.error("something went wrong while converting image", e);
    }

}

From source file:gda.device.detector.mythen.client.TextClientMythenClient.java

private MythenTextClientExecResult execProcess(String... args) throws DeviceException {

    if (!EXEC_LOCK.tryLock()) {
        throw new DeviceException("Cannot acquire: client is already running");
    }/*w ww.j ava  2 s .  c o  m*/

    try {
        MythenTextClientExecResult result = new MythenTextClientExecResult();

        // Build argument list
        List<String> argList = new Vector<String>();
        argList.add(host);
        argList.addAll(Arrays.asList(args));
        logger.info("Starting acquisition");
        logger.debug("Executing Mythen client with args " + argList);

        // Prepend executable name to argument list
        argList.add(0, mythenClientCommand);

        ProcessBuilder pb = new ProcessBuilder(argList);
        try {
            Process p = pb.start();
            BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
            try {
                logger.debug("wait for TextClient to complete data acquisition ...");
                p.waitFor();
                logger.debug("TextClient returned.");
            } catch (InterruptedException e) {
                throw new DeviceException("Unable to wait for text client to finish", e);
            }

            result.output = FileCopyUtils.copyToString(br);

            result.exitValue = p.exitValue();
            if (result.exitValue != 0) {
                throw new DeviceException(
                        String.format("Client exited with non-zero status: %d", result.exitValue));
            }
            InterfaceProvider.getTerminalPrinter().print("Save to file " + this.params.getFilename());
            logger.info("Acquisition completed successfully");
            logger.debug("Client successfully exited with status code " + result.exitValue);

            return result;

        } catch (IOException e) {
            throw new DeviceException("Client operation failed", e);
        }
    } finally {
        EXEC_LOCK.unlock();
    }
}

From source file:org.codesearch.commons.plugins.vcs.GitLocalPlugin.java

private byte[] executeCommand(String... commands) throws VersionControlPluginException {
    try {/*from   w  w w. ja v  a 2s . c o m*/
        Process process = null;

        synchronized (this) {
            processBuilder = new ProcessBuilder();
            processBuilder.directory(branchDirectory);
            processBuilder.command(commands);
            LOG.debug("Executing command: " + processBuilder.command());
            process = processBuilder.start();

            byte[] output = IOUtils.toByteArray(process.getInputStream());

            process.waitFor();
            if (process.exitValue() != 0) {
                throw new VersionControlPluginException("Command returned error code: " + process.exitValue()
                        + "\n    Output: " + IOUtils.toString(process.getErrorStream()));
            }
            cleanupProcess(process);

            return output;
        }
    } catch (InterruptedException ex) {
        throw new VersionControlPluginException("Execution of command interrupted by operating system");
    } catch (IOException ex) {
        throw new VersionControlPluginException("Error executing command: " + ex);
    }
}

From source file:org.eclipse.xtend.util.stdlib.SystemCommand.java

@Override
protected void invokeInternal(final WorkflowContext ctx, final ProgressMonitor monitor, final Issues issues) {
    try {/* w  w w . j  a  v a  2 s .co  m*/
        int rc;
        final List<String> pbArgs = new ArrayList<String>();
        pbArgs.add(command);
        pbArgs.addAll(args);
        final ProcessBuilder pb = new ProcessBuilder(pbArgs);
        if (directory != null) {
            pb.directory(directory);
        }
        for (final String env : enventry) {
            final String[] keyvalue = env.split(",");
            pb.environment().put(keyvalue[0], keyvalue[1]);
        }
        if (inheritEnvironment) {
            log.debug("Inheriting system environment.");
            pb.environment().putAll(System.getenv());
        }
        if (log.isDebugEnabled()) {
            log.debug("Environment:");
            log.debug(pb.environment());
            log.debug(System.getenv());
        }
        log.info("Running command '" + pb.command() + "' in directory " + pb.directory().getAbsolutePath()
                + " ...");
        final Process p = pb.start();
        BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));

        String lineRead;
        while ((lineRead = br.readLine()) != null) {
            log.info(lineRead);
        }

        br = new BufferedReader(new InputStreamReader(p.getErrorStream()));
        while ((lineRead = br.readLine()) != null) {
            log.error(lineRead);
        }
        rc = p.waitFor();
        if (rc != 0) {
            issues.addError("Error running '" + command + "'");
            return;
        }
        rc = p.exitValue();
        if (rc != 0) {
            issues.addError("Execution of command failed with error.");

        } else {
            log.info("Execution of command was successful.");
        }
    } catch (final Exception re) {
        issues.addError("Runtime error: " + re.getMessage());
    }
}

From source file:de.mpg.escidoc.services.extraction.ExtractionChain.java

public ExtractionResult doExtract(String infileName, String outfileName) {
    File outfile = new File(outfileName);

    Date stepStart = new Date();
    Date current;/*from   w  ww.j a v a 2s.  co  m*/

    logger.info("Extracting PDF content ----------------------------------------");
    logger.info("Infile: " + infileName);
    logger.info("Outfile: " + outfileName);

    logger.info(stepStart + " -- started");

    // xPDF

    try {
        logger.info("Extracting with xPDF");

        StringBuffer command = new StringBuffer(2048);
        command.append(System.getProperty("os.name").contains("Windows") ? pdftotext + " -enc UTF-8 "
                : "/usr/bin/pdftotext -enc UTF-8 ");
        command.append(infileName);
        command.append(" ");
        command.append(outfileName);

        Process proc = Runtime.getRuntime().exec(command.toString());

        StreamGobbler inputGobbler = new StreamGobbler(proc.getInputStream(), "xPDF");
        StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "xPDF");

        inputGobbler.start();
        errorGobbler.start();

        int exitCode = proc.waitFor();

        if (proc.exitValue() == 0) {

            if (verbose) {
                BufferedReader bufferedReader = new BufferedReader(
                        new InputStreamReader(new FileInputStream(outfile), "UTF-8"));
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    logger.info(line);
                }
                bufferedReader.close();
            }
            current = new Date();
            logger.info(current + " -- finished successfully");
            logger.info("Extraction took " + (current.getTime() - stepStart.getTime()));

            return ExtractionResult.OK;
        }
    } catch (Exception e) {
        logger.warn("Error extracting PDF with xPDF:");
        logger.warn(e.getStackTrace());
    }

    current = new Date();
    logger.info(current + " -- finished unsuccessfully");
    logger.info("Extraction attempt took " + (current.getTime() - stepStart.getTime()));

    // PDFBox
    try {
        logger.info("Extracting with PDFBox");
        stepStart = new Date();

        StringBuffer command = new StringBuffer(1024);
        command.append(System.getProperty("os.name").contains("Windows")
                ? "java -Dfile.encoding=UTF-8 -jar " + pdfboxAppJar + " ExtractText "
                : "/usr/bin/java -Dfile.encoding=UTF-8 -jar " + pdfboxAppJar + " ExtractText ");
        command.append(infileName);
        command.append(" ");
        command.append(outfileName);

        Process proc = Runtime.getRuntime().exec(command.toString());
        StreamGobbler inputGobbler = new StreamGobbler(proc.getInputStream(), "PDFBox");
        StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "PDFBox");

        inputGobbler.start();
        errorGobbler.start();

        int exitCode = proc.waitFor();

        if (exitCode == 0) {

            if (verbose) {
                BufferedReader bufferedReader = new BufferedReader(
                        new InputStreamReader(new FileInputStream(outfile), "UTF-8"));
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    logger.info(line);
                }
                bufferedReader.close();
            }
            current = new Date();
            logger.info(current + " -- finished successfully");
            logger.info("Extraction took " + (current.getTime() - stepStart.getTime()));

            return ExtractionResult.OK;
        }
    } catch (Exception e) {
        logger.warn("Error extracting PDF with PDFBox:");
        logger.warn(e.getStackTrace());
    }

    current = new Date();
    logger.info(current + " -- finished unsuccessfully");
    logger.info("Extraction attempt took " + (current.getTime() - stepStart.getTime()));

    // iText
    try {
        logger.info("Extracting with iText");
        stepStart = new Date();

        PdfReader reader = new PdfReader(infileName);
        int numberOfPages = reader.getNumberOfPages();

        outputStreamWriter = new OutputStreamWriter(new FileOutputStream(outfile), "UTF-8");
        for (int i = 0; i < numberOfPages; i++) {
            outputStreamWriter.write(PdfTextExtractor.getTextFromPage(reader, i + 1));
        }

        if (verbose) {
            BufferedReader bufferedReader = new BufferedReader(
                    new InputStreamReader(new FileInputStream(outfile), "UTF-8"));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                logger.info(line);
            }
            bufferedReader.close();
        }

        current = new Date();
        logger.info(current + " -- finished successfully");
        logger.info("Extraction took " + (current.getTime() - stepStart.getTime()));

        return ExtractionResult.OK;

    } catch (Exception e) {
        logger.warn("Error extracting PDF with iText:", e);
    }

    // tika

    InputStream stream = null;

    try {
        logger.info("Extracting with Tika");
        stepStart = new Date();

        stream = TikaInputStream.get(new File(infileName));

        ContentHandler handler = new BodyContentHandler(TIKA_CONTENT_SIZE);

        new AutoDetectParser().parse(stream, handler, new Metadata(), new ParseContext());

        String content = handler.toString();

        FileUtils.writeStringToFile(outfile, content);

        stream.close();

        if (verbose) {
            BufferedReader bufferedReader = new BufferedReader(
                    new InputStreamReader(new FileInputStream(outfile), "UTF-8"));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                logger.info(line);
            }
            bufferedReader.close();
        }

        current = new Date();
        logger.info(current + " -- finished successfully");
        logger.info("Extraction took " + (current.getTime() - stepStart.getTime()));

        return ExtractionResult.OK;

    } catch (Exception e) {
        logger.warn("Error extracting Tika:", e);
        try {
            stream.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }

    current = new Date();
    logger.warn(current + " -- finished unsuccessfully");
    logger.info("Extraction attempt took " + (current.getTime() - stepStart.getTime()));

    logger.info("... giving up");

    return ExtractionResult.FAILURE;
}

From source file:com.shubhangrathore.xposed.xhover.MainActivity.java

/**
 * Restarts SystemUI. Requires SuperUser privilege.
 *
 * @return boolean true if successful, else false.
 *//*from   ww  w . ja v  a  2s .  co  m*/
private boolean restartSystemUi() {
    boolean mSuccessful;
    try {
        Process mProcess = Runtime.getRuntime().exec("su");
        DataOutputStream mDataOutputStream = new DataOutputStream(mProcess.getOutputStream());
        mDataOutputStream.writeBytes("pkill com.android.systemui \n");
        mDataOutputStream.writeBytes("exit\n");
        mDataOutputStream.flush();
        // We wait for the command to be completed
        // before moving forward. This ensures that the method
        // returns only after all the commands' execution is complete.
        mProcess.waitFor();

        if (mProcess.exitValue() == 1) {
            // If control is here, that means the sub process has returned
            // an unsuccessful exit code.
            // Most probably, SuperUser permission was denied
            Log.e(TAG, "Utilities: SuperUser permission denied. Unable to restart SystemUI.");
            mSuccessful = false;
        } else {
            // SuperUser permission granted
            Log.i(TAG, "Utilities: SuperUser permission granted. SystemUI restarted.");
            mSuccessful = true;
        }
    } catch (IOException e) {
        Log.e(TAG, "restartSystemUI: I/O exception");
        mSuccessful = false;
    } catch (InterruptedException e) {
        Log.e(TAG, "restartSystemUI: InterruptedException exception");
        mSuccessful = false;
    }
    return mSuccessful;
}

From source file:org.opencb.cellbase.lib.loader.MongoDBCellBaseLoader.java

protected boolean runCreateIndexProcess(Path indexFilePath) throws IOException, InterruptedException {
    //        DatabaseProperties mongodbCredentials = cellBaseConfiguration.getDatabases().get("mongodb");
    DatabaseCredentials mongodbCredentials = cellBaseConfiguration.getDatabases().getMongodb();
    List<String> args = new ArrayList<>();
    args.add("mongo");
    args.add("--host");
    args.add(mongodbCredentials.getHost());
    if (mongodbCredentials.getUser() != null && !mongodbCredentials.getUser().equals("")) {
        args.addAll(Arrays.asList("-u", mongodbCredentials.getUser(), "-p", mongodbCredentials.getPassword()));
    }//from  ww w  .  j a  v  a  2s  .co  m
    if (cellBaseConfiguration != null
            && mongodbCredentials.getOptions().get("authenticationDatabase") != null) {
        args.add("--authenticationDatabase");
        args.add(mongodbCredentials.getOptions().get("authenticationDatabase"));
        logger.debug("MongoDB 'authenticationDatabase' database parameter set to '{}'",
                mongodbCredentials.getOptions().get("authenticationDatabase"));
    }
    args.add(database);
    args.add(indexFilePath.toString());

    ProcessBuilder processBuilder = new ProcessBuilder(args);
    logger.debug("Executing command: '{}'", StringUtils.join(processBuilder.command(), " "));

    //        processBuilder.redirectErrorStream(true);
    //        if (logFilePath != null) {
    //            processBuilder.redirectOutput(ProcessBuilder.Redirect.appendTo(new File(logFilePath)));
    //        }

    Process process = processBuilder.start();
    process.waitFor();

    // Check process output
    boolean executedWithoutErrors = true;
    int genomeInfoExitValue = process.exitValue();
    if (genomeInfoExitValue != 0) {
        logger.warn("Error executing {}, error code: {}", indexFilePath, genomeInfoExitValue);
        executedWithoutErrors = false;
    }
    return executedWithoutErrors;
}

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  w  w  w.  j  a  va2  s. c  o  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:org.apache.slider.server.services.security.CertificateManager.java

/**
 * Runs os command//from  ww w.j  a  va  2s  . com
 *
 * @return command execution exit code
 */
private int runCommand(String command) throws SliderException {
    int exitCode = -1;
    String line = null;
    Process process = null;
    BufferedReader br = null;
    try {
        process = Runtime.getRuntime().exec(command);
        StreamConsumer outputConsumer = new StreamConsumer(process.getInputStream(), true);
        StreamConsumer errorConsumer = new StreamConsumer(process.getErrorStream());

        outputConsumer.start();
        errorConsumer.start();

        try {
            process.waitFor();
            SecurityUtils.logOpenSslExitCode(command, process.exitValue());
            exitCode = process.exitValue();
            if (exitCode != 0) {
                throw new SliderException(exitCode, "Error running command %s", command);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
    }

    return exitCode;//some exception occurred

}

From source file:net.sf.mavenjython.JythonMojo.java

public void runJythonScriptOnInstall(File outputDirectory, List<String> args) throws MojoExecutionException {
    getLog().info("running " + args + " in " + outputDirectory);
    ProcessBuilder pb = new ProcessBuilder(args);
    pb.directory(outputDirectory);//from w  w w .ja v a2 s  .c o  m
    final Process p;
    try {
        p = pb.start();
    } catch (IOException e) {
        throw new MojoExecutionException("Executing jython failed. tried to run: " + pb.command(), e);
    }
    copyIO(p.getInputStream(), System.out);
    copyIO(p.getErrorStream(), System.err);
    copyIO(System.in, p.getOutputStream());
    try {
        if (p.waitFor() != 0) {
            throw new MojoExecutionException("Jython failed with return code: " + p.exitValue());
        }
    } catch (InterruptedException e) {
        throw new MojoExecutionException("Python tests were interrupted", e);
    }

}