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:org.apache.stratos.python.cartridge.agent.integration.tests.PythonAgentIntegrationTest.java

/**
 * Execute shell command/* w w  w  .j  a v  a 2  s  .co m*/
 *
 * @param commandText Command string to be executed
 */
protected ByteArrayOutputStreamLocal executeCommand(final String commandText, int timeout) {
    final ByteArrayOutputStreamLocal outputStream = new ByteArrayOutputStreamLocal();
    try {
        CommandLine commandline = CommandLine.parse(commandText);
        DefaultExecutor exec = new DefaultExecutor();
        PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
        exec.setWorkingDirectory(new File(PythonAgentIntegrationTest.class.getResource(PATH_SEP).getPath()
                + PATH_SEP + ".." + PATH_SEP + PYTHON_AGENT_DIR_NAME));
        exec.setStreamHandler(streamHandler);
        ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout);
        exec.setWatchdog(watchdog);
        exec.execute(commandline, new ExecuteResultHandler() {
            @Override
            public void onProcessComplete(int i) {
                log.info(commandText + " process completed");
            }

            @Override
            public void onProcessFailed(ExecuteException e) {
                log.error(commandText + " process failed", e);
            }
        });
        executorList.put(commandText, exec);
        return outputStream;
    } catch (Exception e) {
        log.error(outputStream.toString(), e);
        throw new RuntimeException(e);
    }
}

From source file:org.apache.stratos.python.cartridge.agent.test.PythonAgentTestManager.java

/**
 * Execute shell command//from   w  w  w .  j  a  va2 s  .  com
 *
 * @param commandText
 */
protected ByteArrayOutputStreamLocal executeCommand(final String commandText) {
    final ByteArrayOutputStreamLocal outputStream = new ByteArrayOutputStreamLocal();
    try {
        CommandLine commandline = CommandLine.parse(commandText);
        DefaultExecutor exec = new DefaultExecutor();
        PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
        exec.setWorkingDirectory(new File(PythonAgentTestManager.class.getResource(PATH_SEP).getPath()
                + PATH_SEP + ".." + PATH_SEP + PYTHON_AGENT_DIR_NAME));
        exec.setStreamHandler(streamHandler);
        ExecuteWatchdog watchdog = new ExecuteWatchdog(TIMEOUT);
        exec.setWatchdog(watchdog);
        exec.execute(commandline, new ExecuteResultHandler() {
            @Override
            public void onProcessComplete(int i) {
                log.info(commandText + " process completed");
            }

            @Override
            public void onProcessFailed(ExecuteException e) {
                log.error(commandText + " process failed", e);
            }
        });
        executorList.put(commandText, exec);
        return outputStream;
    } catch (Exception e) {
        log.error(outputStream.toString(), e);
        throw new RuntimeException(e);
    }
}

From source file:org.apache.stratos.python.cartridge.agent.test.PythonCartridgeAgentTest.java

/**
 * Execute shell command//from w ww. ja v  a2s . c o m
 *
 * @param commandText
 */
private ByteArrayOutputStreamLocal executeCommand(final String commandText) {
    final ByteArrayOutputStreamLocal outputStream = new ByteArrayOutputStreamLocal();
    try {
        CommandLine commandline = CommandLine.parse(commandText);
        DefaultExecutor exec = new DefaultExecutor();
        PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
        exec.setStreamHandler(streamHandler);
        ExecuteWatchdog watchdog = new ExecuteWatchdog(TIMEOUT);
        exec.setWatchdog(watchdog);
        exec.execute(commandline, new ExecuteResultHandler() {
            @Override
            public void onProcessComplete(int i) {
                log.info(commandText + " process completed");
            }

            @Override
            public void onProcessFailed(ExecuteException e) {
                log.error(commandText + " process failed", e);
            }
        });
        executorList.put(commandText, exec);
        return outputStream;
    } catch (Exception e) {
        log.error(outputStream.toString(), e);
        throw new RuntimeException(e);
    }
}

From source file:org.apache.tika.parser.geo.topic.GeoParser.java

public HashMap<String, ArrayList<String>> searchGeoNames(ArrayList<String> locationNameEntities)
        throws ExecuteException, IOException {
    CommandLine cmdLine = new CommandLine("lucene-geo-gazetteer");
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    cmdLine.addArgument("-s");
    for (String name : locationNameEntities) {
        cmdLine.addArgument(name);// w ww .j  a v a2  s  . c  o  m
    }

    LOG.fine("Executing: " + cmdLine);
    DefaultExecutor exec = new DefaultExecutor();
    exec.setExitValue(0);
    ExecuteWatchdog watchdog = new ExecuteWatchdog(60000);
    exec.setWatchdog(watchdog);
    PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
    exec.setStreamHandler(streamHandler);
    int exitValue = exec.execute(cmdLine, EnvironmentUtils.getProcEnvironment());
    String outputJson = outputStream.toString("UTF-8");
    JSONArray json = (JSONArray) JSONValue.parse(outputJson);

    HashMap<String, ArrayList<String>> returnHash = new HashMap<String, ArrayList<String>>();
    for (int i = 0; i < json.size(); i++) {
        JSONObject obj = (JSONObject) json.get(i);
        for (Object key : obj.keySet()) {
            String theKey = (String) key;
            JSONArray vals = (JSONArray) obj.get(theKey);
            ArrayList<String> stringVals = new ArrayList<String>(vals.size());
            for (int j = 0; j < vals.size(); j++) {
                String val = (String) vals.get(j);
                stringVals.add(val);
            }

            returnHash.put(theKey, stringVals);
        }
    }

    return returnHash;

}

From source file:org.apache.tika.parser.ocr.TesseractOCRParser.java

/**
 * This method is used to process the image to an OCR-friendly format.
 * @param streamingObject input image to be processed
 * @param config TesseractOCRconfig class to get ImageMagick properties
 * @throws IOException if an input error occurred
 * @throws TikaException if an exception timed out
 *///w w  w  .  j ava2 s  .c om
private void processImage(File streamingObject, TesseractOCRConfig config) throws IOException, TikaException {

    // fetch rotation script from resources
    InputStream in = getClass().getResourceAsStream("rotation.py");
    TemporaryResources tmp = new TemporaryResources();
    File rotationScript = tmp.createTemporaryFile();
    Files.copy(in, rotationScript.toPath(), StandardCopyOption.REPLACE_EXISTING);

    String cmd = "python " + rotationScript.getAbsolutePath() + " -f " + streamingObject.getAbsolutePath();
    String angle = "0";

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

    // determine the angle of rotation required to make the text horizontal
    CommandLine cmdLine = CommandLine.parse(cmd);
    if (hasPython()) {
        try {
            executor.execute(cmdLine);
            angle = outputStream.toString("UTF-8").trim();
        } catch (Exception e) {

        }
    }

    // process the image - parameter values can be set in TesseractOCRConfig.properties
    String line = "convert -density " + config.getDensity() + " -depth " + config.getDepth() + " -colorspace "
            + config.getColorspace() + " -filter " + config.getFilter() + " -resize " + config.getResize()
            + "% -rotate " + angle + " " + streamingObject.getAbsolutePath() + " "
            + streamingObject.getAbsolutePath();
    cmdLine = CommandLine.parse(line);
    try {
        executor.execute(cmdLine);
    } catch (Exception e) {

    }

    tmp.close();
}

From source file:org.apache.tika.parser.pot.PooledTimeSeriesParser.java

private String computePoT(File input) throws IOException, TikaException {

    CommandLine cmdLine = new CommandLine("pooled-time-series");
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    cmdLine.addArgument("-f");
    cmdLine.addArgument(input.getAbsolutePath());
    LOG.trace("Executing: {}", cmdLine);
    DefaultExecutor exec = new DefaultExecutor();
    exec.setExitValue(0);//from w w w  .  j ava  2s .  com
    ExecuteWatchdog watchdog = new ExecuteWatchdog(60000);
    exec.setWatchdog(watchdog);
    PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
    exec.setStreamHandler(streamHandler);
    int exitValue = exec.execute(cmdLine, EnvironmentUtils.getProcEnvironment());
    return outputStream.toString("UTF-8");

}

From source file:org.apache.zeppelin.interpreter.launcher.Kubectl.java

public ExecuteWatchdog portForward(String resource, String[] ports) throws IOException {
    DefaultExecutor executor = new DefaultExecutor();
    CommandLine cmd = new CommandLine(kubectlCmd);
    cmd.addArguments("port-forward");
    cmd.addArguments(resource);//from  w ww .  j  av  a 2 s. co  m
    cmd.addArguments(ports);

    ExecuteWatchdog watchdog = new ExecuteWatchdog(-1);
    executor.setWatchdog(watchdog);

    executor.execute(cmd, new ExecuteResultHandler() {
        @Override
        public void onProcessComplete(int i) {
            LOGGER.info("Port-forward stopped");
        }

        @Override
        public void onProcessFailed(ExecuteException e) {
            LOGGER.debug("port-forward process exit", e);
        }
    });

    return watchdog;
}

From source file:org.apache.zeppelin.interpreter.launcher.Kubectl.java

public int execute(String[] args, InputStream stdin, OutputStream stdout, OutputStream stderr)
        throws IOException {
    DefaultExecutor executor = new DefaultExecutor();
    CommandLine cmd = new CommandLine(kubectlCmd);
    cmd.addArguments(args);/*from   ww w  . j a va  2s.c o m*/

    ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 1000);
    executor.setWatchdog(watchdog);

    PumpStreamHandler streamHandler = new PumpStreamHandler(stdout, stderr, stdin);
    executor.setStreamHandler(streamHandler);
    return executor.execute(cmd);
}

From source file:org.apache.zeppelin.interpreter.remote.RemoteInterpreterManagedProcess.java

@Override
public void start(String userName, Boolean isUserImpersonate) {
    // start server process
    try {//from   w w w . j a  v a 2  s  .com
        port = RemoteInterpreterUtils.findRandomAvailablePortOnAllLocalInterfaces();
    } catch (IOException e1) {
        throw new InterpreterException(e1);
    }

    CommandLine cmdLine = CommandLine.parse(interpreterRunner);
    cmdLine.addArgument("-d", false);
    cmdLine.addArgument(interpreterDir, false);
    cmdLine.addArgument("-p", false);
    cmdLine.addArgument(Integer.toString(port), false);
    if (isUserImpersonate && !userName.equals("anonymous")) {
        cmdLine.addArgument("-u", false);
        cmdLine.addArgument(userName, false);
    }
    cmdLine.addArgument("-l", false);
    cmdLine.addArgument(localRepoDir, false);

    executor = new DefaultExecutor();

    ByteArrayOutputStream cmdOut = new ByteArrayOutputStream();
    ProcessLogOutputStream processOutput = new ProcessLogOutputStream(logger);
    processOutput.setOutputStream(cmdOut);

    executor.setStreamHandler(new PumpStreamHandler(processOutput));
    watchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
    executor.setWatchdog(watchdog);

    try {
        Map procEnv = EnvironmentUtils.getProcEnvironment();
        procEnv.putAll(env);

        logger.info("Run interpreter process {}", cmdLine);
        executor.execute(cmdLine, procEnv, this);
        running = true;
    } catch (IOException e) {
        running = false;
        throw new InterpreterException(e);
    }

    long startTime = System.currentTimeMillis();
    while (System.currentTimeMillis() - startTime < getConnectTimeout()) {
        if (!running) {
            try {
                cmdOut.flush();
            } catch (IOException e) {
                // nothing to do
            }
            throw new InterpreterException(new String(cmdOut.toByteArray()));
        }

        try {
            if (RemoteInterpreterUtils.checkIfRemoteEndpointAccessible("localhost", port)) {
                break;
            } else {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    logger.error("Exception in RemoteInterpreterProcess while synchronized reference "
                            + "Thread.sleep", e);
                }
            }
        } catch (Exception e) {
            if (logger.isDebugEnabled()) {
                logger.debug("Remote interpreter not yet accessible at localhost:" + port);
            }
        }
    }
    processOutput.setOutputStream(null);
}

From source file:org.apache.zeppelin.interpreter.remote.RemoteInterpreterProcess.java

public int reference(InterpreterGroup interpreterGroup) {
    synchronized (referenceCount) {
        if (executor == null) {
            // start server process
            try {
                port = RemoteInterpreterUtils.findRandomAvailablePortOnAllLocalInterfaces();
            } catch (IOException e1) {
                throw new InterpreterException(e1);
            }//from   w w w . j av  a 2  s .co  m

            CommandLine cmdLine = CommandLine.parse(interpreterRunner);
            cmdLine.addArgument("-d", false);
            cmdLine.addArgument(interpreterDir, false);
            cmdLine.addArgument("-p", false);
            cmdLine.addArgument(Integer.toString(port), false);

            executor = new DefaultExecutor();

            watchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
            executor.setWatchdog(watchdog);

            running = true;
            try {
                Map procEnv = EnvironmentUtils.getProcEnvironment();
                procEnv.putAll(env);

                logger.info("Run interpreter process {}", cmdLine);
                executor.execute(cmdLine, procEnv, this);
            } catch (IOException e) {
                running = false;
                throw new InterpreterException(e);
            }

            long startTime = System.currentTimeMillis();
            while (System.currentTimeMillis() - startTime < connectTimeout) {
                if (RemoteInterpreterUtils.checkIfRemoteEndpointAccessible("localhost", port)) {
                    break;
                } else {
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                    }
                }
            }

            clientPool = new GenericObjectPool<Client>(new ClientFactory("localhost", port));

            remoteInterpreterEventPoller.setInterpreterGroup(interpreterGroup);
            remoteInterpreterEventPoller.setInterpreterProcess(this);
            remoteInterpreterEventPoller.start();
        }
        return referenceCount.incrementAndGet();
    }
}