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

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

Introduction

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

Prototype

public DefaultExecutor() 

Source Link

Document

Default constructor creating a default PumpStreamHandler and sets the working directory of the subprocess to the current working directory.

Usage

From source file:Logi.GSeries.Service.LogiGSKService.java

public void showSystemTray() {
    if ((systemTray != null) && !systemTrayVisible) {
        systemTray.setEnabled(true);/*  w w  w  .  j  ava  2 s  .c o  m*/
        systemTrayVisible = true;
        return;
    }

    try {
        systemTray = SystemTray.getNative();
    } catch (Exception ex) {
        System.out.println(ex.getMessage());
        Logger.getLogger(LogiGSKService.class.getName()).log(Level.SEVERE, null, ex);
    }

    if (systemTray != null) {
        try {
            systemTray.setImage(GSK_Icon);
        } catch (Exception e) {
            System.err.println("Problem setting system tray icon.");
        }
        systemTrayVisible = true;
        callbackOpen = new ActionListener() {
            @Override
            public void actionPerformed(final ActionEvent e) {
                final MenuItem entry = (MenuItem) e.getSource();
                try {
                    CommandLine commandLine = new CommandLine("java");
                    commandLine.addArgument("-jar");
                    String jarPath = new URI(
                            LogiGSKService.class.getProtectionDomain().getCodeSource().getLocation().getPath())
                                    .getPath();
                    commandLine.addArgument(jarPath, false);
                    DefaultExecutor executor = new DefaultExecutor();
                    executor.setExitValue(1);
                    executor.execute(commandLine, new DefaultExecuteResultHandler());
                } catch (URISyntaxException ex) {
                    Logger.getLogger(LogiGSKService.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IOException ex) {
                    Logger.getLogger(LogiGSKService.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        };

        callbackAbout = new ActionListener() {
            @Override
            public void actionPerformed(final ActionEvent e) {
                final MenuItem entry = (MenuItem) e.getSource();
                JOptionPane.showMessageDialog(null, "<HTML>LogiGSK V1.0</HTML>", "LogiGSK",
                        JOptionPane.INFORMATION_MESSAGE);
            }
        };

        Menu mainMenu = systemTray.getMenu();

        MenuItem openEntry = new MenuItem("Open", new ActionListener() {
            @Override
            public void actionPerformed(final ActionEvent e) {
                final MenuItem entry = (MenuItem) e.getSource();
                entry.setCallback(callbackOpen);
                try {
                    CommandLine commandLine = new CommandLine("java");
                    commandLine.addArgument("-jar");
                    String jarPath = new URI(
                            LogiGSKService.class.getProtectionDomain().getCodeSource().getLocation().getPath())
                                    .getPath();
                    commandLine.addArgument(jarPath, false);
                    DefaultExecutor executor = new DefaultExecutor();
                    executor.setExitValue(1);
                    executor.execute(commandLine, new DefaultExecuteResultHandler());
                } catch (URISyntaxException ex) {
                    Logger.getLogger(LogiGSKService.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IOException ex) {
                    Logger.getLogger(LogiGSKService.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
        openEntry.setShortcut('O');
        mainMenu.add(openEntry);
        mainMenu.add(new Separator());

        MenuItem aboutEntry = new MenuItem("About", new ActionListener() {
            @Override
            public void actionPerformed(final ActionEvent e) {
                final MenuItem entry = (MenuItem) e.getSource();
                JOptionPane.showMessageDialog(null, "<HTML>LogiGSK V1.0</HTML>", "LogiGSK",
                        JOptionPane.INFORMATION_MESSAGE);
                entry.setCallback(callbackAbout);
            }
        });
        openEntry.setShortcut('A');
        mainMenu.add(aboutEntry);
        /*} else {
        System.err.println("System tray is null!");
        }*/
    }
}

From source file:info.pancancer.arch3.worker.WorkerRunnable.java

@Override
public void run() {

    int max = maxRuns;

    try {//from   w w w .  ja  va  2  s  . com
        // the VM UUID
        log.info(" WORKER VM UUID provided as: '" + vmUuid + "'");
        // write to
        // TODO: Add some sort of "local debug" mode so that developers working on their local
        // workstation can declare the queue if it doesn't exist. Normally, the results queue is
        // created by the Coordinator.
        resultsChannel = Utilities.setupExchange(settings, this.resultsQueueName);

        while (max > 0 || this.endless) {
            log.debug(max + " remaining jobs will be executed");
            log.info(" WORKER IS PREPARING TO PULL JOB FROM QUEUE " + this.jobQueueName);

            if (!endless) {
                max--;
            }

            // jobChannel needs to be created inside the loop because it is closed inside the loop, and it is closed inside this loop to
            // prevent pre-fetching.
            Channel jobChannel = Utilities.setupQueue(settings, this.jobQueueName);
            if (jobChannel == null) {
                throw new NullPointerException("jobChannel is null for queue: " + this.jobQueueName
                        + ". Something bad must have happened while trying to set up the queue connections. Please ensure that your configuration is correct.");
            }
            QueueingConsumer consumer = new QueueingConsumer(jobChannel);
            jobChannel.basicConsume(this.jobQueueName, false, consumer);

            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            log.info(vmUuid + "  received " + delivery.getEnvelope().toString());
            if (delivery.getBody() != null) {
                String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
                if (message.trim().length() > 0) {

                    log.info(" [x] Received JOBS REQUEST '" + message + "' @ " + vmUuid);

                    Job job = new Job().fromJSON(message);

                    Status status = new Status(vmUuid, job.getUuid(), StatusState.RUNNING,
                            Utilities.JOB_MESSAGE_TYPE, "job is starting", this.networkAddress);
                    status.setStderr("");
                    status.setStdout("");
                    String statusJSON = status.toJSON();

                    log.info(" WORKER LAUNCHING JOB");

                    // greedy acknowledge, it will be easier to deal with lost jobs than zombie workers in hostile OpenStack
                    // environments
                    log.info(vmUuid + " acknowledges " + delivery.getEnvelope().toString());
                    jobChannel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
                    // we need to close the channel IMMEDIATELY to complete the ACK.
                    jobChannel.close();
                    // Close the connection object as well, or the main thread may not exit because of still-open-and-in-use resources.
                    jobChannel.getConnection().close();

                    WorkflowResult workflowResult = new WorkflowResult();
                    if (testMode) {
                        workflowResult.setWorkflowStdout("everything is awesome");
                        workflowResult.setExitCode(0);
                    } else {
                        String seqwareEngine = settings.getString(Constants.WORKER_SEQWARE_ENGINE,
                                Constants.SEQWARE_WHITESTAR_ENGINE);
                        String seqwareSettingsFile = settings.getString(Constants.WORKER_SEQWARE_SETTINGS_FILE);
                        String dockerImage = settings.getString(Constants.WORKER_SEQWARE_DOCKER_IMAGE_NAME);
                        workflowResult = launchJob(statusJSON, job, seqwareEngine, seqwareSettingsFile,
                                dockerImage);
                    }

                    status = new Status(vmUuid, job.getUuid(),
                            workflowResult.getExitCode() == 0 ? StatusState.SUCCESS : StatusState.FAILED,
                            Utilities.JOB_MESSAGE_TYPE, "job is finished", networkAddress);
                    status.setStderr(workflowResult.getWorkflowStdErr());
                    status.setStdout(workflowResult.getWorkflowStdout());
                    statusJSON = status.toJSON();

                    log.info(" WORKER FINISHING JOB");

                    finishJob(statusJSON);
                } else {
                    log.info(NO_MESSAGE_FROM_QUEUE_MESSAGE);
                }
                // we need to close the channel *conditionally*
                if (jobChannel.isOpen()) {
                    jobChannel.close();
                }
                // Close the connection object as well, or the main thread may not exit because of still-open-and-in-use resources.
                if (jobChannel.getConnection().isOpen()) {
                    jobChannel.getConnection().close();
                }
            } else {
                log.info(NO_MESSAGE_FROM_QUEUE_MESSAGE);
            }

            if (endless) {
                log.info("attempting to reset workspace");
                DefaultExecutor executor = new DefaultExecutor();
                DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
                // attempt a cleanup
                CommandLine cli = new CommandLine("sudo");
                List<String> args = new ArrayList<>(Arrays.asList("rm", "-rf", "/datastore/*"));
                cli.addArguments(args.toArray(new String[args.size()]));
                executor.execute(cli, resultHandler);
                // Use the result handler for non-blocking call, so this way we should be able to get updates of
                // stdout and stderr while the command is running.
                resultHandler.waitFor();
                log.info("exit code for cleanup: " + resultHandler.getExitValue());
            }
        }
        log.info(" \n\n\nWORKER FOR VM UUID HAS FINISHED!!!: '" + vmUuid + "'\n\n");

        // turns out this is needed when multiple threads are reading from the same
        // queue otherwise you end up with multiple unacknowledged messages being undeliverable to other workers!!!
        if (resultsChannel != null && resultsChannel.isOpen()) {
            resultsChannel.close();
            resultsChannel.getConnection().close();
        }
        log.debug("result channel open: " + resultsChannel.isOpen());
        log.debug("result channel connection open: " + resultsChannel.getConnection().isOpen());
    } catch (Exception ex) {
        log.error(ex.getMessage(), ex);
    }
}

From source file:hr.fer.zemris.vhdllab.service.impl.GhdlSimulator.java

private List<String> executeProcess(CommandLine cl, java.io.File tempDirectory)
        throws ExecuteException, IOException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Executing process: " + cl.toString());
    }/*from  w  ww  . j ava  2  s. co m*/

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ExecuteStreamHandler handler = new PumpStreamHandler(bos);
    ExecuteWatchdog watchdog = new ExecuteWatchdog(PROCESS_TIMEOUT);
    Executor executor = new DefaultExecutor();
    executor.setWorkingDirectory(tempDirectory);
    executor.setWatchdog(watchdog);
    executor.setStreamHandler(handler);
    /*
     * It seems that when ExecuteWatchdog terminates process by invoking
     * destroy method, process terminates with exit code 143. And since we
     * manually ask watchdog if he killed the process, exit code 143 is
     * marked as successful (just so our code can be executed).
     * 
     * Exit code 1 in case of compilation error(s).
     */
    executor.setExitValues(new int[] { 0, 1, 143 });
    try {
        executor.execute(cl);
    } catch (ExecuteException e) {
        LOG.warn("Process output dump:\n" + bos.toString());
        throw e;
    }

    if (watchdog.killedProcess()) {
        throw new SimulatorTimeoutException(PROCESS_TIMEOUT);
    }
    String output;
    try {
        output = bos.toString(IOUtil.DEFAULT_ENCODING);
    } catch (UnsupportedEncodingException e) {
        throw new UnhandledException(e);
    }
    if (StringUtils.isBlank(output)) {
        return Collections.emptyList();
    }
    return Arrays.asList(StringUtil.splitToNewLines(output));
}

From source file:de.fischer.thotti.core.runner.NDRunner.java

private NDTestResult forkNDTestRunnerInSlaveMode(NonDistributedTestType test, TestInstanceType instance)
        throws IOException {
    NDTestResult result = new NDTestResult();
    GregorianCalendar startTime;//from w ww  .ja v a  2 s.  c o m
    long startTimeMS;
    long endTimeMS;
    int exitCode = -9999;

    result.setTestId(test.getId());
    result.setJVMArgs(instance.getJvmArguments());
    result.setJVMArgsID(instance.getJvmArgsID());
    result.setParamGrpID(instance.getName());

    CommandLine cmdLine = new CommandLine("java");

    if (false == StringUtils.isEmpty(instance.getJvmArguments())) {
        cmdLine.addArguments(instance.getJvmArguments());
    }

    cmdLine.addArgument("-cp").addArgument(System.getProperty("java.class.path"))
            .addArgument(NDRunner.class.getName()).addArgument("--slave").addArgument("--executionid")
            .addArgument(instance.getExecutionID().toString());

    System.gc();
    DefaultExecutor executor = new DefaultExecutor();

    startTime = (GregorianCalendar) Calendar.getInstance();
    startTimeMS = startTime.getTimeInMillis();

    try {
        exitCode = executor.execute(cmdLine);
        result.setSuccessfulTermination(true);
        result.setExitCode(exitCode);
    } catch (ExecuteException e) {
        result.setSuccessfulTermination(false);
        result.setExitCode(e.getExitValue());
    } finally {
        endTimeMS = System.currentTimeMillis();
    }

    result.setExecutionTime(endTimeMS - startTimeMS);
    result.setStartTime(startTime);

    System.out.println(result);

    return result;
}

From source file:edu.stolaf.cs.wmrserver.TransformProcessor.java

private File compile(SubnodeConfiguration languageConf, String transformTypeString, File srcTransformFile,
        File jobTransformDir) throws CompilationException, IOException {
    // Determine correct compiler, returning if none specified
    String compiler = languageConf.getString("compiler-" + transformTypeString, "");
    if (compiler.isEmpty())
        compiler = languageConf.getString("compiler", "");
    if (compiler.isEmpty())
        return srcTransformFile;

    // Determine destination filename
    File compiledTransformFile = new File(jobTransformDir, "compiled-job-" + transformTypeString);

    // Create map to replace ${wmr:...} variables.
    // NOTE: Commons Configuration's built-in interpolator does not work here
    //  for some reason.
    File jobTempDir = getJobTempDir();
    Hashtable<String, String> variableMap = new Hashtable<String, String>();
    File libDir = getLibraryDirectory(languageConf);
    variableMap.put("wmr:lib.dir", (libDir != null) ? libDir.toString() : "");
    variableMap.put("wmr:src.dir", relativizeFile(srcTransformFile.getParentFile(), jobTempDir).toString());
    variableMap.put("wmr:src.file", relativizeFile(srcTransformFile, jobTempDir).toString());
    variableMap.put("wmr:dest.dir", relativizeFile(jobTransformDir, jobTempDir).toString());
    variableMap.put("wmr:dest.file", relativizeFile(compiledTransformFile, jobTempDir).toString());

    // Replace variables in compiler string
    compiler = StrSubstitutor.replace(compiler, variableMap);

    // Run the compiler

    CommandLine compilerCommand = CommandLine.parse(compiler);
    DefaultExecutor exec = new DefaultExecutor();
    ExecuteWatchdog dog = new ExecuteWatchdog(60000); // 1 minute
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    PumpStreamHandler pump = new PumpStreamHandler(output);
    exec.setWorkingDirectory(jobTempDir);
    exec.setWatchdog(dog);//from   w  ww.  j a va  2 s.co  m
    exec.setStreamHandler(pump);
    exec.setExitValues(null); // Can't get the exit code if it throws exception

    int exitStatus = -1;
    try {
        exitStatus = exec.execute(compilerCommand);
    } catch (IOException ex) {
        // NOTE: Exit status is still -1 in this case, since exception was thrown
        throw new CompilationException("Compiling failed for " + transformTypeString, exitStatus,
                new String(output.toByteArray()));
    }

    // Check for successful exit

    if (exitStatus != 0)
        throw new CompilationException("Compiling failed for " + transformTypeString, exitStatus,
                new String(output.toByteArray()));

    // Check that output exists and is readable, and make it executable

    if (!compiledTransformFile.isFile())
        throw new CompilationException(
                "Compiler did not output a " + transformTypeString
                        + " executable (or it was not a regular file).",
                exitStatus, new String(output.toByteArray()));

    if (!compiledTransformFile.canRead())
        throw new IOException(StringUtils.capitalize(transformTypeString)
                + " executable output from compiler was not readable: " + compiledTransformFile.toString());

    if (!compiledTransformFile.canExecute())
        compiledTransformFile.setExecutable(true, false);

    return compiledTransformFile;
}

From source file:ddf.content.plugin.video.VideoThumbnailPlugin.java

private DefaultExecuteResultHandler executeFFmpeg(final CommandLine command, final int timeoutSeconds,
        final PumpStreamHandler streamHandler) throws IOException {
    final ExecuteWatchdog watchdog = new ExecuteWatchdog(timeoutSeconds * 1000);
    final Executor executor = new DefaultExecutor();
    executor.setWatchdog(watchdog);/*from   w  w w . j  a  v a  2  s  .  c o  m*/

    if (streamHandler != null) {
        executor.setStreamHandler(streamHandler);
    }

    final DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
    executor.execute(command, resultHandler);

    return resultHandler;
}

From source file:com.boundlessgeo.wps.grass.GrassProcesses.java

/**
 * Define a GISBASE/LOCATION_NAME/PERMANENT for the provided dem.
 *
 * The dem is staged in GISBASE/dem.tif and then moved to
 * GISBASE/LOCATION_NAME/PERMANENT/dem.tif
 *
 * @param operation/*from w  w  w .jav a  2s. c o m*/
 *            Name used for the location on disk
 * @param dem
 *            File used to establish CRS and Bounds for the location
 * @return Array of files consisting of {GISBASE, LOCATION, MAPSET, dem.tif}
 * @throws Exception
 */
static File location(File location, File raster) throws Exception {
    // grass70 + ' -c ' + myfile + ' -e ' + location_path
    CommandLine cmd = new CommandLine(EXEC);
    cmd.addArgument("-c");
    cmd.addArgument("${raster}");
    cmd.addArgument("-e");
    cmd.addArgument("${location}");
    cmd.setSubstitutionMap(new KVP("raster", raster, "location", location));
    LOGGER.info(cmd.toString());

    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValue(0);
    ExecuteWatchdog watchdog = new ExecuteWatchdog(60000);
    executor.setWatchdog(watchdog);
    executor.setStreamHandler(new PumpStreamHandler(System.out));

    LOGGER.info(cmd.toString());
    try {
        int exitValue = executor.execute(cmd);
    } catch (ExecuteException fail) {
        LOGGER.warning("grass70:" + fail.getLocalizedMessage());
        throw fail;
    }

    File mapset = new File(location, "PERMANENT");
    if (!mapset.exists()) {
        throw new IllegalStateException("Did not create mapset " + mapset);
    }
    return location;
}

From source file:it.drwolf.ridire.index.cwb.CWBFrequencyList.java

private String getFrequencyList(boolean deleteFLFile, List<String> semDescription, List<String> funDescription,
        int quantityP, String type, Integer threshold, boolean sorted) {
    CommandLine commandLine = CommandLine.parse(this.cwbscanExecutable);
    commandLine.addArgument("-q");
    if (threshold != null && threshold > 0) {
        commandLine.addArgument("-f");
        commandLine.addArgument(threshold + "");
    }/*from   w  ww  .  j  av  a  2s  .  c om*/
    commandLine.addArgument("-r").addArgument(this.cqpRegistry);
    commandLine.addArgument("-C");
    commandLine.addArgument(this.cqpCorpusName);
    if (type.equals("forma")) {
        commandLine.addArgument("word+0");
    } else if (type.equals("PoS")) {
        commandLine.addArgument("pos+0");
    } else if (type.equals("easypos")) {
        commandLine.addArgument("easypos+0");
    } else if (type.equals("lemma")) {
        commandLine.addArgument("lemma+0");
    } else if (type.equals("PoS-forma")) {
        commandLine.addArgument("pos+0");
        commandLine.addArgument("word+0");
    } else if (type.equals("PoS-lemma")) {
        commandLine.addArgument("pos+0");
        commandLine.addArgument("lemma+0");
    }
    String semFuncParam = "";
    if (funDescription != null && funDescription.size() > 0 && funDescription.get(0) != null
            && funDescription.get(0).trim().length() > 0
            || semDescription != null && semDescription.size() > 0 && semDescription.get(0) != null
                    && semDescription.get(0).trim().length() > 0) {
        semFuncParam = "?";
        if (funDescription != null && funDescription.size() > 0 && funDescription.get(0) != null
                && funDescription.get(0).trim().length() > 0) {
            String fd = StringUtils.join(funDescription, "\\|");
            semFuncParam += "text_functional=/\\(" + fd + "\\)/ ";
        }
        if (semDescription != null && semDescription.size() > 0 && semDescription.get(0) != null
                && semDescription.get(0).trim().length() > 0) {
            String sd = StringUtils.join(semDescription, "\\|");
            semFuncParam += "text_semantic=/\\(" + sd + "\\)/ ";

        }
        commandLine.addArgument(semFuncParam);
    }
    if (sorted) {
        commandLine.addArgument("|");
        commandLine.addArgument("sort");
        commandLine.addArgument("-nr");
        commandLine.addArgument("-k");
        commandLine.addArgument("1");
    }
    if (quantityP > 0) {
        commandLine.addArgument("|");
        commandLine.addArgument("head");
        commandLine.addArgument("-" + quantityP);
    }
    File flTempFile = null;
    try {
        flTempFile = File.createTempFile("ridireFL", null);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    commandLine.addArgument(" > ");
    commandLine.addArgument(flTempFile.getAbsolutePath());
    String c = commandLine.toString();
    try {
        File tempSh = File.createTempFile("ridireSH", ".sh");
        FileUtils.writeStringToFile(tempSh, c);
        tempSh.setExecutable(true);
        commandLine = CommandLine.parse(tempSh.getAbsolutePath());
        DefaultExecutor executor = new DefaultExecutor();
        executor.setExitValue(0);
        ExecuteWatchdog watchdog = new ExecuteWatchdog(CWBFrequencyList.TIMEOUT);
        executor.setWatchdog(watchdog);
        ByteArrayOutputStream baosStdOut = new ByteArrayOutputStream(1024);
        ByteArrayOutputStream baosStdErr = new ByteArrayOutputStream(1024);
        ExecuteStreamHandler executeStreamHandler = new PumpStreamHandler(baosStdOut, baosStdErr, null);
        executor.setStreamHandler(executeStreamHandler);
        int exitValue = 0;
        exitValue = executor.execute(commandLine);
        FileUtils.deleteQuietly(tempSh);
        if (exitValue == 0) {
            StrTokenizer strTokenizer = new StrTokenizer();
            this.frequencyList = new ArrayList<FrequencyItem>();
            List<String> lines = FileUtils.readLines(flTempFile);
            for (String line : lines) {
                strTokenizer.reset(line);
                String[] tokens = strTokenizer.getTokenArray();
                if (tokens.length == 2) {
                    FrequencyItem frequencyItem = new FrequencyItem(tokens[1],
                            Integer.parseInt(tokens[0].trim()));
                    this.frequencyList.add(frequencyItem);
                } else if (tokens.length == 3) {
                    FrequencyItem frequencyItem = new FrequencyItem(tokens[2], tokens[1],
                            Integer.parseInt(tokens[0].trim()));
                    this.frequencyList.add(frequencyItem);
                }
            }
            if (deleteFLFile) {
                FileUtils.deleteQuietly(flTempFile);
            }
        }
    } catch (ExecuteException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return flTempFile.getAbsolutePath();
}

From source file:com.alibaba.jstorm.utils.JStormUtils.java

/**
 * If it is backend, please set resultHandler, such as DefaultExecuteResultHandler If it is frontend, ByteArrayOutputStream.toString get the result
 * <p/>//  w  w w .j  av  a  2  s  .  c  om
 * This function don't care whether the command is successfully or not
 * 
 * @param command
 * @param environment
 * @param workDir
 * @param resultHandler
 * @return
 * @throws IOException
 */
public static ByteArrayOutputStream launchProcess(String command, final Map environment, final String workDir,
        ExecuteResultHandler resultHandler) throws IOException {

    String[] cmdlist = command.split(" ");

    CommandLine cmd = new CommandLine(cmdlist[0]);
    for (String cmdItem : cmdlist) {
        if (StringUtils.isBlank(cmdItem) == false) {
            cmd.addArgument(cmdItem);
        }
    }

    DefaultExecutor executor = new DefaultExecutor();

    executor.setExitValue(0);
    if (StringUtils.isBlank(workDir) == false) {
        executor.setWorkingDirectory(new File(workDir));
    }

    ByteArrayOutputStream out = new ByteArrayOutputStream();

    PumpStreamHandler streamHandler = new PumpStreamHandler(out, out);
    if (streamHandler != null) {
        executor.setStreamHandler(streamHandler);
    }

    try {
        if (resultHandler == null) {
            executor.execute(cmd, environment);
        } else {
            executor.execute(cmd, environment, resultHandler);
        }
    } catch (ExecuteException e) {

        // @@@@
        // failed to run command
    }

    return out;

}

From source file:it.drwolf.ridire.session.async.Mapper.java

private StringWithEncoding createPlainTextResource(File f, CrawledResource cr, EntityManager entityManager)
        throws SAXException, TikaException, IOException, TransformerConfigurationException,
        InterruptedException {/*from www . j  a va  2 s  . co m*/
    File resourceDir = new File(FilenameUtils.getFullPath(f.getCanonicalPath().replaceAll("__\\d+", ""))
            + JobMapperMonitor.RESOURCESDIR);
    String alchemyKey = entityManager.find(Parameter.class, Parameter.ALCHEMY_KEY.getKey()).getValue();
    String readabilityKey = entityManager.find(Parameter.class, Parameter.READABILITY_KEY.getKey()).getValue();
    String resourceFileName = cr.getDigest() + ".gz";
    File resourceFile = new File(resourceDir, resourceFileName);
    StringWithEncoding rawContentAndEncoding = null;
    String contentType = cr.getContentType();
    // long t1 = System.currentTimeMillis();
    if (contentType != null && contentType.contains("application/msword")) {
        rawContentAndEncoding = this.transformDOC2HTML(resourceFile, entityManager);
    }
    if (contentType != null && contentType.contains("application/rtf")) {
        rawContentAndEncoding = this.transformRTF2HTML(resourceFile, entityManager);
    }
    if (contentType != null && contentType.contains("text/plain")) {
        // txt -> html -> txt is for txt cleaning
        rawContentAndEncoding = this.transformTXT2HTML(resourceFile, entityManager);
    }
    if (contentType != null && contentType.contains("pdf")) {
        rawContentAndEncoding = this.transformPDF2HTML(resourceFile, entityManager);
    }
    if (contentType != null && contentType.contains("html")) {
        rawContentAndEncoding = this.getGuessedEncodingAndSetRawContentFromGZFile(resourceFile);
    }
    // long t2 = System.currentTimeMillis();
    // System.out.println("Transformation: " + (t2 - t1));
    if (rawContentAndEncoding != null) {
        if (rawContentAndEncoding.getEncoding() == null) {
            rawContentAndEncoding = new StringWithEncoding(rawContentAndEncoding.getString(), "UTF8");
        }
        // t1 = System.currentTimeMillis();
        String cleanText = this.replaceUnsupportedChars(rawContentAndEncoding.getString());
        rawContentAndEncoding = new StringWithEncoding(cleanText, rawContentAndEncoding.getEncoding());
        File tmpFile = File.createTempFile("ridire", null);
        FileUtils.writeStringToFile(tmpFile, rawContentAndEncoding.getString(), "UTF-8");
        String ridireCleanerJar = entityManager
                .find(CommandParameter.class, CommandParameter.RIDIRE_CLEANER_EXECUTABLE_KEY).getCommandValue();
        String host = entityManager.find(Parameter.class, Parameter.READABILITY_HOSTAPP.getKey()).getValue();
        CommandLine commandLine = CommandLine
                .parse("java -Xmx128m -Djava.io.tmpdir=" + this.tempDir + " -jar " + ridireCleanerJar);
        commandLine.addArgument("-f");
        commandLine.addArgument(tmpFile.getPath());
        commandLine.addArgument("-e");
        commandLine.addArgument("UTF-8");
        commandLine.addArgument("-h");
        commandLine.addArgument(host);
        commandLine.addArgument("-k");
        commandLine.addArgument(alchemyKey);
        commandLine.addArgument("-r");
        commandLine.addArgument(readabilityKey);
        DefaultExecutor executor = new DefaultExecutor();
        executor.setExitValue(0);
        ExecuteWatchdog watchdog = new ExecuteWatchdog(Mapper.READABILITY_TIMEOUT);
        executor.setWatchdog(watchdog);
        ByteArrayOutputStream baosStdOut = new ByteArrayOutputStream(1024);
        ByteArrayOutputStream baosStdErr = new ByteArrayOutputStream(1024);
        ExecuteStreamHandler executeStreamHandler = new PumpStreamHandler(baosStdOut, baosStdErr, null);
        executor.setStreamHandler(executeStreamHandler);
        int exitValue = executor.execute(commandLine);
        if (exitValue == 0) {
            rawContentAndEncoding = new StringWithEncoding(baosStdOut.toString(), "UTF-8");
            // TODO filter real errors
            rawContentAndEncoding.setCleaner(baosStdErr.toString().trim());
        }
        FileUtils.deleteQuietly(tmpFile);
    }
    return rawContentAndEncoding;
}