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:com.streamsets.pipeline.stage.executor.shell.ShellExecutor.java

private void executeScript(Record record) throws StageException {
    File script = null;/*w ww  .j a  v a 2 s .c  o  m*/
    try {
        script = File.createTempFile("sdc-script-executor", ".sh");
        ELVars variables = getContext().createELVars();
        RecordEL.setRecordInContext(variables, record);

        // Serialize the script into a file on disk (in temporary location)
        FileUtils.writeStringToFile(script, config.script);

        ImmutableList.Builder<String> commandBuilder = new ImmutableList.Builder<>();
        if (impersonationMode != ImpersonationMode.DISABLED) {
            commandBuilder.add(sudo);
            commandBuilder.add("-E");
            commandBuilder.add("-u");
            commandBuilder.add(user);
        }

        commandBuilder.add(shell);
        commandBuilder.add(script.getPath());

        List<String> commandLine = commandBuilder.build();

        // External process configuration
        ProcessBuilder processBuilder = new ProcessBuilder(commandLine);
        for (Map.Entry<String, String> entry : config.environmentVariables.entrySet()) {
            processBuilder.environment().put(eval.eval(variables, entry.getKey(), String.class),
                    eval.eval(variables, entry.getValue(), String.class));
        }

        // Start process and configure forwarders for stderr/stdin
        LOG.debug("Executing script: {}", StringUtils.join(commandLine, " "));
        Process process = processBuilder.start();
        new Thread(new ProcessStdIOForwarder(false, process.getInputStream())).start();
        new Thread(new ProcessStdIOForwarder(true, process.getErrorStream())).start();

        int pid = retrievePidIfFeasible(process);
        LOG.debug("Created process with PID {}", pid);

        // User configures the maximal time for the script execution
        boolean finished = process.waitFor(timeout, TimeUnit.MILLISECONDS);
        if (!finished) {
            process.destroyForcibly();
            throw new OnRecordErrorException(record, Errors.SHELL_002);
        }

        if (process.exitValue() != 0) {
            throw new OnRecordErrorException(record, Errors.SHELL_003, process.exitValue());
        }
    } catch (OnRecordErrorException e) {
        errorRecordHandler.onError(e);
    } catch (Exception e) {
        errorRecordHandler.onError(new OnRecordErrorException(record, Errors.SHELL_001, e.toString(), e));
    } finally {
        if (script != null && script.exists()) {
            script.delete();
        }
    }
}

From source file:com.ah.be.communication.BusinessUtil.java

public static int execCommand(String cmd) {
    try {//from   w  ww .j av a2s  .  c o  m
        String string_Path_Array[] = new String[3];
        string_Path_Array[0] = "bash";
        string_Path_Array[1] = "-c";
        string_Path_Array[2] = cmd;

        Process p = Runtime.getRuntime().exec(string_Path_Array);

        p.waitFor();

        return p.exitValue();
    } catch (Exception e) {
        log.error("execCommand", e);
        return 255;
    }
}

From source file:org.opencastproject.videoeditor.ffmpeg.FFmpegEdit.java

private String run(List<String> params) {
    BufferedReader in = null;/*from www  .  ja v a  2 s.  c  om*/
    Process encoderProcess = null;
    try {
        params.add(0, binary);
        logger.info("executing command: " + StringUtils.join(params, " "));
        ProcessBuilder pbuilder = new ProcessBuilder(params);
        pbuilder.redirectErrorStream(true);
        encoderProcess = pbuilder.start();
        in = new BufferedReader(new InputStreamReader(encoderProcess.getInputStream()));
        String line;
        int n = 5;
        while ((line = in.readLine()) != null) {
            if (n-- > 0)
                logger.info(line);
        }

        // wait until the task is finished
        encoderProcess.waitFor();
        int exitCode = encoderProcess.exitValue();
        if (exitCode != 0) {
            throw new Exception("Ffmpeg exited abnormally with status " + exitCode);
        }

    } catch (Exception ex) {
        logger.error("VideoEditor ffmpeg failed", ex);
        return ex.toString();
    } finally {
        IoSupport.closeQuietly(in);
        IoSupport.closeQuietly(encoderProcess);
    }
    return null;
}

From source file:com.ikanow.aleph2.harvest.logstash.services.LogstashHarvestService.java

/** Runs logstash in test mode before doing anything else, to check its formatting (otherwise deploying the config can crash the entire thread)
 * @param script//from  w  ww.  j a v a  2 s  .  c o  m
 * @param bucket
 * @param config
 * @param globals
 * @return
 */
protected BasicMessageBean validateLogstashConfigBeforeRunning(final String script, final DataBucketBean bucket,
        final LogstashBucketConfigBean config, final LogstashHarvesterConfigBean globals) {

    final ProcessBuilder pb = LogstashUtils.buildLogstashTest(_globals.get(), config, script, 0L,
            Optional.empty());
    try {
        final Process px = pb.start();
        final StringWriter outputAndError = new StringWriter();
        final OutputCollectorService outAndErrorStream = new OutputCollectorService(px.getInputStream(),
                new PrintWriter(outputAndError));
        outAndErrorStream.start();
        if (!px.waitFor(60L, TimeUnit.SECONDS)) { // exited
            px.destroy();
        }
        outAndErrorStream.join();

        int ret_val = px.exitValue();

        return ErrorUtils.buildMessage(ret_val == 0, this.getClass().getSimpleName(),
                "validateLogstashConfigBeforeRunning", outputAndError.toString());
    } catch (Exception e) {
        return ErrorUtils.buildErrorMessage(this.getClass().getSimpleName(),
                "validateLogstashConfigBeforeRunning", ErrorUtils.getLongForm("{0}", e));
    }
}

From source file:com.sastix.cms.common.services.htmltopdf.PdfImpl.java

public byte[] getPDF() throws IOException, InterruptedException {
    ProcessBuilder processBuilder = new ProcessBuilder(getCommandAsArray());
    Process process = processBuilder.start();
    //Runtime runtime = Runtime.getRuntime();
    //Process process = runtime.exec(getCommandAsArray());

    for (Page page : pages) {
        if (page.getType().equals(PageType.htmlAsString)) {
            OutputStream stdInStream = process.getOutputStream();
            stdInStream.write(page.getSource().getBytes("UTF-8"));
            stdInStream.close();//from w  w  w  . ja  v  a  2  s  . c om
        }
    }

    StreamEater outputStreamEater = new StreamEater(process.getInputStream());
    outputStreamEater.start();

    StreamEater errorStreamEater = new StreamEater(process.getErrorStream());
    errorStreamEater.start();

    outputStreamEater.join();
    errorStreamEater.join();
    process.waitFor();

    if (process.exitValue() != 0) {
        throw new RuntimeException("Process (" + getCommand() + ") exited with status code "
                + process.exitValue() + ":\n" + new String(errorStreamEater.getBytes()));
    }

    if (outputStreamEater.getError() != null) {
        throw outputStreamEater.getError();
    }

    if (errorStreamEater.getError() != null) {
        throw errorStreamEater.getError();
    }

    return outputStreamEater.getBytes();
}

From source file:org.codehaus.mojo.osxappbundle.CreateApplicationBundleMojo.java

/**
 * Bundle project as a Mac OS X application bundle.
 * //from  w  ww  .  ja v a2 s  .c  om
 * @throws MojoExecutionException
 *             If an unexpected error occurs during packaging of the bundle.
 */
public void execute() throws MojoExecutionException {

    // Set up and create directories
    buildDirectory.mkdirs();

    File bundleDir = new File(buildDirectory, bundleName + ".app");
    bundleDir.mkdirs();

    File contentsDir = new File(bundleDir, "Contents");
    contentsDir.mkdirs();

    File resourcesDir = new File(contentsDir, "Resources");
    resourcesDir.mkdirs();

    File javaDirectory = new File(resourcesDir, "Java");
    javaDirectory.mkdirs();

    File macOSDirectory = new File(contentsDir, "MacOS");
    macOSDirectory.mkdirs();

    // Copy in the native java application stub
    File stub = new File(macOSDirectory,
            keepJavaApplicationStubName ? javaApplicationStub.getName() : bundleName);
    if (!javaApplicationStub.exists()) {
        String message = "Can't find JavaApplicationStub binary. File does not exist: " + javaApplicationStub;

        if (!isOsX()) {
            message += "\nNOTICE: You are running the osxappbundle plugin on a non OS X platform. To make this work you need to copy the JavaApplicationStub binary into your source tree. Then configure it with the 'javaApplicationStub' configuration property.\nOn an OS X machine, the JavaApplicationStub is typically located under /System/Library/Frameworks/JavaVM.framework/Versions/Current/Resources/MacOS/JavaApplicationStub";
        }

        throw new MojoExecutionException(message);

    } else {
        try {
            FileUtils.copyFile(javaApplicationStub, stub);
        } catch (IOException e) {
            throw new MojoExecutionException(
                    "Could not copy file " + javaApplicationStub + " to directory " + macOSDirectory, e);
        }
    }

    // Copy icon file to the bundle if specified
    if (iconFile != null) {
        try {
            FileUtils.copyFileToDirectory(iconFile, resourcesDir);
        } catch (IOException e) {
            throw new MojoExecutionException("Error copying file " + iconFile + " to " + resourcesDir, e);
        }
    }

    // Resolve and copy in all dependecies from the pom
    List files = copyDependencies(javaDirectory);

    // Create and write the Info.plist file
    File infoPlist = new File(bundleDir, "Contents/Info.plist");
    writeInfoPlist(infoPlist, files);

    // Copy specified additional resources into the top level directory
    if (additionalResources != null && !additionalResources.isEmpty()) {
        copyResources(additionalResources);
    }

    if (isOsX()) {
        // Make the stub executable
        Commandline chmod = new Commandline();
        try {
            chmod.setExecutable("chmod");
            chmod.createArg().setValue("755");
            chmod.createArg().setValue(stub.getAbsolutePath());

            chmod.execute();
        } catch (CommandLineException e) {
            throw new MojoExecutionException("Error executing " + chmod + " ", e);
        }

        // This makes sure that the .app dir is actually registered as an application bundle
        if (new File(SET_FILE_PATH).exists()) {
            Commandline setFile = new Commandline();
            try {
                setFile.setExecutable(SET_FILE_PATH);
                setFile.createArg().setValue("-a B");
                setFile.createArg().setValue(bundleDir.getAbsolutePath());

                getLog().info("executing " + setFile.toString());
                setFile.execute();
            } catch (CommandLineException e) {
                throw new MojoExecutionException("Error executing " + setFile, e);
            }
        } else {
            getLog().warn("Could  not set 'Has Bundle' attribute. " + SET_FILE_PATH
                    + " not found, is Developer Tools installed?");
        }
        // sign the code (if set up)

        if (codesignIdentity.length() > 0 && !keepJavaApplicationStubName) {
            Commandline codesign = new Commandline();
            try {
                codesign.setExecutable("codesign");
                codesign.createArg().setValue("-s");
                codesign.createArg().setValue(codesignIdentity);
                if (codesignIdentifier.length() > 0) {
                    codesign.createArg().setValue("-i");
                    codesign.createArg().setValue(codesignIdentifier);
                }
                codesign.createArg().setValue("-f");
                codesign.createArg().setValue("-vvvv");

                if (codesignKeychain.length() > 0) {
                    codesign.createArg().setValue("--keychain");
                    codesign.createArg().setValue(codesignKeychain);
                }

                // need to escape spaces
                codesign.createArg().setValue(bundleDir.getAbsolutePath().replaceAll(" ", "\\ "));

                getLog().info("executing " + codesign.toString());
                Process process = codesign.execute();

                process.waitFor();

                int result = process.exitValue();
                if (result == 0) {
                    getLog().info("codesign completed successfully");
                } else {

                    StringBuffer buffer = new StringBuffer();
                    buffer.append("codesign failed with exit code: ");
                    buffer.append(result);
                    buffer.append("\n");
                    if (getLog().isDebugEnabled()) {
                        buffer.append(
                                "Verify that the CFBundleExecutable and other Info.plits properties are correct, also check the availability of your certificates in the keychains.\n");
                    } else {
                        buffer.append("retry with 'mvn -X' to get more info");
                    }
                    buffer.append("Error message: ");
                    buffer.append(IOUtils.toString(process.getErrorStream()));
                    if (getLog().isDebugEnabled()) {
                        Commandline debug = new Commandline();
                        debug.setExecutable("security");
                        debug.createArg().setValue("list-keychains");

                        Process process2 = debug.execute();
                        process.waitFor();
                        buffer.append("\nSearched keychains:\n");
                        buffer.append(IOUtils.toString(process2.getInputStream()));
                    }

                    getLog().warn(buffer.toString());

                }
            } catch (CommandLineException e) {
                throw new MojoExecutionException("Error signing the application " + bundleDir.getAbsolutePath()
                        + " with keychain/identity " + codesignKeychain + "/" + codesignIdentity, e);
            } catch (IOException e) {
                throw new MojoExecutionException("blah", e);
            } catch (InterruptedException e) {
                getLog().warn("codesign failed, process interrupted", e);
            }

        }

        // Create a .dmg file of the app
        Commandline dmg = new Commandline();
        try {
            dmg.setExecutable("hdiutil");
            dmg.createArg().setValue("create");
            dmg.createArg().setValue("-srcfolder");
            dmg.createArg().setValue(buildDirectory.getAbsolutePath());
            dmg.createArg().setValue(diskImageFile.getAbsolutePath());
            try {
                dmg.execute().waitFor();
            } catch (InterruptedException e) {
                throw new MojoExecutionException("Thread was interrupted while creating DMG " + diskImageFile,
                        e);
            }
        } catch (CommandLineException e) {
            throw new MojoExecutionException("Error creating disk image " + diskImageFile, e);
        }
        if (internetEnable) {
            try {

                Commandline internetEnable = new Commandline();

                internetEnable.setExecutable("hdiutil");
                internetEnable.createArg().setValue("internet-enable");
                internetEnable.createArg().setValue("-yes");
                internetEnable.createArg().setValue(diskImageFile.getAbsolutePath());

                internetEnable.execute();
            } catch (CommandLineException e) {
                throw new MojoExecutionException("Error internet enabling disk image: " + diskImageFile, e);
            }
        }
        projectHelper.attachArtifact(project, "dmg", null, diskImageFile);
    }

    zipArchiver.setDestFile(zipFile);
    try {
        String[] stubPattern = { buildDirectory.getName() + "/" + bundleDir.getName() + "/Contents/MacOS/"
                + (keepJavaApplicationStubName ? javaApplicationStub.getName() : bundleName) };

        zipArchiver.addDirectory(buildDirectory.getParentFile(),
                new String[] { buildDirectory.getName() + "/**" }, stubPattern);

        DirectoryScanner scanner = new DirectoryScanner();
        scanner.setBasedir(buildDirectory.getParentFile());
        scanner.setIncludes(stubPattern);
        scanner.scan();

        String[] stubs = scanner.getIncludedFiles();
        for (int i = 0; i < stubs.length; i++) {
            String s = stubs[i];
            zipArchiver.addFile(new File(buildDirectory.getParentFile(), s), s, 0755);
        }

        zipArchiver.createArchive();
        projectHelper.attachArtifact(project, "zip", null, zipFile);
    } catch (ArchiverException e) {
        throw new MojoExecutionException("Could not create zip archive of application bundle in " + zipFile, e);
    } catch (IOException e) {
        throw new MojoExecutionException("IOException creating zip archive of application bundle in " + zipFile,
                e);
    }

}

From source file:com.clican.pluto.orm.dynamic.impl.DynamicORMManagePojoHibernateImpl.java

private void compile(String file) throws ORMManageException {
    Process proc = null;
    try {//w  w w.  j  a  v a2s . c o  m
        Set<String> jars = classLoaderUtil.getRuntimeJars();
        StringBuffer command = new StringBuffer();
        command.append("javac ");
        command.append(file);
        command.append("/*.java -encoding utf-8 -classpath \"");
        command.append(StringUtils.getSymbolSplitString(jars, ";"));
        command.append("\"");
        if (log.isDebugEnabled()) {
            log.debug("command=" + command);
        }
        proc = Runtime.getRuntime().exec(command.toString());
        int exitValue = -1;
        while (true) {
            try {
                exitValue = proc.exitValue();
            } catch (IllegalThreadStateException e) {
                Thread.sleep(10);
                continue;
            }
            break;
        }
        if (exitValue != 0) {
            log.error("Compile failure command=[" + command + "]");
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Compile successfully.");
            }
        }
    } catch (Exception e) {
        throw new ORMManageException(e);
    } finally {
        proc.destroy();
    }
}

From source file:org.opencastproject.composer.impl.AbstractCmdlineEmbedderEngine.java

/**
 * /*w  w  w . j av  a2  s  .  c  om*/
 * {@inheritDoc} Language attribute is normalized via <code>normalizeLanguage</code> method even if it is not present.
 * If normalized language returned is <code>null</code>, exception will be thrown.
 * 
 * @see org.opencastproject.composer.api.EmbedderEngine#embed(java.io.File, java.io.File, java.util.Map)
 */
@Override
public File embed(File mediaSource, File[] captionSources, String[] captionLanguages,
        Map<String, String> properties) throws EmbedderException {

    if (mediaSource == null) {
        logger.error("Media source is missing");
        throw new EmbedderException("Missing media source.");
    }
    if (captionSources == null || captionSources.length == 0) {
        logger.error("Captions are missing");
        throw new EmbedderException("Missing captions.");
    }
    if (captionLanguages == null || captionLanguages.length == 0) {
        logger.error("Caption languages are missing");
        throw new EmbedderException("Missing caption language codes.");
    }

    // add all properties
    Map<String, String> embedderProperties = new HashMap<String, String>();
    embedderProperties.putAll(properties);

    // add file properties
    embedderProperties.put("in.media.path", mediaSource.getAbsolutePath());
    embedderProperties.put("out.media.path", mediaSource.getAbsoluteFile().getParent() + File.separator
            + UUID.randomUUID() + "-caption." + FilenameUtils.getExtension(mediaSource.getAbsolutePath()));

    for (int i = 0; i < ((captionSources.length > captionLanguages.length) ? captionSources.length
            : captionLanguages.length); i++) {
        embedderProperties.put("in.captions.path." + i, captionSources[i].getAbsolutePath());
        // check/normalize language property
        String language = normalizeLanguage(captionLanguages[i]);
        if (language == null) {
            logger.error("Language property was set to null.");
            throw new EmbedderException("Captions language has not been set.");
        }
        embedderProperties.put("param.lang." + i, language);
    }

    // execute command
    List<String> commandList = buildCommandFromTemplate(embedderProperties);

    logger.debug("Executing embedding command {}", commandList);

    Process embedderProcess = null;
    BufferedReader processReader = null;
    // create and start process
    try {
        ProcessBuilder pb = new ProcessBuilder(commandList);
        pb.redirectErrorStream(true);

        embedderProcess = pb.start();

        // process embedder output
        processReader = new BufferedReader(new InputStreamReader(embedderProcess.getInputStream()));
        String line = null;
        while ((line = processReader.readLine()) != null) {
            handleEmbedderOutput(line);
        }

        embedderProcess.waitFor();
        int exitCode = embedderProcess.exitValue();
        if (exitCode != 0) {
            throw new EmbedderException("Embedder exited abnormally with error code: " + exitCode);
        }

        return getOutputFile(embedderProperties);

    } catch (Exception e) {
        logger.error(e.getMessage());
        throw new EmbedderException(e);
    } finally {
        IoSupport.closeQuietly(processReader);
        IoSupport.closeQuietly(embedderProcess);
    }
}

From source file:com.hortonworks.streamline.streams.actions.storm.topology.StormTopologyActionsImpl.java

private ShellProcessResult executeShellProcess(List<String> commands) throws Exception {
    LOG.debug("Executing command: {}", Joiner.on(" ").join(commands));
    ProcessBuilder processBuilder = new ProcessBuilder(commands);
    processBuilder.redirectErrorStream(true);
    Process process = processBuilder.start();
    StringWriter sw = new StringWriter();
    IOUtils.copy(process.getInputStream(), sw, Charset.defaultCharset());
    String stdout = sw.toString();
    process.waitFor();/* w  ww  .  j av a2  s  .  c  o  m*/
    int exitValue = process.exitValue();
    LOG.debug("Command output: {}", stdout);
    LOG.debug("Command exit status: {}", exitValue);
    return new ShellProcessResult(exitValue, stdout);
}

From source file:com.datasalt.pangool.solr.SolrRecordWriter.java

private Path findSolrConfig(Configuration conf) throws IOException {
    Path solrHome = null;/*from   www .j  ava 2s  .  com*/

    // we added these lines to make this patch work on Hadoop 0.20.2
    FileSystem localFs = FileSystem.getLocal(conf);
    if (FileSystem.get(conf).equals(localFs)) {
        return new Path(localSolrHome);
    }
    // end-of-addition
    Path[] localArchives = DistributedCache.getLocalCacheArchives(conf);

    if (localArchives.length == 0) {
        throw new IOException(String.format("No local cache archives, where is %s", zipName));
    }
    for (Path unpackedDir : localArchives) {
        // Only logged if debugging
        if (LOG.isDebugEnabled()) {
            LOG.debug(String.format("Examining unpack directory %s for %s", unpackedDir, zipName));

            ProcessBuilder lsCmd = new ProcessBuilder(
                    new String[] { "/bin/ls", "-lR", unpackedDir.toString() });
            lsCmd.redirectErrorStream();
            Process ls = lsCmd.start();
            try {
                byte[] buf = new byte[16 * 1024];
                InputStream all = ls.getInputStream();
                int count;
                while ((count = all.read(buf)) > 0) {
                    System.err.write(buf, 0, count);
                }
            } catch (IOException ignore) {
            }
            System.err.format("Exit value is %d%n", ls.exitValue());
        }
        if (unpackedDir.getName().equals(zipName)) {

            solrHome = unpackedDir;
            break;
        }
    }
    return solrHome;
}