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

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

Introduction

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

Prototype

public void setSubstitutionMap(final Map<String, ?> substitutionMap) 

Source Link

Document

Set the substitutionMap to expand variables in the command line.

Usage

From source file:eu.creatingfuture.propeller.blocklyprop.propeller.GccCompiler.java

protected boolean compileForRam(String executable, File sourceFile, File destinationFile) {
    try {//from w  w w.jav a 2s .  c om
        List<CLib> libs = new ArrayList<>();
        libs.add(cLibs.get("simpletools"));
        libs.add(cLibs.get("simpletext"));
        libs.add(cLibs.get("simplei2c"));

        File libDirectory = new File(new File(System.getProperty("user.dir")), "/propeller-c-lib");
        Map map = new HashMap();
        map.put("sourceFile", sourceFile);
        map.put("destinationFile", destinationFile);
        CommandLine cmdLine = new CommandLine(executable);
        for (CLib lib : libs) {
            cmdLine.addArgument("-I").addArgument("${libdir" + lib.getName() + "}");
            cmdLine.addArgument("-L").addArgument("${memorymodel" + lib.getName() + "}");
            //                cmdLine.addArgument("-l" + lib.getName());

            map.put("libdir" + lib.getName(), new File(libDirectory, lib.getLibdir()));
            map.put("memorymodel" + lib.getName(), new File(libDirectory, lib.getMemoryModel().get("cmm")));
        }
        cmdLine.addArgument("-Os");
        cmdLine.addArgument("-mcmm");
        cmdLine.addArgument("-m32bit-doubles");
        cmdLine.addArgument("-std=c99");
        cmdLine.addArgument("-o").addArgument("${destinationFile}");
        cmdLine.addArgument("${sourceFile}");
        cmdLine.addArgument("-lm");
        for (CLib lib : libs) {
            cmdLine.addArgument("-l" + lib.getName());
        }

        cmdLine.setSubstitutionMap(map);
        DefaultExecutor executor = new DefaultExecutor();
        //  executor.setExitValues(new int[]{402, 101});

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
        executor.setStreamHandler(streamHandler);

        try {
            exitValue = executor.execute(cmdLine);
        } catch (ExecuteException ee) {
            exitValue = ee.getExitValue();
            logger.log(Level.SEVERE, "Unexpected exit value: {0}", exitValue);
            success = false;
            return false;
        } finally {
            output = outputStream.toString();
        }

        //            System.out.println("output: " + output);
        /*
         Scanner scanner = new Scanner(output);
                
                
         Pattern chipFoundPattern = Pattern.compile(".*?(EVT:505).*?");
         Pattern pattern = Pattern.compile(".*?found on (?<comport>[a-zA-Z0-9]*).$");
         while (scanner.hasNextLine()) {
         String portLine = scanner.nextLine();
         if (chipFoundPattern.matcher(portLine).matches()) {
         Matcher portMatch = pattern.matcher(portLine);
         if (portMatch.find()) {
         //   String port = portMatch.group("comport");
                
         }
         }
         }
         */
        //            System.out.println("output: " + output);
        //            System.out.println("exitValue: " + exitValue);
        success = true;
        return true;
    } catch (IOException ioe) {
        logger.log(Level.SEVERE, null, ioe);
        success = false;
        return false;
    }
}

From source file:eu.creatingfuture.propeller.blocklyprop.propeller.GccCompiler.java

/**
 *
 *
 * @param executable//w  w w.j  a va 2  s .  com
 * @param sourceFile
 * @return
 */
protected boolean compile(String executable, File sourceFile) {
    try {
        List<CLib> libs = new ArrayList<>();
        libs.add(cLibs.get("simpletools"));
        libs.add(cLibs.get("simpletext"));
        libs.add(cLibs.get("simplei2c"));

        File temporaryDestinationFile = File.createTempFile("blocklyapp", ".elf");
        File libDirectory = new File(new File(System.getProperty("user.dir")), "/propeller-c-lib");
        Map map = new HashMap();
        map.put("sourceFile", sourceFile);
        map.put("destinationFile", temporaryDestinationFile);

        CommandLine cmdLine = new CommandLine(executable);
        for (CLib lib : libs) {
            cmdLine.addArgument("-I").addArgument("${libdir" + lib.getName() + "}");
            cmdLine.addArgument("-L").addArgument("${memorymodel" + lib.getName() + "}");
            // cmdLine.addArgument("-l" + lib.getName());

            map.put("libdir" + lib.getName(), new File(libDirectory, lib.getLibdir()));
            map.put("memorymodel" + lib.getName(), new File(libDirectory, lib.getMemoryModel().get("cmm")));
        }
        cmdLine.addArgument("-Os");
        cmdLine.addArgument("-mcmm");
        cmdLine.addArgument("-m32bit-doubles");
        cmdLine.addArgument("-fno-exceptions");
        cmdLine.addArgument("-std=c99");
        cmdLine.addArgument("-o").addArgument("${destinationFile}");
        cmdLine.addArgument("${sourceFile}");
        cmdLine.addArgument("-lm");
        for (CLib lib : libs) {
            cmdLine.addArgument("-l" + lib.getName());
        }

        cmdLine.setSubstitutionMap(map);
        DefaultExecutor executor = new DefaultExecutor();
        executor.setExitValues(new int[] { 0, 1 });

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
        executor.setStreamHandler(streamHandler);

        try {
            System.out.println(cmdLine);
            exitValue = executor.execute(cmdLine);
        } catch (ExecuteException ee) {
            exitValue = ee.getExitValue();
            logger.log(Level.SEVERE, "Unexpected exit value: {0}", exitValue);
            success = false;
            return false;
        } finally {
            temporaryDestinationFile.delete();
            output = outputStream.toString();
        }

        //            System.out.println("output: " + output);
        /*
         Scanner scanner = new Scanner(output);
                
                
         Pattern chipFoundPattern = Pattern.compile(".*?(EVT:505).*?");
         Pattern pattern = Pattern.compile(".*?found on (?<comport>[a-zA-Z0-9]*).$");
         while (scanner.hasNextLine()) {
         String portLine = scanner.nextLine();
         if (chipFoundPattern.matcher(portLine).matches()) {
         Matcher portMatch = pattern.matcher(portLine);
         if (portMatch.find()) {
         //   String port = portMatch.group("comport");
                
         }
         }
         }
         */
        //            System.out.println("output: " + output);
        //            System.out.println("exitValue: " + exitValue);
        success = true;
        return true;
    } catch (IOException ioe) {
        logger.log(Level.SEVERE, null, ioe);
        success = false;
        return false;
    }
}

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 ww  w.ja v  a 2  s  . c o  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.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. jav a2s  .c  o  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);

    // 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.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);/*  ww  w . j a  v a  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;
}

From source file:org.jahia.modules.dm.viewer.impl.PDF2SWFConverterService.java

protected CommandLine getConvertCommandLine(File inputFile, File outputFile) {
    CommandLine cmd = new CommandLine(executablePath);
    cmd.addArguments(parameters);/*from   ww  w .ja v  a 2s.co  m*/

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

    cmd.setSubstitutionMap(params);

    return cmd;
}

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);

    return cmd;/*  www  .j  a va  2 s  . c  o  m*/
}

From source file:org.jahia.utils.ProcessHelper.java

/**
 * Executes the external process using the provided command, arguments (optional), parameter substitution map to expand variables in the
 * command or arguments in form of <code>${variable}<code> (optional) and a working directory (optional).
 * Buffers for process output and error stream can be provided.
 * /*from   w  w w.  ja va 2 s  .  c  om*/
 * @param command
 *            the command to be executed
 * @param arguments
 *            optional arguments for the command
 * @param parameterSubstitutionMap
 *            optional values for variables to be expanded
 * @param workingDir
 *            optional working directory for the process to be started from
 * @param resultOut
 *            the buffer to write the process execution output into (optional)
 * @param resultErr
 *            the buffer to write the process execution error into (optional)
 * @return the execution status
 * @return redirectOutputs if set to <code>true</code> the output of the execution will be also redirected to standard system out and
 *         the error to error out
 * @throws JahiaRuntimeException
 *             in case the process execution failed
 */
public static int execute(String command, String arguments[], Map<String, Object> parameterSubstitutionMap,
        File workingDir, StringBuilder resultOut, StringBuilder resultErr, boolean redirectOutputs)
        throws JahiaRuntimeException {

    long timer = System.currentTimeMillis();

    CommandLine cmd = new CommandLine(command);

    if (arguments != null && arguments.length > 0) {
        cmd.addArguments(arguments, false);
    }

    if (parameterSubstitutionMap != null && !parameterSubstitutionMap.isEmpty()) {
        cmd.setSubstitutionMap(parameterSubstitutionMap);
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Executing command: {}", cmd.toString());
    } else if (redirectOutputs) {
        logger.info("Executing command: ");
        logger.info(cmd.toString());
    }

    int exitValue = 0;

    StringOutputStream out = new StringOutputStream(redirectOutputs ? System.out : null);
    StringOutputStream err = new StringOutputStream(redirectOutputs ? System.err : null);
    try {
        DefaultExecutor executor = new DefaultExecutor();
        executor.setStreamHandler(new PumpStreamHandler(out, err));
        if (workingDir != null) {
            if (workingDir.exists() || workingDir.mkdirs()) {
                executor.setWorkingDirectory(workingDir);
            }
        }
        exitValue = executor.execute(cmd, System.getenv());
    } catch (ExecuteException ee) {
        return ee.getExitValue();
    } catch (Exception e) {
        throw new JahiaRuntimeException(e);
    } finally {
        if (resultErr != null) {
            resultErr.append(err.toString());
        }
        if (resultOut != null) {
            resultOut.append(out.toString());
        }
        if (exitValue > 0) {
            logger.error("External process finished with error. Cause: {}", err.toString());
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Execution took {} ms and finished with status {} and output {}",
                    new Object[] { (System.currentTimeMillis() - timer), exitValue, out.toString() });
        }
    }

    return exitValue;
}

From source file:org.jboss.maven.populator.MavenDeployer.java

public void deploy(final String groupId, final String artifactId, final String version,
        final String artifactPath) throws IOException {
    logger.info("Deploying " + artifactPath);

    final Map<String, String> params = new HashMap<String, String>();
    params.put("settingsUrl", settingsPath);
    params.put("artifactId", artifactId);
    params.put("groupId", groupId);
    params.put("version", version);
    params.put("artifactPath", artifactPath);
    params.put("repositoryUrl", repositoryUrl);
    params.put("repositoryId", repositoryId);

    final CommandLine deployCmd = CommandLine.parse(MVN_DEPLOY);
    deployCmd.setSubstitutionMap(params);

    final DefaultExecutor executor = new DefaultExecutor();
    executor.execute(deployCmd);/*from ww  w.ja  v a2  s  .  c o m*/
}

From source file:org.jboss.windup.decorator.java.decompiler.BackupOfJadretroDecompilerAdapter.java

private void executeJad(File classLocation, File sourceOutputLocation) {

    try {//  w w w.  j av a 2s.c  o m
        // Build command array
        CommandLine cmdLine = new CommandLine(APP_NAME);
        cmdLine.addArgument("-d");
        cmdLine.addArgument("${outputLocation}");
        cmdLine.addArgument("-f");
        cmdLine.addArgument("-o");
        cmdLine.addArgument("-s");
        cmdLine.addArgument("java");
        cmdLine.addArgument("${classLocation}");

        Map<String, Object> argMap = new HashMap<String, Object>();
        argMap.put("outputLocation", sourceOutputLocation);
        argMap.put("classLocation", classLocation);
        cmdLine.setSubstitutionMap(argMap);

        DefaultExecutor executor = new DefaultExecutor();
        executor.setExitValue(0);
        ExecuteWatchdog watchdog = new ExecuteWatchdog(60000);
        executor.setWatchdog(watchdog);
        int exitValue = executor.execute(cmdLine);

        LOG.debug("Decompiler exited with exit code: " + exitValue);

        if (!sourceOutputLocation.exists()) {
            LOG.error("Expected decompiled source: " + sourceOutputLocation.getAbsolutePath()
                    + "; did not find file.  This likey means that the decompiler did not successfully decompile the class.");
        } else {
            LOG.debug("Decompiled to: " + sourceOutputLocation.getAbsolutePath());
        }

    } catch (IOException e) {
        throw new FatalWindupException(
                "Error running " + APP_NAME + " decompiler.  Validate that " + APP_NAME + " is on your PATH.",
                e);
    } catch (Exception e) {
        throw new FatalWindupException(
                "Error running " + APP_NAME + " decompiler.  Validate that " + APP_NAME + " is on your PATH.",
                e);
    }
}