Example usage for java.lang ProcessBuilder start

List of usage examples for java.lang ProcessBuilder start

Introduction

In this page you can find the example usage for java.lang ProcessBuilder start.

Prototype

public Process start() throws IOException 

Source Link

Document

Starts a new process using the attributes of this process builder.

Usage

From source file:ape.CorruptCommand.java

/**
 * This method is used to fetch the hdfs config file
 * and then fetch the address of where hdfs blk files
 * are stored from the config file//from  ww w  . java 2  s . co m
 * finally, it returns that a random hdfs blk in that address
 */
private String getCorruptAddress() throws IOException {
    String cmd = "cat $HADOOP_HOME/conf/hdfs-site.xml | grep -A1 'dfs.data.dir' | grep 'value'";
    System.out.println(cmd);
    ProcessBuilder pb = new ProcessBuilder("bash", "-c", cmd);
    pb.redirectErrorStream(true);
    Process sh = null;
    try {

        sh = pb.start();
        if (sh.waitFor() != 0) {
            System.out.println("Executing '" + cmd + "' returned a nonzero exit code.");
            System.out.println("Unable to find HDFS block files");
            Main.logger.info("Executing '" + cmd + "' returned a nonzero exit code.");
            Main.logger.info("Unable to find HDFS block files");
            return null;
        }
    } catch (IOException e) {
        System.out.println("Failed to acquire block address");
        Main.logger.info("Failed to acquire block address");
        e.printStackTrace();
        Main.logger.info(e);
        return null;

    } catch (InterruptedException e) {
        System.out.println("Caught an Interrupt while runnning");
        Main.logger.info("Caught an Interrupt while runnning");
        e.printStackTrace();
        Main.logger.info(e);
        return null;
    }

    InputStream shIn = sh.getInputStream();
    InputStreamReader isr = new InputStreamReader(shIn);
    BufferedReader br = new BufferedReader(isr);
    String line = null;
    try {
        line = br.readLine();
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }

    br.close();
    isr.close();
    line = line.trim();

    int end = line.indexOf("</value>");

    //parse the String and randomly select an address
    String address = line.substring(7, end);

    ArrayList<String> addresses = new ArrayList<String>();

    int idx;

    while ((idx = address.indexOf(',')) != -1) {
        addresses.add(address.substring(0, idx));
        address = address.substring(idx + 1);
    }
    addresses.add(address);

    int index = new Random().nextInt(addresses.size());

    address = addresses.get(index).concat("/current");

    if (Main.VERBOSE) {
        System.out.println("The address of the HDFS data folder is: " + address);
    }
    Main.logger.info("The address of the HDFS data folder is: " + address);

    if (datatype.equalsIgnoreCase("meta")) {
        cmd = "ls " + address + " | grep -i 'blk' |grep -i 'meta' ";
    } else {
        cmd = "ls " + address + " | grep -i 'blk' | grep -v 'meta' ";
    }

    pb = new ProcessBuilder("bash", "-c", cmd);
    pb.redirectErrorStream(true);

    sh = pb.start();

    try {
        if (sh.waitFor() != 0) {
            System.out.println("Getting address of the list of files failed");
            return null;
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
        return null;
    }

    shIn = sh.getInputStream();

    isr = new InputStreamReader(shIn);
    br = new BufferedReader(isr);

    ArrayList<String> data = new ArrayList<String>();

    while ((line = br.readLine()) != null) {
        data.add(line);
    }

    int length = data.size();
    Random rdm = new Random();

    int random = rdm.nextInt(length);

    address = address.concat("/" + data.get(random));

    if (Main.VERBOSE) {
        System.out.println("The location of the data corrupted is " + address);
    }

    // Log the corrupted block
    Main.logger.info("The location of the data corrupted is " + address);

    br.close();
    isr.close();
    shIn.close();

    return address;
}

From source file:de.tudarmstadt.ukp.dkpro.core.RSTAnnotator.java

@Override
public void initialize(UimaContext context) throws ResourceInitializationException {
    super.initialize(context);

    // perform sanity check
    if (sanityCheckOnInit) {
        File rstParserSrcDir = new File(rstParserSrcDirPath);

        // create process
        ProcessBuilder processBuilder = new ProcessBuilder().inheritIO();

        // working dir must be set to the src dir of RST parser
        processBuilder.directory(rstParserSrcDir);

        // run the command
        processBuilder.command("python", new File(rstParserSrcDir, "sanity_check.py").getAbsolutePath());

        try {/*  www. j a  va2 s  .c o  m*/
            Process process = processBuilder.start();

            // and wait
            int returnValue = process.waitFor();

            if (returnValue != 0) {
                throw new RuntimeException("Process exited with code " + returnValue);
            }

        } catch (IOException | InterruptedException e) {
            throw new ResourceInitializationException(e);
        }
    }
}

From source file:net.sf.mavenjython.test.PythonTestMojo.java

public void execute() throws MojoExecutionException {
    // all we have to do is to run nose on the source directory
    List<String> l = new ArrayList<String>();
    if (program.equals("nose")) {
        l.add("nosetests.bat");
        l.add("--failure-detail");
        l.add("--verbose");
    } else {/*from   w w w. j av  a2  s .c  o  m*/
        l.add(program);
    }

    ProcessBuilder pb = new ProcessBuilder(l);
    pb.directory(testOutputDirectory);
    pb.environment().put("JYTHONPATH", ".;" + outputDirectory.getAbsolutePath());
    final Process p;
    getLog().info("starting python tests");
    getLog().info("executing " + pb.command());
    getLog().info("in directory " + testOutputDirectory);
    getLog().info("and also including " + outputDirectory);
    try {
        p = pb.start();
    } catch (IOException e) {
        throw new MojoExecutionException(
                "Python tests execution failed. Provide the executable '" + program + "' in the path", e);
    }
    copyIO(p.getInputStream(), System.out);
    copyIO(p.getErrorStream(), System.err);
    copyIO(System.in, p.getOutputStream());
    try {
        if (p.waitFor() != 0) {
            throw new MojoExecutionException("Python tests failed with return code: " + p.exitValue());
        } else {
            getLog().info("Python tests (" + program + ") succeeded.");
        }
    } catch (InterruptedException e) {
        throw new MojoExecutionException("Python tests were interrupted", e);
    }
}

From source file:loadTest.loadTestLib.LUtil.java

public boolean startDockerSlave(LoadTestConfigModel ltModel) throws InterruptedException, IOException {

    String fileCount = String.valueOf(ltModel.getFileCount());

    if (runInDockerCluster) {
        HashMap<String, Integer> dockerNodes = getDockerNodes();

        Entry<String, Integer> entry = this.getLowestDockerHost();

        startedClusterContainer.put(entry.getKey(), entry.getValue() + 1);

        String dockerCommand = "{" + "\"Hostname\":\"\"," + "\"User\":\"\","
                + "\"Entrypoint\":[\"/bin/bash\",\"/pieShare/pieShareAppIntegrationTests/src/test/resources/docker/internal.sh\"],"
                + "\"Cmd\":[\"slave\",\"" + fileCount.toString() + "\"]," + "\"Memory\":0,"
                + "\"MemorySwap\":0," + "\"AttachStdin\":false," + "\"AttachStdout\":false,"
                + "\"AttachStderr\":false," + "\"PortSpecs\":null," + "\"Privileged\": false,"
                + "\"Tty\":false," + "\"OpenStdin\":false," + "\"StdinOnce\":false," + "\"Env\":null,"
                + "\"Dns\":null," + "\"Image\":\"vauvenal5/loadtest\"," + "\"Volumes\":{},"
                + "\"VolumesFrom\":\"\"," + "\"WorkingDir\":\"\"}";

        String url = entry.getKey() + "/containers/create";
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-type", "application/json");
        con.setDoOutput(true);// w  w w . j  a  va 2  s .c o  m
        con.getOutputStream().write(dockerCommand.getBytes());
        con.getOutputStream().flush();
        con.getOutputStream().close();

        int responseCode = con.getResponseCode();

        if (responseCode != 201) {
            return false;
        }

        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String line = null;
        String msg = "";

        while ((line = in.readLine()) != null) {
            msg += line;
        }

        ObjectMapper mapper = new ObjectMapper();
        JsonNode node = mapper.readTree(msg);

        String containerId = node.get("Id").asText();
        con.disconnect();

        url = entry.getKey() + "/containers/" + containerId + "/start";
        obj = new URL(url);
        con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-type", "application/json");

        responseCode = con.getResponseCode();

        if (responseCode != 204) {
            return false;
        }

        if (!this.runningContainers.containsKey(entry.getKey())) {
            this.runningContainers.put(entry.getKey(), new ArrayList<>());
        }

        this.runningContainers.get(entry.getKey()).add(containerId);

        return true;
    }

    ProcessBuilder processBuilder = new ProcessBuilder("docker", "run", "vauvenal5/loadtest", "slave",
            fileCount);
    Process proc = processBuilder.start();
    this.slaves.add(proc);
    return true;
}

From source file:com.dsdev.mupdate.MainForm.java

private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
    //Set window properties
    this.setLocationRelativeTo(null);
    this.setIconImage(Resources.getImageResource("icon.png").getImage());
    popupDialog.setIconImage(Resources.getImageResource("icon.png").getImage());
    UpdateLogoLabel.setIcon(Resources.getImageResource("update.png"));
    popupDialogImageLabel.setIcon(Resources.getImageResource("alert.png"));

    SimpleSwingWorker worker = new SimpleSwingWorker() {

        @Override/*from   www . ja v  a2  s  . co m*/
        protected void task() {

            //Copy updates
            copyDirectoryAndBackUpOldFiles(new File("./launcherpatch"), new File(".."));

            //Load version config
            JSONObject versionConfig;
            try {
                versionConfig = (JSONObject) JSONValue
                        .parse(FileUtils.readFileToString(new File("./version.json")));
            } catch (IOException ex) {
                showPopupDialog("Warning:  The version file could not be updated!  This may cause problems.");
                System.exit(0);
                return;
            }

            //Get new version from arguments
            String newVersion = "0";
            for (String arg : Arguments) {
                if (arg.startsWith("--version=")) {
                    newVersion = arg.substring(10);
                    break;
                }
            }

            //Save new version file
            try {
                versionConfig.put("moddleversion", newVersion);
                FileUtils.writeStringToFile(new File("./version.json"), versionConfig.toJSONString());
            } catch (IOException ex) {
                showPopupDialog("Warning:  The version file could not be updated!  This may cause problems.");
                System.exit(0);
                return;
            }

            //Start Moddle
            try {
                ProcessBuilder moddle = new ProcessBuilder(new String[] { "javaw.exe", "-jar",
                        "\"" + new File("../Moddle.jar").getCanonicalPath() + "\"" });
                moddle.directory(new File(".."));
                moddle.start();
            } catch (IOException ex) {
                try {
                    ProcessBuilder moddle = new ProcessBuilder(
                            new String[] { "javaw.exe", "-jar", "\"../Moddle.jar\"" });
                    moddle.directory(new File(".."));
                    moddle.start();
                } catch (IOException ex2) {
                    showPopupDialog("Failed to start Moddle!");
                }
            }

            //Exit
            System.exit(0);

        }

    };
    worker.execute();
}

From source file:com.enjoyxstudy.selenium.autoexec.AutoExecServer.java

/**
 * @param command/*from   w w w  . j av a  2 s  .  c  o m*/
 * @throws IOException
 * @throws InterruptedException
 */
private void executeCommand(String command) throws IOException, InterruptedException {

    log.info("Command command[" + command + "]");

    ProcessBuilder processBuilder = new ProcessBuilder(command.split("\\s"));

    processBuilder.redirectErrorStream(true);

    Process process = processBuilder.start();

    StringWriter output = new StringWriter();
    BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    try {
        int ch;
        while ((ch = reader.read()) != -1) {
            output.write(ch);
        }
    } finally {
        reader.close();
    }

    int result = process.waitFor();

    log.info("Command returnCode[" + result + "] output[" + output.toString() + "]");

    if (result != 0) {
        throw new IOException("Execute command Error command[" + command + "] returnCode[" + result
                + "] output[" + output.toString() + "]");
    }
}

From source file:org.trustedanalytics.servicebroker.gearpump.service.externals.helpers.ExternalProcessExecutor.java

public ExternalProcessExecutorResult run(String[] command, String workingDir, Map<String, String> properties) {

    String lineToRun = Arrays.asList(command).stream().collect(Collectors.joining(" "));

    LOGGER.info("===================");
    LOGGER.info("Command to invoke: {}", lineToRun);

    ProcessBuilder processBuilder = new ProcessBuilder(command);
    updateEnvOfProcessBuilder(processBuilder.environment(), properties);

    if (workingDir != null) {
        processBuilder.directory(new File(workingDir));
    }//w  ww.  j a  va 2  s  .  co m
    processBuilder.redirectErrorStream(true);

    StringBuilder processOutput = new StringBuilder();
    Process process;
    BufferedReader stdout = null;

    try {
        process = processBuilder.start();
        stdout = new BufferedReader(new InputStreamReader(process.getInputStream()));

        String line;
        while ((line = stdout.readLine()) != null) {
            LOGGER.debug(":::::: " + line);
            processOutput.append(line);
            processOutput.append('\n');
        }

        try {
            process.waitFor();
        } catch (InterruptedException e) {
            LOGGER.error("Command '" + lineToRun + "' interrupted.", e);
        }
    } catch (IOException e) {
        LOGGER.error("Problem executing external process.", e);
        return new ExternalProcessExecutorResult(Integer.MIN_VALUE, "", e);
    } finally {
        closeReader(stdout);
    }

    ExternalProcessExecutorResult result = new ExternalProcessExecutorResult(process.exitValue(),
            processOutput.toString(), null);

    LOGGER.info("Exit value: {}", result.getExitCode());
    LOGGER.info("===================");
    return result;
}

From source file:com.urbancode.terraform.tasks.vmware.events.CloneVmCreatedEventListener.java

public void runCommand(String vmUser, String vmPassword, String vmRunCommand, List<String> args)
        throws IOException, InterruptedException {
    if (vmUser == null || vmPassword == null) {
        log.error("Either VM user or password were null. "
                + "They need to be specified in the template under the clone element.");
        throw new NullPointerException();
    }//from  w  w  w.  j a  va  2 s. c o  m
    VirtualHost host = environment.fetchVirtualHost();
    host.waitForVmtools(router);
    String vmx = host.getVmxPath(router);
    String url = host.getUrl();
    String virtualHostUser = host.getUser();
    String virtualHostPassword = host.getPassword();
    List<String> commandLine = new ArrayList<String>();
    commandLine.add("vmrun");
    commandLine.add("-T");
    commandLine.add("server");
    commandLine.add("-h");
    commandLine.add(url);
    commandLine.add("-u");
    commandLine.add(virtualHostUser);
    commandLine.add("-p");
    commandLine.add(virtualHostPassword);
    commandLine.add("-gu");
    commandLine.add(vmUser);
    commandLine.add("-gp");
    commandLine.add(vmPassword);
    commandLine.add(vmRunCommand);
    commandLine.add(vmx);
    commandLine.addAll(args);
    ProcessBuilder builder = new ProcessBuilder(commandLine);
    builder.redirectErrorStream(true);
    Process process = builder.start();

    InputStream procIn = process.getInputStream();
    IOUtil.getInstance().discardStream(procIn);

    int exitCode = process.waitFor();
    if (exitCode != 0) {
        throw new IOException("Command failed with code " + exitCode);
    }
    log.info("ran command " + vmRunCommand + " " + args.get(0));
}

From source file:com.fanniemae.ezpie.actions.HighlightScan.java

private void changeOracleExtractExtension(File castExtractionFile) {
    ProcessBuilder pb = new ProcessBuilder("java", "-jar", _dbDeliveryToolPath);
    Process process = null;//from   www. j av a2  s. c  o m
    Robot robot = null;
    try {
        process = pb.start();
        robot = new Robot();
    } catch (IOException | AWTException e) {
        throw new PieException("Could not start Oracle extract.", e);
    }

    sleep(15000);
    // navigating to input text
    for (int i = 0; i < 3; i++) {
        keyPressRelease(KeyEvent.VK_TAB, 200);
        sleep(200);
    }

    // select populated target folder path
    keyPressReleaseControlA(500);

    // entering target folder path
    Keyboard keyboard = new Keyboard(robot);
    keyboard.type(castExtractionFile.getParent() + "\\deliveryResults");

    // navigate to options
    keyPressReleaseShiftTab(200);
    keyPressRelease(KeyEvent.VK_RIGHT, 500);
    for (int i = 0; i < 2; i++) {
        keyPressRelease(KeyEvent.VK_TAB, 200);
        sleep(200);
    }

    // select populated extraction file path
    keyPressReleaseControlA(500);

    // entering target folder path that contains .castextraction file
    keyboard.type(castExtractionFile.getPath());
    sleep(500);
    keyPressRelease(KeyEvent.VK_TAB, 200);
    sleep(500);

    // navigate to menu bar to select Application/Run Application since tabbing to 'Run Application' button
    // and pressing enter does not execute run
    keyPressRelease(KeyEvent.VK_ALT, 500);
    sleep(500);
    for (int i = 0; i < 2; i++) {
        keyPressRelease(KeyEvent.VK_RIGHT, 200);
    }
    keyPressRelease(KeyEvent.VK_ENTER, 200);
    keyPressRelease(KeyEvent.VK_DOWN, 500);
    keyPressRelease(KeyEvent.VK_ENTER, 200);

    sleep(5000);
    process.destroy();
}

From source file:com.reelfx.model.PostProcessor.java

public void run() {
    try {/*from   w  ww. j  av  a2s.c om*/
        String ffmpeg = "ffmpeg" + (Applet.IS_WINDOWS ? ".exe" : "");

        // ----- quickly merge audio and video after recording -----------------------
        if (outputFile != null && encodingOpts.containsKey(MERGE_AUDIO_VIDEO) && !Applet.IS_MAC) {
            fireProcessUpdate(ENCODING_STARTED);
            // get information about the media file:
            //Map<String,Object> metadata = parseMediaFile(ScreenRecorder.OUTPUT_FILE.getAbsolutePath());
            //printMetadata(metadata);

            List<String> ffmpegArgs = new ArrayList<String>();
            ffmpegArgs.add(Applet.BIN_FOLDER.getAbsoluteFile() + File.separator + ffmpeg);
            ffmpegArgs.add("-y"); // overwrite any existing file
            // audio and video files
            if (AudioRecorder.OUTPUT_FILE.exists()) { // if opted for microphone
                // delay the audio if needed ( http://howto-pages.org/ffmpeg/#delay )
                if (encodingOpts.containsKey(OFFSET_AUDIO))
                    ffmpegArgs.addAll(parseParameters("-itsoffset 00:00:0" + encodingOpts.get(OFFSET_AUDIO))); // assume offset is less than 10 seconds
                ffmpegArgs.addAll(parseParameters("-i " + AudioRecorder.OUTPUT_FILE.getAbsolutePath()));
                // delay the video if needed ( http://howto-pages.org/ffmpeg/#delay )
                if (encodingOpts.containsKey(OFFSET_VIDEO))
                    ffmpegArgs.addAll(parseParameters("-itsoffset 00:00:0" + encodingOpts.get(OFFSET_VIDEO)));
            }
            ffmpegArgs.addAll(parseParameters("-i " + ScreenRecorder.OUTPUT_FILE));
            // export settings
            ffmpegArgs.addAll(getFfmpegCopyParams());
            // resize screen
            //ffmpegArgs.addAll(parseParameters("-s 1024x"+Math.round(1024.0/(double)Applet.SCREEN.width*(double)Applet.SCREEN.height)));

            ffmpegArgs.add(outputFile.getAbsolutePath());
            logger.info("Executing this command: " + prettyCommand(ffmpegArgs));
            ProcessBuilder pb = new ProcessBuilder(ffmpegArgs);
            ffmpegProcess = pb.start();

            errorGobbler = new StreamGobbler(ffmpegProcess.getErrorStream(), false, "ffmpeg E");
            inputGobbler = new StreamGobbler(ffmpegProcess.getInputStream(), false, "ffmpeg O");

            logger.info("Starting listener threads...");
            errorGobbler.start();
            inputGobbler.start();

            ffmpegProcess.waitFor();
            logger.info("Done encoding...");
            fireProcessUpdate(ENCODING_COMPLETE);
        } // end merging audio/video

        // ----- encode file to X264 -----------------------
        else if (outputFile != null && encodingOpts.containsKey(ENCODE_TO_X264) && !Applet.IS_MAC
                && !DEFAULT_OUTPUT_FILE.exists()) {
            fireProcessUpdate(ENCODING_STARTED);
            File inputFile = Applet.IS_LINUX ? LinuxController.MERGED_OUTPUT_FILE
                    : WindowsController.MERGED_OUTPUT_FILE;

            // get information about the media file:
            //metadata = parseMediaFile(inputFile.getAbsolutePath());
            //printMetadata(metadata);

            List<String> ffmpegArgs = new ArrayList<String>();
            ffmpegArgs.add(Applet.BIN_FOLDER.getAbsoluteFile() + File.separator + ffmpeg);
            ffmpegArgs.addAll(parseParameters("-y -i " + inputFile.getAbsolutePath()));
            ffmpegArgs.addAll(getFfmpegX264FastFirstPastBaselineParams());

            ffmpegArgs.add(DEFAULT_OUTPUT_FILE.getAbsolutePath());
            logger.info("Executing this command: " + prettyCommand(ffmpegArgs));
            ProcessBuilder pb = new ProcessBuilder(ffmpegArgs);
            ffmpegProcess = pb.start();

            errorGobbler = new StreamGobbler(ffmpegProcess.getErrorStream(), false, "ffmpeg E");
            inputGobbler = new StreamGobbler(ffmpegProcess.getInputStream(), false, "ffmpeg O");

            logger.info("Starting listener threads...");
            //errorGobbler.addActionListener("frame", this);
            errorGobbler.start();
            inputGobbler.start();

            ffmpegProcess.waitFor();
            logger.info("Done encoding...");
            fireProcessUpdate(ENCODING_COMPLETE);
        }
        // do we need to copy the X264 encoded file somewhere?
        if (outputFile != null && encodingOpts.containsKey(ENCODE_TO_X264) && !Applet.IS_MAC
                && !outputFile.getAbsolutePath().equals(DEFAULT_OUTPUT_FILE.getAbsolutePath())) {
            FileUtils.copyFile(DEFAULT_OUTPUT_FILE, outputFile);
            fireProcessUpdate(ENCODING_COMPLETE);
        }

        // ----- just copy the file if it's a Mac -----------------------
        if (outputFile != null && Applet.IS_MAC) {
            FileUtils.copyFile(ScreenRecorder.OUTPUT_FILE, outputFile);
            fireProcessUpdate(ENCODING_COMPLETE);
        }

        try {

            // ----- post data of screen capture to Insight -----------------------         
            if (postRecording) {
                // base code: http://stackoverflow.com/questions/1067655/how-to-upload-a-file-using-java-httpclient-library-working-with-php-strange-pro
                fireProcessUpdate(POST_STARTED);

                HttpClient client = new DefaultHttpClient();
                client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

                CountingMultipartEntity entity = new CountingMultipartEntity();
                ContentBody body = new FileBody(outputFile, "video/quicktime");
                entity.addPart("capture_file", body);

                HttpPost post = new HttpPost(postUrl);
                post.setEntity(entity);

                logger.info("Posting file to server... " + post.getRequestLine());

                HttpResponse response = client.execute(post);
                HttpEntity responseEntity = response.getEntity();

                logger.info("Response Status Code: " + response.getStatusLine());
                if (responseEntity != null) {
                    logger.info(EntityUtils.toString(responseEntity)); // to see the response body
                }

                // redirection to show page (meaning everything was correct); NOTE: Insight redirects you to the login form when you're not logged in (or no api_key)
                //if(response.getStatusLine().getStatusCode() == 302) {
                //Header header = response.getFirstHeader("Location");
                //logger.info("Redirecting to "+header.getValue());
                //Applet.redirectWebPage(header.getValue());
                //Applet.APPLET.showDocument(new URL(header.getValue()),"_self");

                if (response.getStatusLine().getStatusCode() == 200) {
                    fireProcessUpdate(POST_COMPLETE);
                } else {
                    fireProcessUpdate(POST_FAILED);
                }

                if (responseEntity != null) {
                    responseEntity.consumeContent();
                }

                client.getConnectionManager().shutdown();
            }
            // ----- post data of screen capture to Insight -----------------------           
            else if (postData) {
                fireProcessUpdate(POST_STARTED);

                HttpClient client = new DefaultHttpClient();
                client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

                HttpPost post = new HttpPost(postUrl);

                logger.info("Sending data to Insight... " + post.getRequestLine());

                HttpResponse response = client.execute(post);
                HttpEntity responseEntity = response.getEntity();

                logger.info("Response Status Code: " + response.getStatusLine());
                if (responseEntity != null) {
                    logger.info(EntityUtils.toString(responseEntity)); // to see the response body
                }

                if (response.getStatusLine().getStatusCode() == 200) {
                    fireProcessUpdate(POST_COMPLETE);
                } else {
                    fireProcessUpdate(POST_FAILED);
                }

                if (responseEntity != null) {
                    responseEntity.consumeContent();
                }

                client.getConnectionManager().shutdown();
            }

            // TODO monitor the progress of the transcoding?
            // TODO allow canceling of the transcoding?

        } catch (Exception e) {
            logger.error("Error occurred while posting the file.", e);
            fireProcessUpdate(POST_FAILED);
        } finally {
            outputFile = null;
            encodingOpts = new HashMap<Integer, String>(); // reset encoding options 
            metadata = null;
        }
    } catch (Exception e) {
        logger.error("Error occurred while encoding the file.", e);
        fireProcessUpdate(ENCODING_FAILED);
    }
}