Example usage for java.lang Thread interrupt

List of usage examples for java.lang Thread interrupt

Introduction

In this page you can find the example usage for java.lang Thread interrupt.

Prototype

public void interrupt() 

Source Link

Document

Interrupts this thread.

Usage

From source file:fm.smart.r1.CreateSoundActivity.java

public void onClick(View v) {
    String threegpfile_name = "test.3gp_amr";
    String amrfile_name = "test.amr";
    File dir = this.getDir("sounds", MODE_WORLD_READABLE);
    final File threegpfile = new File(dir, threegpfile_name);
    File amrfile = new File(dir, amrfile_name);
    String path = threegpfile.getAbsolutePath();
    Log.d("CreateSoundActivity", path);
    Log.d("CreateSoundActivity", (String) button.getText());
    if (button.getText().equals("Start")) {
        try {/*from  w w w  .ja v  a 2 s.c  om*/
            recorder = new MediaRecorder();

            // ContentValues values = new ContentValues(3);
            //
            // values.put(MediaStore.MediaColumns.TITLE, "test");
            // values.put(MediaStore.MediaColumns.DATE_ADDED,
            // System.currentTimeMillis());
            // values.put(MediaStore.MediaColumns.MIME_TYPE,
            // MediaRecorder.OutputFormat.THREE_GPP);
            //
            // ContentResolver contentResolver = new ContentResolver(this);
            //
            // Uri base = MediaStore.Audio.INTERNAL_CONTENT_URI;
            // Uri newUri = contentResolver.insert(base, values);

            recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            recorder.setOutputFormat(MediaRecorder.OutputFormat.RAW_AMR);
            recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
            recorder.setOutputFile(path);

            recorder.prepare();
            button.setText("Stop");
            recorder.start();
        } catch (Exception e) {
            Log.w(TAG, e);
        }
    } else {
        FileOutputStream os = null;
        FileInputStream is = null;
        try {
            recorder.stop();
            recorder.release(); // Now the object cannot be reused
            button.setEnabled(false);

            // ThreegpReader tr = new ThreegpReader(threegpfile);
            // os = new FileOutputStream(amrfile);
            // tr.extractAmr(os);
            is = new FileInputStream(threegpfile);
            playSound(is.getFD());

            final String media_entity = "http://test.com/test.mp3";
            final String author = "tansaku";
            final String author_url = "http://smart.fm/users/tansaku";

            if (LoginActivity.isNotLoggedIn(this)) {
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setClassName(this, LoginActivity.class.getName());
                intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                LoginActivity.return_to = CreateSoundActivity.class.getName();
                LoginActivity.params = new HashMap<String, String>();
                LoginActivity.params.put("item_id", item_id);
                LoginActivity.params.put("goal_id", goal_id);
                LoginActivity.params.put("id", id);
                LoginActivity.params.put("to_record", to_record);
                LoginActivity.params.put("sound_type", sound_type);
                startActivity(intent);
            } else {

                final ProgressDialog myOtherProgressDialog = new ProgressDialog(this);
                myOtherProgressDialog.setTitle("Please Wait ...");
                myOtherProgressDialog.setMessage("Creating Sound ...");
                myOtherProgressDialog.setIndeterminate(true);
                myOtherProgressDialog.setCancelable(true);

                final Thread create_sound = new Thread() {
                    public void run() {
                        // TODO make this interruptable .../*if
                        // (!this.isInterrupted())*/
                        CreateSoundActivity.create_sound_result = createSound(threegpfile, media_entity, author,
                                author_url, "1", item_id, id, to_record);
                        // this will also ensure item is in goal, but this
                        // should be sentence
                        // submission if we are handling sentence sound.
                        if (sound_type.equals(Integer.toString(R.id.cue_sound))) {
                            CreateSoundActivity.add_item_result = new AddItemResult(
                                    Main.lookup.addItemToGoal(Main.transport, Main.default_study_goal_id,
                                            item_id, CreateSoundActivity.create_sound_result.sound_id));
                        } else {
                            // ensure item is in goal
                            CreateSoundActivity.add_item_result = new AddItemResult(Main.lookup
                                    .addItemToGoal(Main.transport, Main.default_study_goal_id, item_id, null));
                            CreateSoundActivity.add_sentence_result = new AddSentenceResult(
                                    Main.lookup.addSentenceToGoal(Main.transport, Main.default_study_goal_id,
                                            item_id, id, CreateSoundActivity.create_sound_result.sound_id));

                        }
                        myOtherProgressDialog.dismiss();

                    }
                };
                myOtherProgressDialog.setButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        create_sound.interrupt();
                    }
                });
                OnCancelListener ocl = new OnCancelListener() {
                    public void onCancel(DialogInterface arg0) {
                        create_sound.interrupt();
                    }
                };
                myOtherProgressDialog.setOnCancelListener(ocl);
                myOtherProgressDialog.show();
                create_sound.start();
            }
        } catch (Exception e) {
            Log.w(TAG, e);
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

}

From source file:com.streamsets.pipeline.stage.origin.hdfs.cluster.ClusterHDFSSourceIT.java

@Test(timeout = 30000)
public void testProduceAvroData() throws Exception {
    ClusterHdfsConfigBean conf = new ClusterHdfsConfigBean();
    conf.hdfsUri = miniDFS.getURI().toString();
    conf.hdfsDirLocations = Arrays.asList(dir.toUri().getPath());
    conf.hdfsConfigs = new HashMap<>();
    conf.hdfsKerberos = false;//from  w  w  w .  ja v  a 2s  .  c o m
    conf.hdfsConfDir = hadoopConfDir;
    conf.recursive = false;
    conf.produceSingleRecordPerMessage = false;
    conf.dataFormat = DataFormat.AVRO;

    SourceRunner sourceRunner = new SourceRunner.Builder(ClusterHdfsDSource.class, createSource(conf))
            .addOutputLane("lane").setExecutionMode(ExecutionMode.CLUSTER_BATCH).setResourcesDir(resourcesDir)
            .build();

    sourceRunner.runInit();

    List<Map.Entry> list = new ArrayList<>();
    list.add(new Pair("path::" + "1" + "::1",
            createAvroData("a", 30, ImmutableList.of("a@company.com", "a2@company.com"))));
    list.add(new Pair("path::" + "1" + "::2",
            createAvroData("b", 40, ImmutableList.of("b@company.com", "b2@company.com"))));

    Thread th = createThreadForAddingBatch(sourceRunner, list);
    try {
        StageRunner.Output output = sourceRunner.runProduce(null, 5);
        String newOffset = output.getNewOffset();
        Assert.assertEquals("path::" + "1::2", newOffset);
        List<Record> records = output.getRecords().get("lane");
        Assert.assertEquals(2, records.size());

        Record record = records.get(0);
        Assert.assertTrue(record.has("/name"));
        Assert.assertEquals("a", record.get("/name").getValueAsString());
        Assert.assertTrue(record.has("/age"));
        Assert.assertEquals(30, record.get("/age").getValueAsInteger());
        Assert.assertTrue(record.has("/emails"));
        Assert.assertTrue(record.get("/emails").getValueAsList() instanceof List);
        List<Field> emails = record.get("/emails").getValueAsList();
        Assert.assertEquals(2, emails.size());
        Assert.assertEquals("a@company.com", emails.get(0).getValueAsString());
        Assert.assertEquals("a2@company.com", emails.get(1).getValueAsString());

        record = records.get(1);
        Assert.assertTrue(record.has("/name"));
        Assert.assertEquals("b", record.get("/name").getValueAsString());
        Assert.assertTrue(record.has("/age"));
        Assert.assertEquals(40, record.get("/age").getValueAsInteger());
        Assert.assertTrue(record.has("/emails"));
        Assert.assertTrue(record.get("/emails").getValueAsList() instanceof List);
        emails = record.get("/emails").getValueAsList();
        Assert.assertEquals(2, emails.size());
        Assert.assertEquals("b@company.com", emails.get(0).getValueAsString());
        Assert.assertEquals("b2@company.com", emails.get(1).getValueAsString());

    } finally {
        th.interrupt();
    }
}

From source file:org.silverpeas.core.process.io.file.TestFileHandler.java

@Test
public void testWaitForWithSuccessFileCreationInTime() throws Exception {
    assertThat(getFile(sessionComponentPath, "file").exists(), is(false));

    final Thread create = new Thread(new Runnable() {

        @Override/*w  ww .j a  va  2 s. c om*/
        public void run() {
            try {
                Thread.sleep(450);
                touch(getFile(sessionComponentPath, "file"));
            } catch (final Exception e) {
            }
        }
    });
    final RunnableTest<Boolean> waitForRun = new RunnableTest<Boolean>() {
        @Override
        public void run() {
            result = false;
            result = fileHandler.waitFor(BASE_PATH_TEST, getFile(realComponentPath, "file"), 1);
        }
    };
    final Thread waitFor = new Thread(waitForRun);

    try {
        create.start();
        waitFor.start();
        Thread.sleep(200);
        assertThat(getFile(sessionComponentPath, "file").exists(), is(false));
        assertThat(waitForRun.getResult(), is(false));
        Thread.sleep(400);
        assertThat(getFile(sessionComponentPath, "file").exists(), is(true));
        assertThat(waitForRun.getResult(), is(true));
        Thread.sleep(500);
    } finally {
        create.interrupt();
        waitFor.interrupt();
    }
    assertThat(waitForRun.getResult(), is(true));
    assertThat(getFile(sessionComponentPath, "file").exists(), is(true));
}

From source file:org.silverpeas.core.process.io.file.TestFileHandler.java

@Test
public void testWaitForForWithFailFileCreationInTime() throws Exception {
    assertThat(getFile(sessionComponentPath, "file").exists(), is(false));

    final Thread create = new Thread(new Runnable() {

        @Override/*from   w ww .  ja  va  2s .  c o  m*/
        public void run() {
            try {
                Thread.sleep(1200);
                touch(getFile(sessionComponentPath, "file"));
            } catch (final Exception e) {
            }
        }
    });
    final RunnableTest<Boolean> waitForRun = new RunnableTest<Boolean>() {
        @Override
        public void run() {
            result = false;
            result = fileHandler.waitFor(BASE_PATH_TEST, getFile(realComponentPath, "file"), 1);
        }
    };
    final Thread waitFor = new Thread(waitForRun);

    try {
        create.start();
        waitFor.start();
        Thread.sleep(200);
        assertThat(getFile(sessionComponentPath, "file").exists(), is(false));
        assertThat(waitForRun.getResult(), is(false));
        Thread.sleep(400);
        assertThat(getFile(sessionComponentPath, "file").exists(), is(false));
        assertThat(waitForRun.getResult(), is(false));
        Thread.sleep(500);
    } finally {
        create.interrupt();
        waitFor.interrupt();
    }
    assertThat(waitForRun.getResult(), is(false));
    assertThat(getFile(sessionComponentPath, "file").exists(), is(false));
}

From source file:com.gochinatv.datasync.util.Shell.java

/**
 * Run a command/*from  ww  w . j a  va2s .  c om*/
 */
private void runCommand() throws IOException {
    ProcessBuilder builder = new ProcessBuilder(getExecString());
    Timer timeOutTimer = null;
    ShellTimeoutTimerTask timeoutTimerTask;
    timedOut = new AtomicBoolean(false);
    completed = new AtomicBoolean(false);

    if (environment != null) {
        builder.environment().putAll(this.environment);
    }
    if (dir != null) {
        builder.directory(this.dir);
    }

    process = builder.start();
    if (timeOutInterval > 0) {
        timeOutTimer = new Timer();
        timeoutTimerTask = new ShellTimeoutTimerTask(this);
        //One time scheduling.
        timeOutTimer.schedule(timeoutTimerTask, timeOutInterval);
    }
    final BufferedReader errReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
    BufferedReader inReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    final StringBuffer errMsg = new StringBuffer();

    // read error and input streams as this would free up the buffers
    // free the error stream buffer
    Thread errThread = new Thread() {
        @Override
        public void run() {
            try {
                String line = errReader.readLine();
                while ((line != null) && !isInterrupted()) {
                    errMsg.append(line);
                    errMsg.append(System.getProperty("line.separator"));
                    line = errReader.readLine();
                }
            } catch (IOException ioe) {
                LOG.warn("Error reading the error stream", ioe);
            }
        }
    };
    try {
        errThread.start();
    } catch (IllegalStateException ignored) {
    }
    try {
        parseExecResult(inReader); // parse the output
        // clear the input stream buffer
        String line = inReader.readLine();
        while (line != null) {
            line = inReader.readLine();
        }
        // wait for the process to finish and check the exit code
        exitCode = process.waitFor();
        try {
            // make sure that the error thread exits
            errThread.join();
        } catch (InterruptedException ie) {
            LOG.warn("Interrupted while reading the error stream", ie);
        }
        completed.set(true);
        //the timeout thread handling
        //taken care in finally block
        if (exitCode != 0) {
            throw new ExitCodeException(exitCode, errMsg.toString());
        }
    } catch (InterruptedException ie) {
        throw new IOException(ie.toString());
    } finally {
        if ((timeOutTimer != null) && !timedOut.get()) {
            timeOutTimer.cancel();
        }
        // close the input stream
        try {
            inReader.close();
        } catch (IOException ioe) {
            LOG.warn("Error while closing the input stream", ioe);
        }
        if (!completed.get()) {
            errThread.interrupt();
        }
        try {
            errReader.close();
        } catch (IOException ioe) {
            LOG.warn("Error while closing the error stream", ioe);
        }
        process.destroy();
        lastTime = System.currentTimeMillis();
    }
}

From source file:org.apache.hadoop.mapred.util.Shell.java

/** Run a command */
private void runCommand() throws IOException {
    ProcessBuilder builder = new ProcessBuilder(getExecString());
    Timer timeOutTimer = null;//from www  .  j ava2  s  .  c o m
    ShellTimeoutTimerTask timeoutTimerTask = null;
    timedOut = new AtomicBoolean(false);
    completed = new AtomicBoolean(false);

    if (environment != null) {
        builder.environment().putAll(this.environment);
    }
    if (dir != null) {
        builder.directory(this.dir);
    }

    process = builder.start();
    if (timeOutInterval > 0) {
        timeOutTimer = new Timer();
        timeoutTimerTask = new ShellTimeoutTimerTask(this);
        //One time scheduling.
        timeOutTimer.schedule(timeoutTimerTask, timeOutInterval);
    }
    final BufferedReader errReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
    BufferedReader inReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    final StringBuffer errMsg = new StringBuffer();

    // read error and input streams as this would free up the buffers
    // free the error stream buffer
    Thread errThread = new Thread() {
        @Override
        public void run() {
            try {
                String line = errReader.readLine();
                while ((line != null) && !isInterrupted()) {
                    errMsg.append(line);
                    errMsg.append(System.getProperty("line.separator"));
                    line = errReader.readLine();
                }
            } catch (IOException ioe) {
                LOG.warn("Error reading the error stream", ioe);
            }
        }
    };
    try {
        errThread.start();
    } catch (IllegalStateException ise) {
    }
    try {
        parseExecResult(inReader); // parse the output
        // clear the input stream buffer
        String line = inReader.readLine();
        while (line != null) {
            line = inReader.readLine();
        }
        // wait for the process to finish and check the exit code
        exitCode = process.waitFor();
        try {
            // make sure that the error thread exits
            errThread.join();
        } catch (InterruptedException ie) {
            LOG.warn("Interrupted while reading the error stream", ie);
        }
        completed.set(true);
        //the timeout thread handling
        //taken care in finally block
        if (exitCode != 0) {
            throw new ExitCodeException(exitCode, errMsg.toString());
        }
    } catch (InterruptedException ie) {
        throw new IOException(ie.toString());
    } finally {
        if ((timeOutTimer != null) && !timedOut.get()) {
            timeOutTimer.cancel();
        }
        // close the input stream
        try {
            inReader.close();
        } catch (IOException ioe) {
            LOG.warn("Error while closing the input stream", ioe);
        }
        if (!completed.get()) {
            errThread.interrupt();
        }
        try {
            errReader.close();
        } catch (IOException ioe) {
            LOG.warn("Error while closing the error stream", ioe);
        }
        process.destroy();
        lastTime = System.currentTimeMillis();
    }
}

From source file:com.gargoylesoftware.htmlunit.WebClientTest.java

/**
 * @throws Exception if the test fails/*w ww  .  j  a  v  a 2  s. c  o m*/
 */
@Test
public void testJavaScriptTimeout() throws Exception {
    final WebClient client = getWebClient();
    final long timeout = 2000;
    final long oldTimeout = client.getJavaScriptTimeout();
    client.setJavaScriptTimeout(timeout);

    try {
        client.getOptions().setThrowExceptionOnScriptError(false);

        final String content = "<html><body><script>while(1) {}</script></body></html>";
        final MockWebConnection webConnection = new MockWebConnection();
        webConnection.setDefaultResponse(content);
        client.setWebConnection(webConnection);

        final Exception[] exceptions = { null };
        final Thread runner = new Thread() {
            @Override
            public void run() {
                try {
                    client.getPage(URL_FIRST);
                } catch (final Exception e) {
                    exceptions[0] = e;
                }
            }
        };

        runner.start();

        runner.join(timeout * 2);
        if (runner.isAlive()) {
            runner.interrupt();
            fail("Script was still running after timeout");
        }
        assertNull(exceptions[0]);
    } finally {
        client.setJavaScriptTimeout(oldTimeout);
    }
}

From source file:com.android.exchange.ExchangeService.java

private void stopAccountSyncs(long acctId, boolean includeAccountMailbox) {
    synchronized (sSyncLock) {
        List<Long> deletedBoxes = new ArrayList<Long>();
        for (Long mid : mServiceMap.keySet()) {
            Mailbox box = Mailbox.restoreMailboxWithId(this, mid);
            if (box != null) {
                if (box.mAccountKey == acctId) {
                    if (!includeAccountMailbox && box.mType == Mailbox.TYPE_EAS_ACCOUNT_MAILBOX) {
                        AbstractSyncService svc = mServiceMap.get(mid);
                        if (svc != null) {
                            svc.stop();//from   w w  w. ja v  a  2s . c  o  m
                        }
                        continue;
                    }
                    AbstractSyncService svc = mServiceMap.get(mid);
                    if (svc != null) {
                        svc.stop();
                        Thread t = svc.mThread;
                        if (t != null) {
                            t.interrupt();
                        }
                    }
                    deletedBoxes.add(mid);
                }
            }
        }
        for (Long mid : deletedBoxes) {
            releaseMailbox(mid);
        }
    }
}

From source file:org.apache.hadoop.hdfs.TestFileConcurrentReader.java

private void runTestUnfinishedBlockCRCError(final boolean transferToAllowed, final SyncType syncType,
        final int writeSize, Configuration conf) throws IOException {
    conf.setBoolean(DFSConfigKeys.DFS_DATANODE_TRANSFERTO_ALLOWED_KEY, transferToAllowed);
    init(conf);//from   w ww  .  j  av  a 2 s  .  com

    final Path file = new Path("/block-being-written-to");
    final int numWrites = 2000;
    final AtomicBoolean writerDone = new AtomicBoolean(false);
    final AtomicBoolean writerStarted = new AtomicBoolean(false);
    final AtomicBoolean error = new AtomicBoolean(false);
    final FSDataOutputStream initialOutputStream = fileSystem.create(file);
    final Thread writer = new Thread(new Runnable() {
        private FSDataOutputStream outputStream = initialOutputStream;

        @Override
        public void run() {
            try {
                for (int i = 0; !error.get() && i < numWrites; i++) {
                    try {
                        final byte[] writeBuf = DFSTestUtil.generateSequentialBytes(i * writeSize, writeSize);
                        outputStream.write(writeBuf);
                        if (syncType == SyncType.SYNC) {
                            outputStream.hflush();
                        } else { // append
                            outputStream.close();
                            outputStream = fileSystem.append(file);
                        }
                        writerStarted.set(true);
                    } catch (IOException e) {
                        error.set(true);
                        LOG.error("error writing to file", e);
                    }
                }

                writerDone.set(true);
                outputStream.close();
            } catch (Exception e) {
                LOG.error("error in writer", e);

                throw new RuntimeException(e);
            }
        }
    });
    Thread tailer = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                long startPos = 0;
                while (!writerDone.get() && !error.get()) {
                    if (writerStarted.get()) {
                        try {
                            startPos = tailFile(file, startPos);
                        } catch (IOException e) {
                            LOG.error(String.format("error tailing file %s", file), e);

                            throw new RuntimeException(e);
                        }
                    }
                }
            } catch (RuntimeException e) {
                if (e.getCause() instanceof ChecksumException) {
                    error.set(true);
                }

                writer.interrupt();
                LOG.error("error in tailer", e);
                throw e;
            }
        }
    });

    writer.start();
    tailer.start();

    try {
        writer.join();
        tailer.join();

        assertFalse("error occurred, see log above", error.get());
    } catch (InterruptedException e) {
        LOG.info("interrupted waiting for writer or tailer to complete");

        Thread.currentThread().interrupt();
    }
    initialOutputStream.close();
}

From source file:fx.DownloadFxApp.java

public void createScene(Stage stage) {
    try {/*from   w ww.  j a v a2  s.c o m*/
        stage.setTitle("Downloading JDK " + version + "...");

        instance.set(this);
        appStartedLatch.countDown();

        final SimpleBrowser browser = SimpleBrowser.newBuilder().useFirebug(false).useJQuery(true)
                .createWebView(!miniMode).build();

        final ProgressBar progressBar = new ProgressBar(0);
        final Label progressLabel = new Label("Retrieving a link...");

        VBox vBox = VBoxBuilder.create().children(progressLabel, progressBar, browser).fillWidth(true).build();

        Scene scene = new Scene(vBox);

        stage.setScene(scene);

        if (miniMode) {
            stage.setWidth(300);
        } else {
            stage.setWidth(1024);
            stage.setHeight(768);
        }

        stage.show();

        VBox.setVgrow(browser, Priority.ALWAYS);

        /**
         The sequence of calls
         location changed to: http://www.oracle.com/technetwork/java/javase/downloads/java-archive-downloads-javase7-521261.html?
         location changed to: http://download.oracle.com/otn/java/jdk/7u45-b18/jdk-7u45-linux-x64.tar.gz
         location changed to: https://edelivery.oracle.com/akam/otn/java/jdk/7u45-b18/jdk-7u45-linux-x64.tar.gz
         location changed to: https://login.oracle.com/pls/orasso/orasso.wwsso_app_admin.ls_login?Site2pstoreToken=v1.2~CA55CD32~750C6EFBC9B3CB198B2ADFE87BDD4DEB60E0218858C8BFE85DCCC65865D0E810E845839B422974847E1D489D3AF25FDC9574400197F9190C389876C1EC683A6006A06F7F05D41C94455B8354559F5699F5D0EF102F26FE905E77D40487455F7829501E3A783E1354EB0B8F05B828D0FC3BA22C62D3576883850E0B99849309B0C26F286E5650F63E9C6A7C376165C9A3EED86BF2FA0FAEE3D1F7F2957F5FBD5035AF0A3522E534141FE38DFDD55C4F7F517F9E81336C993BB76512C0D30A5B5C5FD82ED1C10E9D27284B6B1633E4B7B9FA5C2E38D9C5E3845C18C009E294E881FD8B654B67050958E57F0DC20885D6FA87A59FAA7564F94F
         location changed to: https://login.oracle.com/mysso/signon.jsp
         location changed to: https://login.oracle.com/oam/server/sso/auth_cred_submit
         location changed to: https://edelivery.oracle.com/osso_login_success?urlc=v1.2%7E30E69346FE17F27D4F83121B0B8EC362E0B315901364AAA7D6F0B7A05CD8AA31802F5A69D70C708F34C64B65D233922B57D3C31839E82CE78E5C8DA55D729DD339893285D21A8E8B1AE8557C9240D6E33C9965956E136F4CB093779F97AF67C3DB8FF19FF2A638296BD0AA81A7801904AC5607F0568B6CEAF7ED9FCE4B7BEA80071617E4B2779F60F0C76A89F7D195965D2F003F9EDD2A1ADFD264C1C4C7F921010B08D3846CEC9524237A9337B6B0BC433BB17993A670B6C913EB4CFDC217A753F9E2943DE0CBDC41D4705AC67C2B96A4892C65F5450B146939B0EBFDF098680BBBE1F13356460C95A23D8D198D1C6762E45E62F120E32C2549E6263071DA84F8321370D2410CCA93E9A071A02ED6EB40BF40EDFC6F65AC7BA73CDB06DF4265455419D9185A6256FFE41A7FF54042374D09F5C720F3104B2EAC924778482D4BE855A45B2636CE91C7D947FF1F764674CE0E42FFCCFE411AABFE07EA0E96838AFEA263D2D5A405BD
         location changed to: https://edelivery.oracle.com/akam/otn/java/jdk/7u45-b18/jdk-7u45-linux-x64.tar.gz
         location changed to: http://download.oracle.com/otn/java/jdk/7u45-b18/jdk-7u45-linux-x64.tar.gz?AuthParam=1390405890_f9186a44471784229268632878dd89e4
                
         */

        browser.getEngine().locationProperty().addListener(new ChangeListener<String>() {
            @Override
            public void changed(ObservableValue<? extends String> observableValue, String oldLoc,
                    final String uri) {
                logger.info("change: {}", uri);

                if (uri.contains("signon.jsp")) {
                    browser.getEngine().executeScript(
                            "" + "alert(document);\n" + "alert(document.getElementById('sso_username'));\n");

                    new Thread("signon.jsp waiter") {
                        @Override
                        public void run() {
                            setStatus("waiting for the login form...");

                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                throw Exceptions.runtime(e);
                            }

                            browser.waitFor("$('#sso_username').length > 0", 10000);

                            System.out.println("I see it all, I see it now!");

                            Platform.runLater(new Runnable() {
                                @Override
                                public void run() {
                                    browser.getEngine().executeScript(""
                                            + "alert(document.getElementById('sso_username'));\n"
                                            + "alert($('#sso_username').val('" + oracleUser + "'));\n"
                                            + "alert($('#ssopassword').val('" + oraclePassword + "'));\n"
                                            + downloadJDKJs() + "\n" + "clickIt($('.sf-btnarea a'))");
                                }
                            });
                        }
                    }.start();
                }

                if (uri.contains("download.oracle") && uri.contains("?")) {
                    // will be here after
                    // clicking accept license and link -> * not logged in * -> here -> download -> redirect to login
                    // download -> fill form -> * logged in * -> here -> download
                    Thread thread = new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                DefaultHttpClient httpClient = new DefaultHttpClient();

                                HttpGet httppost = new HttpGet(uri);

                                HttpResponse response = httpClient.execute(httppost);

                                int code = response.getStatusLine().getStatusCode();

                                if (code != 200) {
                                    System.out.println(IOUtils.toString(response.getEntity().getContent()));
                                    throw new RuntimeException("failed to download: " + uri);
                                }

                                final File file = new File(tempDestDir,
                                        StringUtils.substringBefore(FilenameUtils.getName(uri), "?"));
                                HttpEntity entity = response.getEntity();

                                final long length = entity.getContentLength();

                                final CountingOutputStream os = new CountingOutputStream(
                                        new FileOutputStream(file));

                                System.out.printf("Downloading %s to %s...%n", uri, file);

                                Thread progressThread = new Thread(new Runnable() {
                                    double lastProgress;

                                    @Override
                                    public void run() {
                                        while (!Thread.currentThread().isInterrupted()) {
                                            long copied = os.getCount();

                                            double progress = copied * 100D / length;

                                            if (progress != lastProgress) {
                                                final String s = String.format("%s: %s/%s %s%%", file.getName(),
                                                        FileUtils.humanReadableByteCount(copied, false, false),
                                                        FileUtils.humanReadableByteCount(length, false, true),
                                                        LangUtils.toConciseString(progress, 1));

                                                setStatus(s);

                                                System.out.print("\r" + s);
                                            }

                                            lastProgress = progress;
                                            progressBar.setProgress(copied * 1D / length);

                                            //                                                progressProp.set(progress);

                                            try {
                                                Thread.sleep(500);
                                            } catch (InterruptedException e) {
                                                break;
                                            }
                                        }
                                    }
                                }, "progressThread");

                                progressThread.start();

                                ByteStreams.copy(entity.getContent(), os);

                                progressThread.interrupt();

                                System.out.println("Download complete.");

                                downloadResult.set(new DownloadResult(file, "", true));
                                downloadLatch.countDown();
                            } catch (Exception e) {
                                LoggerFactory.getLogger("log").warn("", e);
                                downloadResult.set(new DownloadResult(null, e.getMessage(), false));
                                throw Exceptions.runtime(e);
                            }
                        }
                    }, "fx-downloader");

                    thread.start();
                }
            }

            public void setStatus(final String s) {
                Platform.runLater(new Runnable() {
                    @Override
                    public void run() {
                        progressLabel.setText(s);
                    }
                });
            }
        });

        // links from http://www.oracle.com/technetwork/java/archive-139210.html

        Map<Integer, String> archiveLinksMap = new HashMap<Integer, String>();

        archiveLinksMap.put(5,
                "http://www.oracle.com/technetwork/java/javasebusiness/downloads/java-archive-downloads-javase5-419410.html");
        archiveLinksMap.put(6,
                "http://www.oracle.com/technetwork/java/javase/downloads/java-archive-downloads-javase6-419409.html");
        archiveLinksMap.put(7,
                "http://www.oracle.com/technetwork/java/javase/downloads/java-archive-downloads-javase7-521261.html");

        Map<Integer, String> latestLinksMap = new HashMap<Integer, String>();

        latestLinksMap.put(7,
                "http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html");

        String archiveUrl = null;
        String latestUrl = null;

        char ch = version.charAt(0);

        switch (ch) {
        case '7':
        case '6':
        case '5':
            latestUrl = latestLinksMap.get(ch - '0');
            archiveUrl = archiveLinksMap.get(ch - '0');
            break;
        default:
            archiveUrl = null;
        }

        if (latestUrl != null) {
            final String finalArchiveUrl = archiveUrl;
            tryFind(browser, latestUrl, new WhenDone() {
                @Override
                public void whenDone(boolean found) {
                    tryArchiveLink(found, finalArchiveUrl, browser);
                }
            });
        } else {
            tryArchiveLink(false, archiveUrl, browser);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}