List of usage examples for java.util Collections synchronizedList
public static <T> List<T> synchronizedList(List<T> list)
From source file:halive.shootinoutside.common.core.game.map.GameMap.java
public void clearSpawnPositions() { for (int i = 0; i < spawnPositions.length; i++) { spawnPositions[i] = Collections.synchronizedList(new ArrayList<Vector2D>()); }/* w ww.j av a2 s .c o m*/ }
From source file:org.energy_home.jemma.javagal.layers.data.implementations.IDataLayerImplementation.DataFreescale.java
/** * Creates a new instance with a reference to the Gal Controller. * //from ww w .j a v a 2 s . co m * @param _gal * a reference to the Gal Controller. * @throws Exception * if an error occurs. */ public DataFreescale(GalController _gal) throws Exception { gal = _gal; listLocker = Collections.synchronizedList(new LinkedList<ParserLocker>()); _key = new SerialCommRxTx(gal.getPropertiesManager().getzgdDongleUri(), gal.getPropertiesManager().getzgdDongleSpeed(), this); INTERNAL_TIMEOUT = gal.getPropertiesManager().getCommandTimeoutMS(); Thread thr = new Thread() { @Override public void run() { ByteArrayObject _currentCommand; while (true) { try { _currentCommand = listOfCommandToSend.poll(); if (_currentCommand != null) { if (gal.getPropertiesManager().getDebugEnabled()) { logger.info(">>> Sending: " + _currentCommand.ToHexString()); System.out.println(">>> Sending: " + _currentCommand.ToHexString()); } _key.write(_currentCommand); } Thread.sleep(30); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }; thr.start(); }
From source file:com.scooter1556.sms.android.playback.QueueManager.java
private void updateQueue(final String id, final int index) { final List<MediaSessionCompat.QueueItem> newQueue = Collections .synchronizedList(new ArrayList<MediaSessionCompat.QueueItem>()); List<String> parsedMediaId = MediaUtils.parseMediaId(id); if (parsedMediaId.isEmpty()) { metadataListener.onMetadataRetrieveError(); return;//w w w. j av a 2s . c om } // Handle Playlist if (parsedMediaId.get(0).equals(MediaUtils.MEDIA_ID_PLAYLIST)) { if (parsedMediaId.size() < 2) { metadataListener.onMetadataRetrieveError(); return; } final UUID playlistId = UUID.fromString(parsedMediaId.get(1)); RESTService.getInstance().getPlaylistContents(ctx, playlistId, new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, cz.msebera.android.httpclient.Header[] headers, JSONObject response) { MediaElement element; Gson parser = new Gson(); element = parser.fromJson(response.toString(), MediaElement.class); if (element == null) { throw new IllegalArgumentException( "Failed to fetch contents of playlist with ID: " + playlistId); } MediaDescriptionCompat description = MediaUtils.getMediaDescription(element); if (description != null) { List<MediaSessionCompat.QueueItem> queue = new ArrayList<>(); newQueue.add(new MediaSessionCompat.QueueItem(description, element.getID().hashCode())); } if (!newQueue.isEmpty()) { if (index == -1 || currentQueue.size() == 0) { setQueue(newQueue); setCurrentQueue(newQueue); updateMetadata(); } else { queue.addAll(newQueue); if (currentQueue.size() > index) { currentQueue.addAll(index, newQueue); } else { currentQueue.addAll(newQueue); } metadataListener.onQueueUpdated(currentQueue); } } else { Log.e(TAG, "No media items to add to queue after processing playlist with ID: " + playlistId); } } @Override public void onSuccess(int statusCode, cz.msebera.android.httpclient.Header[] headers, JSONArray response) { Gson parser = new Gson(); for (int i = 0; i < response.length(); i++) { try { MediaElement element = parser.fromJson(response.getJSONObject(i).toString(), MediaElement.class); if (element == null) { throw new IllegalArgumentException( "Failed to fetch contents of playlist with ID: " + playlistId); } MediaDescriptionCompat description = MediaUtils.getMediaDescription(element); if (description != null) { newQueue.add( new MediaSessionCompat.QueueItem(description, element.getID().hashCode())); } } catch (JSONException e) { Log.e(TAG, "Failed to process JSON", e); } } if (!newQueue.isEmpty()) { if (index == -1 || currentQueue.size() == 0) { // Update master queue setQueue(newQueue); // Handle Shuffle if (shuffle) { Collections.shuffle(newQueue); } setCurrentQueue(newQueue); updateMetadata(); } else { queue.addAll(newQueue); // Handle Shuffle if (shuffle) { Collections.shuffle(newQueue); } if (currentQueue.size() > index) { currentQueue.addAll(index, newQueue); } else { currentQueue.addAll(newQueue); } metadataListener.onQueueUpdated(currentQueue); } } else { Log.e(TAG, "No media items to add to queue after processing playlist with ID: " + playlistId); } } @Override public void onFailure(int statusCode, cz.msebera.android.httpclient.Header[] headers, Throwable throwable, JSONObject response) { throw new IllegalArgumentException( "Failed to fetch contents for playlist with ID: " + playlistId); } }); } else if (parsedMediaId.get(0).equals(MediaUtils.MEDIA_ID_RANDOM_AUDIO)) { RESTService.getInstance().getRandomMediaElements(ctx, 200, MediaElement.MediaElementType.AUDIO, new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, cz.msebera.android.httpclient.Header[] headers, JSONObject response) { MediaElement element; Gson parser = new Gson(); element = parser.fromJson(response.toString(), MediaElement.class); if (element == null) { throw new IllegalArgumentException("Failed to fetch random media elements."); } MediaDescriptionCompat description = MediaUtils.getMediaDescription(element); if (description != null) { newQueue.add( new MediaSessionCompat.QueueItem(description, element.getID().hashCode())); } if (!newQueue.isEmpty()) { setQueue(newQueue); setCurrentQueue(newQueue); updateMetadata(); } else { Log.e(TAG, "No media items to add to queue."); } } @Override public void onSuccess(int statusCode, cz.msebera.android.httpclient.Header[] headers, JSONArray response) { Gson parser = new Gson(); for (int i = 0; i < response.length(); i++) { try { MediaElement element = parser.fromJson(response.getJSONObject(i).toString(), MediaElement.class); if (element == null) { throw new IllegalArgumentException( "Failed to fetch random media elements."); } MediaDescriptionCompat description = MediaUtils.getMediaDescription(element); if (description != null) { newQueue.add(new MediaSessionCompat.QueueItem(description, element.getID().hashCode())); } } catch (JSONException e) { Log.e(TAG, "Failed to process JSON", e); } } if (!newQueue.isEmpty()) { setQueue(newQueue); setCurrentQueue(newQueue); updateMetadata(); } else { Log.e(TAG, "No media items to add to queue"); } } @Override public void onFailure(int statusCode, cz.msebera.android.httpclient.Header[] headers, Throwable throwable, JSONObject response) { throw new IllegalArgumentException("Failed to fetch random media elements."); } }); } else if (index == -1) { if (parsedMediaId.size() < 2) { metadataListener.onMetadataRetrieveError(); return; } final UUID elementId = UUID.fromString(parsedMediaId.get(1)); RESTService.getInstance().getMediaElementContents(ctx, elementId, new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, cz.msebera.android.httpclient.Header[] headers, JSONObject response) { MediaElement element; Gson parser = new Gson(); element = parser.fromJson(response.toString(), MediaElement.class); if (element == null) { throw new IllegalArgumentException("Failed to fetch item with ID: " + id); } MediaDescriptionCompat description = MediaUtils.getMediaDescription(element); if (description != null) { newQueue.add(new MediaSessionCompat.QueueItem(description, element.getID().hashCode())); } if (!newQueue.isEmpty()) { setQueue(newQueue); setCurrentQueue(newQueue, id); updateMetadata(); } else { Log.e(TAG, "No media items to add to queue after processing media ID: " + id); } } @Override public void onSuccess(int statusCode, cz.msebera.android.httpclient.Header[] headers, JSONArray response) { Gson parser = new Gson(); for (int i = 0; i < response.length(); i++) { try { MediaElement element = parser.fromJson(response.getJSONObject(i).toString(), MediaElement.class); if (element == null) { throw new IllegalArgumentException("Failed to fetch item with ID: " + id); } MediaDescriptionCompat description = MediaUtils.getMediaDescription(element); if (description != null) { newQueue.add( new MediaSessionCompat.QueueItem(description, element.getID().hashCode())); } } catch (JSONException e) { Log.e(TAG, "Failed to process JSON", e); } } if (!newQueue.isEmpty()) { // Update master queue setQueue(newQueue); // Handle Shuffle if (shuffle) { Collections.shuffle(newQueue); if (QueueUtils.getIndexByMediaID(newQueue, id) != -1) { MediaSessionCompat.QueueItem currentItem = newQueue .get(QueueUtils.getIndexByMediaID(newQueue, id)); newQueue.remove(currentItem); newQueue.add(0, currentItem); } } setCurrentQueue(newQueue, id); updateMetadata(); } else { Log.e(TAG, "No media items to add to queue after processing media ID: " + id); } } @Override public void onFailure(int statusCode, cz.msebera.android.httpclient.Header[] headers, Throwable throwable, JSONObject response) { throw new IllegalArgumentException("Failed to fetch item with ID: " + id); } }); } else { if (parsedMediaId.size() < 2) { metadataListener.onMetadataRetrieveError(); return; } final UUID elementId = UUID.fromString(parsedMediaId.get(1)); switch (parsedMediaId.get(0)) { case MediaUtils.MEDIA_ID_DIRECTORY_AUDIO: case MediaUtils.MEDIA_ID_DIRECTORY_VIDEO: RESTService.getInstance().getMediaElementContents(ctx, elementId, new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, cz.msebera.android.httpclient.Header[] headers, JSONObject response) { MediaElement element; Gson parser = new Gson(); element = parser.fromJson(response.toString(), MediaElement.class); if (element == null) { throw new IllegalArgumentException("Failed to fetch item with ID: " + id); } MediaDescriptionCompat description = MediaUtils.getMediaDescription(element); if (description != null) { newQueue.add(new MediaSessionCompat.QueueItem(description, element.getID().hashCode())); } if (!newQueue.isEmpty()) { if (currentQueue.size() == 0) { setQueue(newQueue); setCurrentQueue(newQueue, id); updateMetadata(); } else { queue.addAll(newQueue); if (currentQueue.size() > index) { currentQueue.addAll(index, newQueue); } else { currentQueue.addAll(newQueue); } metadataListener.onQueueUpdated(currentQueue); } } else { Log.e(TAG, "No media items to add to queue after processing media ID: " + id); } } @Override public void onSuccess(int statusCode, cz.msebera.android.httpclient.Header[] headers, JSONArray response) { Gson parser = new Gson(); for (int i = 0; i < response.length(); i++) { try { MediaElement element = parser.fromJson(response.getJSONObject(i).toString(), MediaElement.class); if (element == null) { throw new IllegalArgumentException("Failed to fetch item with ID: " + id); } MediaDescriptionCompat description = MediaUtils.getMediaDescription(element); if (description != null) { newQueue.add(new MediaSessionCompat.QueueItem(description, element.getID().hashCode())); } } catch (JSONException e) { Log.e(TAG, "Failed to process JSON", e); } } if (!newQueue.isEmpty()) { if (currentQueue.size() == 0) { setQueue(newQueue); // Handle Shuffle if (shuffle) { Collections.shuffle(newQueue); if (QueueUtils.getIndexByMediaID(newQueue, id) != -1) { MediaSessionCompat.QueueItem currentItem = newQueue .get(QueueUtils.getIndexByMediaID(newQueue, id)); newQueue.remove(currentItem); newQueue.add(0, currentItem); } } setCurrentQueue(newQueue, id); updateMetadata(); } else { // Update master queue queue.addAll(newQueue); // Handle Shuffle if (shuffle) { Collections.shuffle(newQueue); if (QueueUtils.getIndexByMediaID(newQueue, id) != -1) { MediaSessionCompat.QueueItem currentItem = newQueue .get(QueueUtils.getIndexByMediaID(newQueue, id)); newQueue.remove(currentItem); newQueue.add(0, currentItem); } } if (currentQueue.size() > index) { currentQueue.addAll(index, newQueue); } else { currentQueue.addAll(newQueue); } metadataListener.onQueueUpdated(currentQueue); } } else { Log.e(TAG, "No media items to add to queue after processing media ID: " + id); } } @Override public void onFailure(int statusCode, cz.msebera.android.httpclient.Header[] headers, Throwable throwable, JSONObject response) { throw new IllegalArgumentException("Failed to fetch item with ID: " + id); } }); break; case MediaUtils.MEDIA_ID_AUDIO: case MediaUtils.MEDIA_ID_VIDEO: RESTService.getInstance().getMediaElement(ctx, elementId, new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, cz.msebera.android.httpclient.Header[] headers, JSONObject response) { MediaElement element; Gson parser = new Gson(); element = parser.fromJson(response.toString(), MediaElement.class); if (element == null) { throw new IllegalArgumentException("Failed to fetch item with ID: " + id); } MediaDescriptionCompat description = MediaUtils.getMediaDescription(element); if (description != null) { newQueue.add(new MediaSessionCompat.QueueItem(description, element.getID().hashCode())); } if (!newQueue.isEmpty()) { if (currentQueue.size() == 0) { setQueue(newQueue); setCurrentQueue(newQueue, id); updateMetadata(); } else { queue.addAll(newQueue); if (currentQueue.size() > index) { currentQueue.addAll(index, newQueue); } else { currentQueue.addAll(newQueue); } metadataListener.onQueueUpdated(currentQueue); } } else { Log.e(TAG, "No media items to add to queue after processing media ID: " + id); } } @Override public void onSuccess(int statusCode, cz.msebera.android.httpclient.Header[] headers, JSONArray response) { Gson parser = new Gson(); for (int i = 0; i < response.length(); i++) { try { MediaElement element = parser.fromJson(response.getJSONObject(i).toString(), MediaElement.class); if (element == null) { throw new IllegalArgumentException("Failed to fetch item with ID: " + id); } MediaDescriptionCompat description = MediaUtils.getMediaDescription(element); if (description != null) { newQueue.add(new MediaSessionCompat.QueueItem(description, element.getID().hashCode())); } } catch (JSONException e) { Log.e(TAG, "Failed to process JSON", e); } } if (!newQueue.isEmpty()) { // Update master queue queue.addAll(newQueue); if (currentQueue.size() > index) { currentQueue.addAll(index, newQueue); } else { currentQueue.addAll(newQueue); } metadataListener.onQueueUpdated(currentQueue); } else { Log.e(TAG, "No media items to add to queue after processing media ID: " + id); } } @Override public void onFailure(int statusCode, cz.msebera.android.httpclient.Header[] headers, Throwable throwable, JSONObject response) { throw new IllegalArgumentException("Failed to fetch item with ID: " + id); } }); break; } } }
From source file:org.eclipse.hudson.plugins.PluginCenter.java
public HttpResponse doInstallPlugin(@QueryParameter String pluginName) { if (!hudsonSecurityManager.hasPermission(Permission.HUDSON_ADMINISTER)) { return HttpResponses.forbidden(); }/* w w w . j a v a2s.c om*/ AvailablePluginInfo plugin = updateSiteManager.getAvailablePlugin(pluginName); if (plugin != null) { try { PluginInstallationJob installJob = null; // If the plugin is already being installed, don't schedule another. Make the search thread safe List<PluginInstallationJob> jobs = Collections.synchronizedList(installationsJobs); synchronized (jobs) { for (PluginInstallationJob job : jobs) { if (job.getName().equals(pluginName)) { installJob = job; } } } // No previous install of the plugn, create new if (installJob == null) { Future<PluginInstallationJob> newJob = install(plugin); installJob = newJob.get(); } if (!installJob.getStatus()) { installationsJobs.remove(installJob); return new ErrorHttpResponse( "Plugin " + pluginName + " could not be installed. " + installJob.getErrorMsg()); } } catch (Exception ex) { return new ErrorHttpResponse( "Plugin " + pluginName + " could not be installed. " + ex.getLocalizedMessage()); } installedPluginManager.loadInstalledPlugins(); return HttpResponses.ok(); } return new ErrorHttpResponse("Plugin " + pluginName + " is not a valid plugin"); }
From source file:com.gargoylesoftware.htmlunit.WebClient2Test.java
/** * Background tasks that have been registered before the serialization should * wake up and run normally after the deserialization. * Until now (2.7-SNAPSHOT 17.09.09) HtmlUnit has probably never supported it. * This is currently not requested and this test is just to document the current status. * @throws Exception if an error occurs//from w w w . j a v a 2 s . c o m */ @Test @NotYetImplemented public void serialization_withJSBackgroundTasks() throws Exception { final String html = "<html><head>\n" + "<script>\n" + " function foo() {\n" + " if (window.name == 'hello') {\n" + " alert('exiting');\n" + " clearInterval(intervalId);\n" + " }\n" + " }\n" + " var intervalId = setInterval(foo, 10);\n" + "</script></head>\n" + "<body></body></html>"; final HtmlPage page = loadPageWithAlerts(html); // verify that 1 background job exists assertEquals(1, page.getEnclosingWindow().getJobManager().getJobCount()); final byte[] bytes = SerializationUtils.serialize(page); page.getWebClient().close(); // deserialize page and verify that 1 background job exists final HtmlPage clonedPage = (HtmlPage) SerializationUtils.deserialize(bytes); assertEquals(1, clonedPage.getEnclosingWindow().getJobManager().getJobCount()); // configure a new CollectingAlertHandler (in fact it has surely already one and we could get and cast it) final List<String> collectedAlerts = Collections.synchronizedList(new ArrayList<String>()); final AlertHandler alertHandler = new CollectingAlertHandler(collectedAlerts); clonedPage.getWebClient().setAlertHandler(alertHandler); // make some change in the page on which background script reacts clonedPage.getEnclosingWindow().setName("hello"); clonedPage.getWebClient().waitForBackgroundJavaScriptStartingBefore(100); assertEquals(0, clonedPage.getEnclosingWindow().getJobManager().getJobCount()); final String[] expectedAlerts = { "exiting" }; assertEquals(expectedAlerts, collectedAlerts); }
From source file:com.gargoylesoftware.htmlunit.javascript.host.xml.XMLHttpRequest3Test.java
/** * Asynchronous callback should be called in "main" js thread and not parallel to other js execution. * See http://sourceforge.net/p/htmlunit/bugs/360/. * @throws Exception if the test fails/*from ww w. j a v a2 s .c om*/ */ @Test public void noParallelJSExecutionInPage() throws Exception { final String content = "<html><head><script>\n" + "var j = 0;\n" + "function test() {\n" + " req = " + XMLHttpRequest2Test.XHRInstantiation_ + ";\n" + " req.onreadystatechange = handler;\n" + " req.open('post', 'foo.xml', true);\n" + " req.send('');\n" + " alert('before long loop');\n" + " for (var i = 0; i < 5000; i++) {\n" + " j = j + 1;\n" + " }\n" + " alert('after long loop');\n" + "}\n" + "function handler() {\n" + " if (req.readyState == 4) {\n" + " alert('ready state handler, content loaded: j=' + j);\n" + " }\n" + "}\n" + "</script></head>\n" + "<body onload='test()'></body></html>"; final WebClient client = getWebClient(); final List<String> collectedAlerts = Collections.synchronizedList(new ArrayList<String>()); client.setAlertHandler(new CollectingAlertHandler(collectedAlerts)); final MockWebConnection conn = new MockWebConnection() { @Override public WebResponse getResponse(final WebRequest webRequest) throws IOException { collectedAlerts.add(webRequest.getUrl().toExternalForm()); return super.getResponse(webRequest); } }; conn.setResponse(URL_FIRST, content); final URL urlPage2 = new URL(URL_FIRST + "foo.xml"); conn.setResponse(urlPage2, "<foo/>\n", "text/xml"); client.setWebConnection(conn); client.getPage(URL_FIRST); assertEquals(0, client.waitForBackgroundJavaScriptStartingBefore(1000)); final String[] alerts = { URL_FIRST.toExternalForm(), "before long loop", "after long loop", urlPage2.toExternalForm(), "ready state handler, content loaded: j=5000" }; assertEquals(alerts, collectedAlerts); }
From source file:org.piwik.sdk.dispatcher.DispatcherTest.java
@Test public void testRandomDispatchIntervals() throws Exception { final List<Packet> dryRunData = Collections.synchronizedList(new ArrayList<Packet>()); mDispatcher.setDryRunTarget(dryRunData); final int threadCount = 10; final int queryCount = 100; final List<String> createdEvents = Collections.synchronizedList(new ArrayList<String>()); new Thread(new Runnable() { @Override// w ww.j a v a2 s . co m public void run() { try { while (getFlattenedQueries(new ArrayList<>(dryRunData)).size() != threadCount * queryCount) mDispatcher.setDispatchInterval(new Random().nextInt(20 - -1) + -1); } catch (Exception e) { e.printStackTrace(); } } }).start(); launchTestThreads(mApiUrl, mDispatcher, threadCount, queryCount, createdEvents); checkForMIAs(threadCount * queryCount, createdEvents, dryRunData); }
From source file:org.goko.viewer.jogl.service.JoglSceneManager.java
/** * @return the renderers/*w w w. j a va 2s .c om*/ */ private List<ICoreJoglRenderer> getRenderers() { if (renderers == null) { renderers = Collections.synchronizedList(new ArrayList<ICoreJoglRenderer>()); } return renderers; }
From source file:voldemort.store.routed.RoutedStore.java
public boolean delete(final ByteArray key, final Version version) throws VoldemortException { StoreUtils.assertValidKey(key);/* ww w .ja va2 s.c o m*/ final List<Node> nodes = availableNodes(routingStrategy.routeRequest(key.get())); // quickly fail if there aren't enough live nodes to meet the // requirements final int numNodes = nodes.size(); if (numNodes < this.storeDef.getRequiredWrites()) throw new InsufficientOperationalNodesException("Only " + numNodes + " nodes in preference list, but " + this.storeDef.getRequiredWrites() + " writes required."); // A count of the number of successful operations final AtomicInteger successes = new AtomicInteger(0); final AtomicBoolean deletedSomething = new AtomicBoolean(false); // A list of thrown exceptions, indicating the number of failures final List<Exception> failures = Collections.synchronizedList(new LinkedList<Exception>()); // A semaphore indicating the number of completed operations // Once inititialized all permits are acquired, after that // permits are released when an operation is completed. // semaphore.acquire(n) waits for n operations to complete final Semaphore semaphore = new Semaphore(0, false); // Add the operations to the pool for (final Node node : nodes) { this.executor.execute(new Runnable() { public void run() { long startNs = System.nanoTime(); try { boolean deleted = innerStores.get(node.getId()).delete(key, version); successes.incrementAndGet(); deletedSomething.compareAndSet(false, deleted); recordSuccess(node, startNs); } catch (UnreachableStoreException e) { failures.add(e); recordException(node, startNs, e); } catch (VoldemortApplicationException e) { throw e; } catch (Exception e) { failures.add(e); logger.warn("Error in DELETE on node " + node.getId() + "(" + node.getHost() + ")", e); } finally { // signal that the operation is complete semaphore.release(); } } }); } int attempts = Math.min(storeDef.getPreferredWrites(), numNodes); if (this.storeDef.getPreferredWrites() <= 0) { return true; } else { for (int i = 0; i < numNodes; i++) { try { boolean acquired = semaphore.tryAcquire(timeoutMs, TimeUnit.MILLISECONDS); if (!acquired) logger.warn("Delete operation timed out waiting for operation " + i + " to complete after waiting " + timeoutMs + " ms."); // okay, at least the required number of operations have // completed, were they successful? if (successes.get() >= attempts) return deletedSomething.get(); } catch (InterruptedException e) { throw new InsufficientOperationalNodesException("Delete operation interrupted!", e); } } } // If we get to here, that means we couldn't hit the preferred number // of writes, throw an exception if you can't even hit the required // number if (successes.get() < storeDef.getRequiredWrites()) throw new InsufficientOperationalNodesException( this.storeDef.getRequiredWrites() + " deletes required, but " + successes.get() + " succeeded.", failures); else return deletedSomething.get(); }
From source file:com.gargoylesoftware.htmlunit.WebClientWaitForBackgroundJobsTest.java
/** * When waitForBackgroundJavaScriptStartingBefore is called and a new job is scheduled after the one that * is first found as the last one within the delay (a job starts a new one or simply a setInterval), * a few retries should be done to see if new jobs exists. * @throws Exception if the test fails/*from w w w.j a v a 2 s. c o m*/ */ @Test public void waitWhenLastJobStartsNewOne() throws Exception { final String html = "<html>\n" + "<head>\n" + " <title>test</title>\n" + " <script>\n" + " function test() {\n" + " setTimeout(doWork1, 200);\n" + " }\n" + " function doWork1() {\n" + " alert('work1');\n" + " setTimeout(doWork2, 200);\n" + " }\n" + " function doWork2() {\n" + " alert('work2');\n" + " }\n" + " </script>\n" + "</head>\n" + "<body onload='test()'>\n" + "</body>\n" + "</html>"; final List<String> collectedAlerts = Collections.synchronizedList(new ArrayList<String>()); final HtmlPage page = loadPage(html, collectedAlerts); final JavaScriptJobManager jobManager = page.getEnclosingWindow().getJobManager(); assertNotNull(jobManager); assertEquals(1, jobManager.getJobCount()); startTimedTest(); assertEquals(0, page.getWebClient().waitForBackgroundJavaScriptStartingBefore(20_000)); assertMaxTestRunTime(1000); assertEquals(0, jobManager.getJobCount()); final String[] expectedAlerts = { "work1", "work2" }; assertEquals(expectedAlerts, collectedAlerts); }