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

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

Introduction

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

Prototype

public PumpStreamHandler(final OutputStream outAndErr) 

Source Link

Document

Construct a new PumpStreamHandler.

Usage

From source file:org.nps.autopsypycaffe.NPSPyCaffeFactory.java

public NPSPyCaffeFactory() {
    IngestServices services = IngestServices.getInstance();
    props = new Properties();
    //The user directory is where the plugin got installed
    File userDir = PlatformUtil.getUserDirectory();
    basePath = userDir.toString();//from  www.  j  ava  2  s  . c  om
    // Search for all directories in the detectors directory.  This is the list
    // of all the detector types.
    if (new File(basePath + "/NPSPyCaffe/detectors").exists() == false) {
        // When we run in the netbeans debugger basePath is up two directories
        basePath = basePath + "/../../release/NPSPyCaffe/detectors/";
    } else
        basePath = basePath + "/NPSPyCaffe/detectors/";
    String[] dlist = new File(basePath).list();
    for (String name : dlist) {
        if (new File(basePath + name).isDirectory()) {
            detectorTypes.add(name);
        }
    }
    if (detectorTypes.size() == 0) {
        IngestMessage msg = IngestMessage.createErrorMessage(NPSPyCaffeFactory.getModuleName(),
                "Congigure Error!", "No Detector types found!");
        services.postMessage(msg);
    } else
        for (String det : detectorTypes) {
            String[] plist = new File(basePath + det).list();
            for (String name : plist) {
                if (name.endsWith(".properties")) {
                    // Read anything that ends with .properties
                    File propfile = new File(basePath + det + "/" + name);
                    if (propfile.exists() == true) {
                        try {
                            FileInputStream in = new FileInputStream(propfile);
                            props.load(in);
                            in.close();
                            if (name.equals("detector.properties")) {
                                // main property file describing the detector type
                                boolean gpu = checkForGPU(det);
                                hasGPU.put(det, gpu);
                            } else {
                                // specific detector property file so use name of file as detector name
                                int idx = name.indexOf(".properties");
                                String detName = name.substring(0, idx);
                                detectorNames.add(det + "." + detName);
                            }
                        } catch (FileNotFoundException ex) {
                            logger.log(Level.SEVERE, "Could not Find detector.properties file");
                        } catch (IOException ex) {
                            logger.log(Level.SEVERE, ex.getMessage());
                        }
                    }
                }
            }

            for (String name : plist) {
                if (name.endsWith(".properties")) {

                }
            }
        }
    // Find Python Exec
    try {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        CommandLine args = CommandLine.parse("where.exe");
        args.addArgument("python");
        DefaultExecutor exec = new DefaultExecutor();
        PumpStreamHandler stdpump = new PumpStreamHandler(outStream);
        exec.setStreamHandler(stdpump);
        exec.execute(args);
        String whereOut = outStream.toString();
        String[] lines = StringUtils.split(whereOut, "\r\n");
        pythonExec = lines[0];

    } catch (IOException ex) {
    }

}

From source file:org.openflamingo.engine.util.FileReader.java

/**
 * ? ??  ??  ? ? .//from w w w .  j a  v  a  2s  .c  o  m
 *
 * @param start     ??
 * @param end       ??
 * @param filename ?? ?
 * @return ?? 
 * @throws IOException          ?? ??   
 * @throws InterruptedException       
 */
public static String read(long start, long end, String filename) throws IOException, InterruptedException {
    String command = org.slf4j.helpers.MessageFormatter
            .arrayFormat("sed '{},{}!d' {}", new Object[] { start, end, filename }).getMessage();

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
    PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(out);

    CommandLine cmdLine = CommandLine.parse(command);
    ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 1000);
    Executor executor = new DefaultExecutor();
    executor.setStreamHandler(pumpStreamHandler);
    executor.setExitValue(1);
    executor.setWatchdog(watchdog);
    executor.execute(cmdLine, resultHandler);

    resultHandler.waitFor();

    return new String(out.toByteArray());
}

From source file:org.openflamingo.engine.util.FileReader.java

/**
 * ? ?? ??  ? ./*from   www  .java 2s  .com*/
 *
 * @param filename ??  ? ?
 * @return  ?? ?? 
 * @throws IOException          ?? ??   
 * @throws InterruptedException       
 */
public static int lines(String filename) throws IOException, InterruptedException {
    String command = org.slf4j.helpers.MessageFormatter.arrayFormat("sed -n '$=' {}", new Object[] { filename })
            .getMessage();

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
    PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(out);

    CommandLine cmdLine = CommandLine.parse(command);
    ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 1000);
    Executor executor = new DefaultExecutor();
    executor.setStreamHandler(pumpStreamHandler);
    executor.setExitValue(1);
    executor.setWatchdog(watchdog);
    executor.execute(cmdLine, resultHandler);

    resultHandler.waitFor();

    return Integer.parseInt(new String(out.toByteArray()).trim());
}

From source file:org.openhab.binding.exec.internal.ExecBinding.java

/**
 * <p>Executes <code>commandLine</code>. Sometimes (especially observed on 
 * MacOS) the commandLine isn't executed properly. In that cases another 
 * exec-method is to be used. To accomplish this please use the special 
 * delimiter '<code>@@</code>'. If <code>commandLine</code> contains this 
 * delimiter it is split into a String[] array and the special exec-method
 * is used.</p>//w w w  . j  a v a  2s  .  com
 * <p>A possible {@link IOException} gets logged but no further processing is
 * done.</p> 
 * 
 * @param commandLine the command line to execute
 * @return response data from executed command line 
 */
private String executeCommandAndWaitResponse(String commandLine) {
    String retval = null;

    CommandLine cmdLine = null;

    if (commandLine.contains(CMD_LINE_DELIMITER)) {
        String[] cmdArray = commandLine.split(CMD_LINE_DELIMITER);
        cmdLine = new CommandLine(cmdArray[0]);

        for (int i = 1; i < cmdArray.length; i++) {
            cmdLine.addArgument(cmdArray[i], false);
        }
    } else {
        cmdLine = CommandLine.parse(commandLine);
    }

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

    ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout);
    Executor executor = new DefaultExecutor();

    ByteArrayOutputStream stdout = new ByteArrayOutputStream();
    PumpStreamHandler streamHandler = new PumpStreamHandler(stdout);

    executor.setExitValue(1);
    executor.setStreamHandler(streamHandler);
    executor.setWatchdog(watchdog);

    try {
        executor.execute(cmdLine, resultHandler);
        logger.debug("executed commandLine '{}'", commandLine);
    } catch (ExecuteException e) {
        logger.error("couldn't execute commandLine '" + commandLine + "'", e);
    } catch (IOException e) {
        logger.error("couldn't execute commandLine '" + commandLine + "'", e);
    }

    // some time later the result handler callback was invoked so we
    // can safely request the exit code
    try {
        resultHandler.waitFor();
        int exitCode = resultHandler.getExitValue();
        retval = StringUtils.chomp(stdout.toString());
        logger.debug("exit code '{}', result '{}'", exitCode, retval);

    } catch (InterruptedException e) {
        logger.error("Timeout occured when executing commandLine '" + commandLine + "'", e);
    }

    return retval;
}

From source file:org.openhab.io.net.exec.ExecUtil.java

/**
 * <p>/*from  ww w  .j a  v a2s  .c om*/
 * Executes <code>commandLine</code>. Sometimes (especially observed on
 * MacOS) the commandLine isn't executed properly. In that cases another
 * exec-method is to be used. To accomplish this please use the special
 * delimiter '<code>@@</code>'. If <code>commandLine</code> contains this
 * delimiter it is split into a String[] array and the special exec-method
 * is used.
 * </p>
 * <p>
 * A possible {@link IOException} gets logged but no further processing is
 * done.
 * </p>
 * 
 * @param commandLine
 *            the command line to execute
 * @param timeout
 *            timeout for execution in milliseconds
 * @return response data from executed command line
 */
public static String executeCommandLineAndWaitResponse(String commandLine, int timeout) {
    String retval = null;

    CommandLine cmdLine = null;

    if (commandLine.contains(CMD_LINE_DELIMITER)) {
        String[] cmdArray = commandLine.split(CMD_LINE_DELIMITER);
        cmdLine = new CommandLine(cmdArray[0]);

        for (int i = 1; i < cmdArray.length; i++) {
            cmdLine.addArgument(cmdArray[i], false);
        }
    } else {
        cmdLine = CommandLine.parse(commandLine);
    }

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

    ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout);
    Executor executor = new DefaultExecutor();

    ByteArrayOutputStream stdout = new ByteArrayOutputStream();
    PumpStreamHandler streamHandler = new PumpStreamHandler(stdout);

    executor.setExitValue(1);
    executor.setStreamHandler(streamHandler);
    executor.setWatchdog(watchdog);

    try {
        executor.execute(cmdLine, resultHandler);
        logger.debug("executed commandLine '{}'", commandLine);
    } catch (ExecuteException e) {
        logger.error("couldn't execute commandLine '" + commandLine + "'", e);
    } catch (IOException e) {
        logger.error("couldn't execute commandLine '" + commandLine + "'", e);
    }

    // some time later the result handler callback was invoked so we
    // can safely request the exit code
    try {
        resultHandler.waitFor();
        int exitCode = resultHandler.getExitValue();
        retval = StringUtils.chomp(stdout.toString());
        if (resultHandler.getException() != null) {
            logger.warn(resultHandler.getException().getMessage());
        } else {
            logger.debug("exit code '{}', result '{}'", exitCode, retval);
        }

    } catch (InterruptedException e) {
        logger.error("Timeout occured when executing commandLine '" + commandLine + "'", e);
    }

    return retval;
}

From source file:org.openqa.selenium.iphone.IPhoneSimulatorBinary.java

public void launch() {
    Executor executor = new DefaultExecutor();
    executor.setStreamHandler(new PumpStreamHandler(createOutputStream()));
    try {//  www  .  ja  va  2 s.  c  om
        exitCode = executor.execute(commandLine);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.owasp.goatdroid.gui.emulator.Emulator.java

static public boolean isAndroidDeviceAvailable() {

    ByteArrayOutputStream stdout = new ByteArrayOutputStream();
    PumpStreamHandler psh = new PumpStreamHandler(stdout);
    try {/*  w  w  w.  ja  v  a2s.c o  m*/

        CommandLine cmdLine = new CommandLine(
                Config.getSDKPath() + getSlash() + "platform-tools" + getSlash() + "adb");
        cmdLine.addArgument("devices", false);
        DefaultExecutor executor = new DefaultExecutor();
        executor.setStreamHandler(psh);
        executor.execute(cmdLine);
        String stringy = stdout.toString();
        stdout.close();
        /*
         * Shell command response will be 27 characters in length if there
         * are no devices currently attached.
         * 
         * Output is: List of devices attached \n\n
         */
        if (stringy.length() > 27)
            return true;
        else
            return false;
    } catch (CorruptConfigException e) {
        return false;
    } catch (IOException e) {
        return false;
    }
}

From source file:org.owasp.goatdroid.gui.emulator.Emulator.java

static public String[] getAvailableAndroidDevices() {

    ByteArrayOutputStream stdout = new ByteArrayOutputStream();
    PumpStreamHandler psh = new PumpStreamHandler(stdout);
    try {//from  w w  w .jav a  2s.  com

        CommandLine cmdLine = new CommandLine(
                Config.getSDKPath() + getSlash() + "platform-tools" + getSlash() + "adb");
        cmdLine.addArgument("devices", false);
        DefaultExecutor executor = new DefaultExecutor();
        executor.setStreamHandler(psh);
        executor.execute(cmdLine);
        String output = stdout.toString();
        /*
         * Shell command response will be 27 characters in length if there
         * are no devices currently attached.
         * 
         * Output is: List of devices attached \n\n
         */
        if (output.length() > 27) {
            List<String> devices = new ArrayList<String>(Arrays.asList(output.split("\n")));
            /*
             * This removes the first line.. We don't care about the first
             * one [0] because that's just the first line (List of devices
             * attached \n)
             */
            devices.remove(0);
            for (int count = 0; count < devices.size(); count++) {
                devices.set(count, devices.get(count).replaceAll("\t.*", "").trim());
            }
            return devices.toArray(new String[devices.size()]);
            /*
             * If there were no devices, return an empty list
             */
        } else {
            return new String[0];
        }
    }

    catch (CorruptConfigException e) {
        return new String[0];
    } catch (IOException e) {
        return new String[0];
    }
}

From source file:org.owasp.goatdroid.gui.emulator.EmulatorWorker.java

static public String startEmulator(String deviceName)
        throws FileNotFoundException, IOException, CorruptConfigException {
    HashMap<String, String> settings = Config.readConfig();
    String emulator = settings.get("sdk_path") + getSlash() + "tools" + getSlash();
    if (getOperatingSystem().startsWith("windows"))
        emulator += "emulator-arm.exe";
    else//from w w  w . j a  va 2  s .c om
        emulator += "emulator";
    CommandLine cmdLine = new CommandLine(emulator);
    // If the Windows path has spaces, we don't even want to deal with it
    // will ignore parameters, known issue
    if (getOperatingSystem().startsWith("windows")) {
        cmdLine.addArgument("@" + deviceName.toLowerCase().replace(".avd", ""));
        cmdLine.addArgument("-scale");
        if (Config.getAndroidEmulatorScreenSize() == 0)
            cmdLine.addArgument("1");
        else if (Config.getAndroidEmulatorScreenSize() > 3)
            cmdLine.addArgument("3");
        else
            cmdLine.addArgument(Integer.toString(Config.getAndroidEmulatorScreenSize()));
    } else {
        cmdLine.addArgument("-avd", false);
        cmdLine.addArgument(deviceName.toLowerCase().replace(".avd", ""), false);
        cmdLine.addArgument("-scale");
        if (Config.getAndroidEmulatorScreenSize() < 1)
            cmdLine.addArgument("1");
        else if (Config.getAndroidEmulatorScreenSize() > 3)
            cmdLine.addArgument("3");
        else
            cmdLine.addArgument(Integer.toString(Config.getAndroidEmulatorScreenSize()));
    }
    if (!(settings.get("proxy_host").equals("") || settings.get("proxy_port").equals(""))) {
        cmdLine.addArgument("-http-proxy");
        cmdLine.addArgument("http://" + settings.get("proxy_host") + ":" + settings.get("proxy_port"));
    }
    ByteArrayOutputStream stdout = new ByteArrayOutputStream();
    PumpStreamHandler psh = new PumpStreamHandler(stdout);
    DefaultExecutor executor = new DefaultExecutor();
    try {
        executor.setStreamHandler(psh);
        executor.execute(cmdLine);
        return Constants.SUCCESS;
    } catch (ExecuteException e) {
        return stdout.toString();
    } catch (IOException e) {
        return Constants.INVALID_SDK_PATH;
    }
}

From source file:org.owasp.goatdroid.gui.emulator.EmulatorWorker.java

static public String pushAppOntoDevice(String appPath) {

    ByteArrayOutputStream stdout = new ByteArrayOutputStream();
    PumpStreamHandler psh = new PumpStreamHandler(stdout);
    CommandLine cmdLine = new CommandLine(sdkPath + getSlash() + "platform-tools" + getSlash() + "adb");
    cmdLine.addArgument("install");
    cmdLine.addArgument(appPath, false);
    DefaultExecutor executor = new DefaultExecutor();
    try {/*  w  ww .  j a  va2 s  . c o m*/
        executor.setStreamHandler(psh);
        executor.execute(cmdLine);
        return stdout.toString();
    } catch (ExecuteException e) {
        return Constants.UNEXPECTED_ERROR;
    } catch (IOException e) {
        return Constants.UNEXPECTED_ERROR;
    }
}