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

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

Introduction

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

Prototype

public CommandLine addArgument(final String argument) 

Source Link

Document

Add a single argument.

Usage

From source file:org.fuin.esmp.EventStoreDownloadMojo.java

private void applyFileMode(final File file, final FileMode fileMode) throws MojoExecutionException {

    if (OS.isFamilyUnix() || OS.isFamilyMac()) {
        final String smode = fileMode.toChmodStringFull();
        final CommandLine cmdLine = new CommandLine("chmod");
        cmdLine.addArgument(smode);
        cmdLine.addArgument(file.getAbsolutePath());
        final Executor executor = new DefaultExecutor();
        try {/*ww w.  j av a 2s .c  o  m*/
            final int result = executor.execute(cmdLine);
            if (result != 0) {
                throw new MojoExecutionException("Error # " + result + " while trying to set mode \"" + smode
                        + "\" for file: " + file.getAbsolutePath());
            }
        } catch (final IOException ex) {
            throw new MojoExecutionException(
                    "Error while trying to set mode \"" + smode + "\" for file: " + file.getAbsolutePath(), ex);
        }
    } else {
        file.setReadable(fileMode.isUr() || fileMode.isGr() || fileMode.isOr());
        file.setWritable(fileMode.isUw() || fileMode.isGw() || fileMode.isOw());
        file.setExecutable(fileMode.isUx() || fileMode.isGx() || fileMode.isOx());
    }
}

From source file:org.fuin.esmp.EventStoreStartMojo.java

private CommandLine createCommandLine() throws MojoExecutionException {
    final CommandLine cmdLine = new CommandLine(command);
    if (arguments != null) {
        for (final String argument : arguments) {
            cmdLine.addArgument(argument);
        }/*from  w  w w .j a  va2s  . c om*/
    }
    return cmdLine;
}

From source file:org.fuin.esmp.EventStoreStopMojo.java

private CommandLine createCommandLine() throws MojoExecutionException {
    final CommandLine cmdLine = new CommandLine(command);
    if (OS.isFamilyWindows()) {
        cmdLine.addArgument("/PID");
        cmdLine.addArgument(readPid());/*from  w w w . j  a  v a2 s  . c om*/
        cmdLine.addArgument("/F");
    } else if (OS.isFamilyUnix() || OS.isFamilyMac()) {
        cmdLine.addArgument("-SIGKILL");
        cmdLine.addArgument(readPid());
    } else {
        throw new MojoExecutionException("Unknown OS - Cannot kill the process");
    }
    return cmdLine;
}

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.//  w  w w  . j a  v a  2  s .co  m
 * 
 * @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.
 * /*  ww  w. j av a 2s .  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

protected boolean checkAvailable() throws IOException {
    try {//from   ww  w.  j  a  v a  2 s  .com
        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.GdalAddoTransform.java

@Override
protected void setupCommandLine(boolean inline, CommandLine cmd) {
    super.setupCommandLine(inline, cmd);
    for (Integer level : levels) {
        cmd.addArgument(String.valueOf(level));
    }//w  w w .  j  av a2  s  . c o  m
}

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;// w  ww . j av  a  2 s.  c  o  m
    }

    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.jahia.modules.docviewer.PDF2SWFConverterService.java

protected CommandLine getConvertCommandLine(File inputFile, File outputFile) {
    CommandLine cmd = new CommandLine(getExecutablePath());
    cmd.addArgument("${inFile}");
    cmd.addArgument("-o");
    cmd.addArgument("${outFile}");
    cmd.addArguments(getParameters(), false);

    Map<String, File> params = new HashMap<String, File>(2);
    params.put("inFile", inputFile);
    params.put("outFile", outputFile);

    cmd.setSubstitutionMap(params);//  www .ja va2 s  .  c o  m

    return cmd;
}

From source file:org.jberet.support.io.OsCommandBatchlet.java

/**
 * {@inheritDoc}/*w w w  . ja v  a 2s  . c  o m*/
 * <p>
 * This method runs the OS command.
 * If the command completes successfully, its process exit code is returned.
 * If there is exception while running the OS command, which may be
 * caused by timeout, the command being stopped, or other errors, the process
 * exit code is set as the step exit status, and the exception is thrown.
 *
 * @return the OS command process exit code
 *
 * @throws Exception upon errors
 */
@Override
public String process() throws Exception {
    final DefaultExecutor executor = new DefaultExecutor();
    final CommandLine commandLineObj;
    if (commandLine != null) {
        commandLineObj = CommandLine.parse(commandLine);
    } else {
        if (commandArray == null) {
            throw SupportMessages.MESSAGES.invalidReaderWriterProperty(null, null, "commandArray");
        } else if (commandArray.isEmpty()) {
            throw SupportMessages.MESSAGES.invalidReaderWriterProperty(null, commandArray.toString(),
                    "commandArray");
        }
        commandLineObj = new CommandLine(commandArray.get(0));
        final int len = commandArray.size();
        if (len > 1) {
            for (int i = 1; i < len; i++) {
                commandLineObj.addArgument(commandArray.get(i));
            }
        }
    }

    if (workingDir != null) {
        executor.setWorkingDirectory(workingDir);
    }
    if (streamHandler != null) {
        executor.setStreamHandler((ExecuteStreamHandler) streamHandler.newInstance());
    }

    SupportLogger.LOGGER.runCommand(commandLineObj.getExecutable(),
            Arrays.toString(commandLineObj.getArguments()), executor.getWorkingDirectory().getAbsolutePath());

    if (commandOkExitValues != null) {
        executor.setExitValues(commandOkExitValues);
    }

    watchdog = new ExecuteWatchdog(
            timeoutSeconds > 0 ? timeoutSeconds * 1000 : ExecuteWatchdog.INFINITE_TIMEOUT);
    executor.setWatchdog(watchdog);

    executor.setProcessDestroyer(new ShutdownHookProcessDestroyer());
    final DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
    executor.execute(commandLineObj, environment, resultHandler);
    resultHandler.waitFor();

    final ExecuteException exception = resultHandler.getException();
    if (exception != null) {
        stepContext.setExitStatus(String.valueOf(resultHandler.getExitValue()));
        if (!isStopped) {
            throw exception;
        } else {
            SupportLogger.LOGGER.warn("", exception);
        }
    }
    return String.valueOf(resultHandler.getExitValue());
}