Example usage for org.apache.commons.exec CommandLine CommandLine

List of usage examples for org.apache.commons.exec CommandLine CommandLine

Introduction

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

Prototype

public CommandLine(final CommandLine other) 

Source Link

Document

Copy constructor.

Usage

From source file:org.fuin.kickstart4j.Kickstart4J.java

/**
 * Executes the installer/updater./*from  w w  w  .j  ava  2 s  .co m*/
 * 
 * @throws CanceledException
 *             The user canceled the installation.
 * @throws InvalidConfigException
 *             The configuration is invalid.
 */
public final void execute() throws CanceledException, InvalidConfigException {

    Locale.setDefault(config.getLocale());
    final File destDir = getDestDir();
    config.getCmdLineOptions().put("destDir", destDir.toString());

    // Check configuration AFTER destination directory is set
    // and logging is initialized
    config.check();
    initLogging();
    listener.initComplete();

    // Start the update
    final UpdateSet updateSet = new UpdateSet(config.getSrcFiles(), config.getMkDirs(), destDir,
            config.isLazyLoading());
    if (updateSet.isUpdateNecessary()) {
        if (LOG.isInfoEnabled()) {
            LOG.info("An update is available: New=" + updateSet.getNewFiles().size() + ", Changed="
                    + updateSet.getChangedFiles().size() + ", Deleted=" + updateSet.getDeletedFiles().size()
                    + ", SilentInstall=" + config.isSilentInstall() + ", SilentUpdate="
                    + config.isSilentUpdate() + ", FirstInstallation=" + config.isFirstInstallation());
        }
        if (config.isSilentUpdate() || config.isFirstInstallation()
                || isAnswerYes(config.getMessages().getUpdateAvailable())) {
            execute(updateSet);
            final File installationIncompleteFile = new File(destDir, INCOMPLETE_FILE);
            if (installationIncompleteFile.exists()) {
                installationIncompleteFile.delete();
            }
        }
    } else {
        LOG.info("Files are up to date");
    }

    final JFrame startFrame = showStartFrame();

    config.getCmdLineOptions().put("classpath", updateSet.createClasspath());

    // Write the config to the target directory
    saveConfigToTargetDir(destDir);

    // Run the target application
    final CommandLine commandLine = new CommandLine(config.getJavaExe());
    commandLine.addArguments(config.getJavaArgs(), false);
    logStart(destDir, commandLine.toString());
    new ApplicationStarter(destDir, commandLine, startFrame, listener, config).execute();

}

From source file:org.fuin.owndeb.commons.DebUtils.java

/**
 * Untars a given 'tar.gz' file on a linux system using the 'tar' command in
 * the directory where it is placed./*from w  w  w  . j  a v a 2s  .  c  om*/
 * 
 * @param tarFile
 *            File to unpack.
 */
public static final void unTarGz(@NotNull final File tarFile) {
    Contract.requireArgNotNull("tarFile", tarFile);

    final String tarFilePath = Utils4J.getCanonicalPath(tarFile);
    LOG.info("unTarGz: {}", tarFilePath);

    final CommandLine cmdLine = new CommandLine("tar");
    cmdLine.addArgument("-zvxf");
    cmdLine.addArgument(tarFilePath);

    execute(cmdLine, tarFile.getParentFile(), "unTarGz: " + tarFilePath);

}

From source file:org.fuin.owndeb.commons.DebUtils.java

/**
 * Creates a tar.gz file on a linux system using the 'tar' command.
 * //from  w  w  w. j ava2  s . c o  m
 * @param parentDir
 *            Working directory.
 * @param dirName
 *            Directory inside the working directory that will be archived.
 * 
 * @return Tar file.
 */
public static final File tarGz(@NotNull final File parentDir, final String dirName) {

    Contract.requireArgNotNull("parentDir", parentDir);
    Contract.requireArgNotNull("dirName", dirName);

    final File tarFile = new File(parentDir, dirName + ".tar.gz");
    final String tarFileNameAndPath = Utils4J.getCanonicalPath(tarFile);
    LOG.info("tarGz '{}': {}", dirName, tarFileNameAndPath);

    final CommandLine cmdLine = new CommandLine("tar");
    cmdLine.addArgument("-zvcf");
    cmdLine.addArgument(tarFileNameAndPath);
    cmdLine.addArgument(dirName);

    execute(cmdLine, parentDir, "tar file: " + tarFileNameAndPath);

    return tarFile;
}

From source file:org.geoserver.importer.transform.AbstractCommandLinePreTransform.java

@Override
public void apply(ImportTask task, ImportData data) throws Exception {
    boolean inline = isInline();
    File executable = getExecutable();
    File inputFile = getInputFile(data);
    Map<String, File> substitutions = new HashMap<>();
    substitutions.put("input", inputFile);
    File outputDirectory = null;/*from  w w w . j a  v a2 s.co m*/
    File outputFile = null;
    if (!inline) {
        outputDirectory = getOutputDirectory(data);
        outputFile = new File(outputDirectory, inputFile.getName());
        substitutions.put("output", outputFile);
    }

    // setup the options
    CommandLine cmd = new CommandLine(executable);
    cmd.setSubstitutionMap(substitutions);

    setupCommandLine(inline, cmd);

    try {
        execute(cmd, null);

        // if not inline, replace inputs with output
        if (!inline) {
            List<String> names = getReplacementTargetNames(data);
            File inputParent = inputFile.getParentFile();
            for (String name : names) {
                File output = new File(outputDirectory, name);
                File input = new File(inputParent, name);
                if (output.exists()) {
                    // uses atomic rename on *nix, delete and copy on Windows
                    IOUtils.rename(output, input);
                } else if (input.exists()) {
                    input.delete();
                }
            }
        }
    } finally {
        if (outputDirectory != null) {
            FileUtils.deleteQuietly(outputDirectory);
        }
    }
}

From source file:org.geoserver.importer.transform.AbstractCommandLinePreTransform.java

protected boolean checkAvailable() throws IOException {
    try {//from  w  w  w  .j a  v a2  s.  c  om
        CommandLine cmd = new CommandLine(getExecutable());
        for (String option : getAvailabilityTestOptions()) {
            cmd.addArgument(option);
        }

        // prepare to run
        DefaultExecutor executor = new DefaultExecutor();

        // grab at least some part of the outputs
        int limit = 16 * 1024;
        try (OutputStream os = new BoundedOutputStream(new ByteArrayOutputStream(), limit);
                OutputStream es = new BoundedOutputStream(new ByteArrayOutputStream(), limit)) {
            PumpStreamHandler streamHandler = new PumpStreamHandler(os, es);
            executor.setStreamHandler(streamHandler);
            int result = executor.execute(cmd);

            if (result != 0) {
                LOGGER.log(Level.SEVERE, "Failed to execute command " + cmd.toString()
                        + "\nStandard output is:\n" + os.toString() + "\nStandard error is:\n" + es.toString());
                return false;
            }

        } catch (Exception e) {
            LOGGER.log(Level.SEVERE, "Failure to execute command " + cmd.toString(), e);
            return false;
        }
    } catch (Exception e) {
        LOGGER.log(Level.SEVERE, "Failure to locate executable for class " + this.getClass(), e);
        return false;
    }

    return true;
}

From source file:org.geoserver.importer.transform.AbstractCommandLineTransform.java

@Override
public void apply(ImportTask task, ImportData data) throws Exception {
    boolean inline = isInline();
    File executable = getExecutable();
    File inputFile = getInputFile(data);
    Map<String, File> substitutions = new HashMap<>();
    substitutions.put("input", inputFile);
    File outputDirectory = null;/*from w w  w  .j  av a2 s  . c  om*/
    File outputFile = null;
    if (!inline) {
        outputDirectory = getOutputDirectory(data);
        outputFile = new File(outputDirectory, inputFile.getName());
        substitutions.put("output", outputFile);
    }

    // setup the options
    CommandLine cmd = new CommandLine(executable);
    cmd.setSubstitutionMap(substitutions);

    setupCommandLine(inline, cmd);

    // prepare to run
    DefaultExecutor executor = new DefaultExecutor();
    // make sure we don't try to execute for too much time
    executor.setWatchdog(new ExecuteWatchdog(DEFAULT_TIMEOUT));

    // grab at least some part of the outputs
    int limit = 16 * 1024;
    try {
        try (OutputStream os = new BoundedOutputStream(new ByteArrayOutputStream(), limit);
                OutputStream es = new BoundedOutputStream(new ByteArrayOutputStream(), limit)) {
            PumpStreamHandler streamHandler = new PumpStreamHandler(os, es);
            executor.setStreamHandler(streamHandler);
            try {
                int result = executor.execute(cmd);

                if (executor.isFailure(result)) {
                    // toString call is routed to ByteArrayOutputStream, which does the right string
                    // conversion
                    throw new IOException(
                            "Failed to execute command " + cmd.toString() + "\nStandard output is:\n"
                                    + os.toString() + "\nStandard error is:\n" + es.toString());
                }
            } catch (Exception e) {
                throw new IOException("Failure to execute command " + cmd.toString() + "\nStandard output is:\n"
                        + os.toString() + "\nStandard error is:\n" + es.toString(), e);
            }
        }

        // if not inline, replace inputs with output
        if (!inline) {
            List<String> names = getReplacementTargetNames(data);
            File inputParent = inputFile.getParentFile();
            for (String name : names) {
                File output = new File(outputDirectory, name);
                File input = new File(inputParent, name);
                if (output.exists()) {
                    // uses atomic rename on *nix, delete and copy on Windows
                    IOUtils.rename(output, input);
                } else if (input.exists()) {
                    input.delete();
                }
            }
        }
    } finally {
        if (outputDirectory != null) {
            FileUtils.deleteQuietly(outputDirectory);
        }
    }
}

From source file:org.geoserver.importer.transform.PostScriptTransform.java

@Override
public void apply(ImportTask task, ImportData data) throws Exception {
    File executable = getExecutable();

    CommandLine cmd = new CommandLine(executable);
    for (String option : options) {
        cmd.addArgument(option, false);/*from  w  w  w  .  ja  v  a  2  s  .co  m*/
    }

    execute(cmd, getScriptsFolder().dir());
}

From source file:org.gluu.oxtrust.ldap.service.StatusCheckerTimer.java

private void setDfAttributes(GluuAppliance appliance) {
    log.debug("Setting df attributes");
    // Run df only on linux
    if (!isLinux()) {
        return;/*from   w w  w .ja  va 2 s  . com*/
    }

    String programPath = OxTrustConstants.PROGRAM_DF;
    CommandLine commandLine = new CommandLine(programPath);
    commandLine.addArgument("/");
    commandLine.addArgument("--human-readable");

    ByteArrayOutputStream bos = new ByteArrayOutputStream(4096);
    try {
        boolean result = ProcessHelper.executeProgram(commandLine, false, 0, bos);
        if (!result) {
            return;
        }
    } finally {
        IOUtils.closeQuietly(bos);
    }

    String resultOutput = null;
    try {
        resultOutput = new String(bos.toByteArray(), "UTF-8");
    } catch (UnsupportedEncodingException ex) {
        log.error("Failed to parse program {0} output", ex, programPath);
        return;
    }

    String[] outputLines = resultOutput.split("\\r?\\n");
    String[] outputValues = null;
    if (outputLines.length == 2) {
        outputValues = outputLines[1].split("\\s+");
    } else if (outputLines.length == 3) {
        outputValues = outputLines[2].split("\\s+");
    }

    if (outputValues != null) {
        if (outputValues.length < 6) {
            return;
        }

        Number usedDiskSpace = getNumber(outputValues[4]);
        Number freeDiskSpace = usedDiskSpace == null ? null : 100 - usedDiskSpace.doubleValue();

        // Update appliance attributes
        appliance.setFreeDiskSpace(toIntString(freeDiskSpace));
    }
}

From source file:org.grouplens.lenskit.eval.maven.RScriptMojo.java

@Override
public void execute() throws MojoExecutionException {
    getLog().info("The analysis directory is " + analysisDir);
    getLog().info("The analysisScript is " + analysisScript);
    getLog().info("The R executable is " + rscriptExecutable);

    // Copy the script file into the working directory.  We could just execute
    // it from its original location, but it will be easier for our users to 
    // have the copy from the src directory next to its results in target.
    File scriptFile = new File(analysisScript);
    File scriptCopy = new File(analysisDir, scriptFile.getName());
    try {//from  w  w w.  j av a 2  s . co  m
        if (!scriptFile.getCanonicalPath().equals(scriptCopy.getCanonicalPath())) {
            copyFile(scriptFile, scriptCopy);
        }
    } catch (IOException e1) {
        throw new MojoExecutionException("Unable to copy scriptFile " + scriptFile.getAbsolutePath()
                + " into working directory " + scriptCopy.getAbsolutePath());
    }

    // Generate the command line for executing R.
    final CommandLine command = new CommandLine(rscriptExecutable).addArgument(scriptCopy.getAbsolutePath(),
            false);
    getLog().debug("command: " + command);

    // Execute the command line, in the working directory.
    final DefaultExecutor executor = new DefaultExecutor();
    executor.setWorkingDirectory(new File(analysisDir));
    try {
        if (executor.execute(command) != 0) {
            throw new MojoExecutionException("Error code returned for: " + command.toString());
        }
    } catch (ExecuteException e) {
        throw new MojoExecutionException("Error executing command: " + command.toString(), e);
    } catch (IOException e) {
        throw new MojoExecutionException("IO Exception while executing command: " + command.toString(), e);
    }
}

From source file:org.jahia.modules.dm.thumbnails.video.impl.VideoThumbnailServiceImpl.java

protected CommandLine getConvertCommandLine(File inputFile, File outputFile, String offset, String size) {
    CommandLine cmd = new CommandLine(executablePath);
    cmd.addArguments(parameters);/*  w  w w .ja  va  2s. c  o m*/

    Map<String, Object> params = new HashMap<String, Object>(4);
    params.put("offset", offset);
    params.put("input", inputFile);
    params.put("output", outputFile);
    params.put("size", size);

    cmd.setSubstitutionMap(params);

    return cmd;
}