Example usage for org.apache.commons.exec Executor isFailure

List of usage examples for org.apache.commons.exec Executor isFailure

Introduction

In this page you can find the example usage for org.apache.commons.exec Executor isFailure.

Prototype

boolean isFailure(final int exitValue);

Source Link

Document

Checks whether exitValue signals a failure.

Usage

From source file:de.pawlidi.openaletheia.utils.exec.ProcessExecutor.java

/**
 * Execute given system command with arguments.
 * /* ww  w  .  j  av a  2 s.c om*/
 * @param command
 *            to execute
 * @param args
 *            as command arguments
 * @return command output as String, null otherwise
 */
public static String executeCommand(final String command, String... args) {
    if (StringUtils.isNotEmpty(command)) {

        // create string output for executor
        ProcessStringOutput processOutput = new ProcessStringOutput(PROCESS_OUTPUT_LEVEL);
        // create external process
        Executor executor = createExecutor(processOutput);

        // create command line without any arguments
        final CommandLine commandLine = new CommandLine(command);

        if (ArrayUtils.isNotEmpty(args)) {
            // add command arguments
            commandLine.addArguments(args);
        }
        int exitValue = -1;

        try {
            // execute command
            exitValue = executor.execute(commandLine);
        } catch (IOException e) {
            // ignore exception
        }

        if (!executor.isFailure(exitValue)) {
            return processOutput.getOutput();
        }
    }
    return null;
}

From source file:cc.arduino.contributions.packages.ContributionInstaller.java

private void executeScripts(File folder, Collection<File> postInstallScripts, boolean trusted, boolean trustAll)
        throws IOException {
    File script = postInstallScripts.iterator().next();

    if (!trusted && !trustAll) {
        System.err.println(/*from   w  w  w.  j  a  v  a  2 s .c om*/
                I18n.format(tr("Warning: non trusted contribution, skipping script execution ({0})"), script));
        return;
    }

    if (trustAll) {
        System.err.println(I18n.format(tr("Warning: forced untrusted script execution ({0})"), script));
    }

    ByteArrayOutputStream stdout = new ByteArrayOutputStream();
    ByteArrayOutputStream stderr = new ByteArrayOutputStream();
    Executor executor = new DefaultExecutor();
    executor.setStreamHandler(new PumpStreamHandler(stdout, stderr));
    executor.setWorkingDirectory(folder);
    executor.setExitValues(null);
    int exitValue = executor.execute(new CommandLine(script));
    executor.setExitValues(new int[0]);

    System.out.write(stdout.toByteArray());
    System.err.write(stderr.toByteArray());

    if (executor.isFailure(exitValue)) {
        throw new IOException();
    }
}

From source file:com.thinkbiganalytics.spark.shell.MultiUserProcessManager.java

/**
 * Calls kinit to request a new Kerberos ticket if the previous one is about to expire.
 *///from  w w w. ja  v a2s  .  c  o  m
private void refreshKerberosTicket() {
    // Determine if a new ticket is needed
    if (kerberos == null || kerberos.getInitInterval() <= 0
            || kerberosNextInit > DateTimeUtils.currentTimeMillis()) {
        return;
    }

    // Build executor
    final Executor executor = new DefaultExecutor();

    final ShutdownHookProcessDestroyer processDestroyer = new ShutdownHookProcessDestroyer();
    executor.setProcessDestroyer(processDestroyer);

    final Logger outputLogger = LoggerFactory.getLogger(getClass().getName() + ".kinit");
    final LoggerOutputStream outputStream = new LoggerOutputStream(outputLogger);
    final PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
    executor.setStreamHandler(streamHandler);

    final ExecuteWatchdog watchdog = new ExecuteWatchdog(TimeUnit.SECONDS.toMillis(kerberos.getInitTimeout()));
    executor.setWatchdog(watchdog);

    // Run kinit to acquire a new ticket
    final CommandLine command = new CommandLine("kinit").addArgument("-kt")
            .addArgument(kerberos.getKeytabLocation()).addArgument(kerberos.getKerberosPrincipal());
    log.debug("Acquiring a new Kerberos ticket with command: {}", command);

    int exitCode;
    try {
        exitCode = executor.execute(command);
    } catch (final IOException e) {
        log.error("Failed to execute kinit", e);
        exitCode = -1;
    }

    // Record next time to acquire ticket
    if (!executor.isFailure(exitCode)) {
        kerberosNextInit = DateTimeUtils.currentTimeMillis()
                + TimeUnit.SECONDS.toMillis(kerberos.getInitInterval());
    } else {
        if (watchdog.killedProcess()) {
            log.error("Failed to acquire a Kerberos ticket within the allotted time: {}",
                    kerberos.getInitTimeout());
        } else {
            log.error("Kinit exited with non-zero status: {}", exitCode);
        }
        kerberosNextInit = DateTimeUtils.currentTimeMillis()
                + TimeUnit.SECONDS.toMillis(kerberos.getRetryInterval());
        throw new IllegalStateException("Failed to acquire a Kerberos ticket");
    }
}

From source file:gov.nasa.jpl.magicdraw.projectUsageIntegrity.graph.SSCAEProjectUsageGraph.java

public BufferedImageFile convertDOTFile(@Nonnull File pugDOT, @Nonnull DOTImageFormat dotImageFormat)
        throws IIOException, IOException, InterruptedException {
    String dotCommand = ProjectUsageIntegrityPlugin.getInstance().getDOTexecutablePath();
    if (null == dotCommand)
        return null;

    File pugTemp = pugDOT.getParentFile();
    File pugImage = new File(pugTemp.getAbsoluteFile() + File.separator + project.getID() + "."
            + DOTImageFormatName.get(dotImageFormat));
    if (pugImage.exists()) {
        pluginLog.info(String.format("%s - convertDOTFile - deleting previous image for '%s' : '%s'",
                pluginName, project.getName(), pugImage.getName()));
        pugImage.delete();/*from ww  w.  ja  va  2s .  c  om*/
    }

    CommandLine cmdLine = new CommandLine(dotCommand);
    cmdLine.addArgument("-Tpng");
    cmdLine.addArgument("-o");
    cmdLine.addArgument(pugImage.getName());
    cmdLine.addArgument(pugDOT.getName());

    pluginLog.info(String.format("%s - convertDOTgraph - converting gv to image for '%s'", pluginName,
            project.getName()));

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

    ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 1000);

    // consider '0' exit value as success.
    Executor executor = new DefaultExecutor();
    executor.setExitValue(0);
    executor.setWatchdog(watchdog);
    executor.setWorkingDirectory(pugTemp);
    executor.execute(cmdLine, resultHandler);

    resultHandler.waitFor();

    if (!executor.isFailure(resultHandler.getExitValue())) {
        pluginLog.info(String.format("%s - convertDOTgraph - reading image for '%s' from: '%s'", pluginName,
                project.getName(), pugImage.getName()));
        BufferedImageFile imageFile = new BufferedImageFile(pugImage);

        pluginLog.info(
                String.format("%s - convertDOTgraph - got image for '%s'", pluginName, project.getName()));
        return imageFile;
    }

    return null;
}

From source file:gov.nasa.jpl.magicdraw.projectUsageIntegrity.graph.SSCAEProjectUsageGraph.java

/**
 * @param pugDOT gv file//  w ww.  ja  v  a  2 s.c om
 * @return true if the graphviz application was opened successfully for the gv file.
 * @throws IIOException
 * @throws IOException
 * @throws InterruptedException
 */
public boolean openDOTFileWithGraphViz(@Nonnull File pugDOT)
        throws IIOException, IOException, InterruptedException {
    String graphvizApp = ProjectUsageIntegrityPlugin.getInstance().getGraphvizApplicationPath();
    if (null == graphvizApp)
        return false;

    File pugTemp = pugDOT.getParentFile();

    CommandLine cmdLine;

    switch (SSCAEProjectUsageIntegrityOptions.getCurrentPlatform()) {
    case LINUX:
        cmdLine = new CommandLine(graphvizApp);
        break;
    case MACOSX:
        cmdLine = new CommandLine("/usr/bin/open");
        cmdLine.addArgument("-a");
        cmdLine.addArgument(graphvizApp);
        break;
    case WINDOWS:
        cmdLine = new CommandLine("cmd");
        cmdLine.addArgument("/c");
        cmdLine.addArgument("start");
        cmdLine.addArgument(graphvizApp);
        break;
    default:
        return false;
    }
    cmdLine.addArgument(pugDOT.getName());

    pluginLog.info(String.format("%s - openDOTFileWithGraphViz - opening DOT file for project: '%s'",
            pluginName, project.getName()));

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

    ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 1000);

    // consider '0' exit value as success.
    Executor executor = new DefaultExecutor();
    executor.setExitValue(0);
    executor.setWatchdog(watchdog);
    executor.setWorkingDirectory(pugTemp);
    executor.execute(cmdLine, resultHandler);

    resultHandler.waitFor();

    if (executor.isFailure(resultHandler.getExitValue())) {
        pluginLog.error(String.format(
                "%s - openDOTFileWithGraphViz - error while opening DOT file for project '%s' from: '%s'",
                pluginName, project.getName(), pugDOT.getAbsolutePath()), resultHandler.getException());
        return false;
    }

    pluginLog.info(String.format("%s - openDOTFileWithGraphViz - opened DOT file for project '%s' from: '%s'",
            pluginName, project.getName(), pugDOT.getAbsolutePath()));
    return true;
}