Search in sources :

Example 26 with MILLISECONDS

use of java.util.concurrent.TimeUnit.MILLISECONDS in project ExoPlayer by google.

the class SessionCallbackBuilderTest method allowedCommand_afterCurrentMediaItemPrepared_notifiesSeekToAvailable.

@Test
public void allowedCommand_afterCurrentMediaItemPrepared_notifiesSeekToAvailable() throws Exception {
    List<MediaItem> testPlaylist = new ArrayList<>();
    testPlaylist.add(TestUtils.createMediaItem(R.raw.video_desks));
    UriMediaItem secondPlaylistItem = TestUtils.createMediaItem(R.raw.video_big_buck_bunny);
    testPlaylist.add(secondPlaylistItem);
    CountDownLatch readAllowedLatch = new CountDownLatch(1);
    playerTestRule.setDataSourceInstrumentation(dataSpec -> {
        if (dataSpec.uri.equals(secondPlaylistItem.getUri())) {
            try {
                assertThat(readAllowedLatch.await(PLAYER_STATE_CHANGE_WAIT_TIME_MS, MILLISECONDS)).isTrue();
            } catch (Exception e) {
                assertWithMessage("Unexpected exception %s", e).fail();
            }
        }
    });
    try (MediaSession session = createMediaSession(sessionPlayerConnector, new SessionCallbackBuilder(context, sessionPlayerConnector).build())) {
        assertPlayerResultSuccess(sessionPlayerConnector.setPlaylist(testPlaylist, null));
        assertPlayerResultSuccess(sessionPlayerConnector.prepare());
        CountDownLatch seekToAllowedForSecondMediaItem = new CountDownLatch(1);
        OnAllowedCommandsChangedListener allowedCommandsChangedListener = (controller, allowedCommands) -> {
            if (allowedCommands.hasCommand(SessionCommand.COMMAND_CODE_PLAYER_SEEK_TO) && controller.getCurrentMediaItemIndex() == 1) {
                seekToAllowedForSecondMediaItem.countDown();
            }
        };
        try (MediaController controller = createConnectedController(session, /* onConnectedListener= */
        null, allowedCommandsChangedListener)) {
            assertPlayerResultSuccess(sessionPlayerConnector.skipToNextPlaylistItem());
            readAllowedLatch.countDown();
            assertThat(seekToAllowedForSecondMediaItem.await(CONTROLLER_COMMAND_WAIT_TIME_MS, MILLISECONDS)).isTrue();
        }
    }
}
Also used : Context(android.content.Context) HeartRating(androidx.media2.session.HeartRating) Arrays(java.util.Arrays) Bundle(android.os.Bundle) Uri(android.net.Uri) MediaSession(androidx.media2.session.MediaSession) RunWith(org.junit.runner.RunWith) SessionResult(androidx.media2.session.SessionResult) AndroidJUnit4(androidx.test.ext.junit.runners.AndroidJUnit4) TestUtils.assertPlayerResultSuccess(com.google.android.exoplayer2.ext.media2.TestUtils.assertPlayerResultSuccess) ApplicationProvider(androidx.test.core.app.ApplicationProvider) ArrayList(java.util.ArrayList) Future(java.util.concurrent.Future) SessionCommand(androidx.media2.session.SessionCommand) ContextCompat(androidx.core.content.ContextCompat) LargeTest(androidx.test.filters.LargeTest) Before(org.junit.Before) SessionPlayer(androidx.media2.common.SessionPlayer) MediaMetadata(androidx.media2.common.MediaMetadata) Truth.assertWithMessage(com.google.common.truth.Truth.assertWithMessage) Executor(java.util.concurrent.Executor) TextUtils(android.text.TextUtils) UriMediaItem(androidx.media2.common.UriMediaItem) Test(org.junit.Test) MILLISECONDS(java.util.concurrent.TimeUnit.MILLISECONDS) Truth.assertThat(com.google.common.truth.Truth.assertThat) MediaItem(androidx.media2.common.MediaItem) Rating(androidx.media2.common.Rating) R(com.google.android.exoplayer2.ext.media2.test.R) CountDownLatch(java.util.concurrent.CountDownLatch) SessionCommandGroup(androidx.media2.session.SessionCommandGroup) List(java.util.List) Nullable(androidx.annotation.Nullable) Rule(org.junit.Rule) MediaController(androidx.media2.session.MediaController) RawResourceDataSource(com.google.android.exoplayer2.upstream.RawResourceDataSource) MediaController(androidx.media2.session.MediaController) MediaSession(androidx.media2.session.MediaSession) UriMediaItem(androidx.media2.common.UriMediaItem) MediaItem(androidx.media2.common.MediaItem) ArrayList(java.util.ArrayList) CountDownLatch(java.util.concurrent.CountDownLatch) UriMediaItem(androidx.media2.common.UriMediaItem) LargeTest(androidx.test.filters.LargeTest) Test(org.junit.Test)

Example 27 with MILLISECONDS

use of java.util.concurrent.TimeUnit.MILLISECONDS in project ignite by apache.

the class DistributedProcessCoordinatorLeftTest method testCoordinatorFailed.

/**
 * Tests that coordinator failing during sending single result not cause node failure and the process finishes.
 *
 * <ol>
 *  <li>Start new process of {@link DistributedProcess}.</li>
 *  <li>The coordinator fails.</li>
 *  <li>Nodes try to send a single message to the not-alive coordinator.</li>
 *  <li>{@link DistributedProcess} process a node left event and reinitialize a new coordinator.</li>
 *  <li>Process finishes.</li>
 * </ol>
 *
 * @throws Exception If failed.
 */
@Test
public void testCoordinatorFailed() throws Exception {
    startGrids(NODES_CNT);
    CountDownLatch startLatch = new CountDownLatch(NODES_CNT);
    CountDownLatch finishLatch = new CountDownLatch(NODES_CNT - 1);
    HashMap<String, DistributedProcess<Integer, Integer>> processes = new HashMap<>();
    int processRes = 1;
    for (Ignite grid : G.allGrids()) {
        DistributedProcess<Integer, Integer> dp = new DistributedProcess<>(((IgniteEx) grid).context(), TEST_PROCESS, req -> {
            IgniteInternalFuture<Integer> fut = runAsync(() -> {
                try {
                    nodeLeftLatch.await();
                } catch (InterruptedException ignored) {
                    fail("Unexpected interrupt.");
                }
                return req;
            });
            // It is guaranteed by the LIFO order of future listeners notifying.
            if (!grid.name().equals(getTestIgniteInstanceName(STOP_NODE_IDX)))
                fut.listen(f -> msgSendLatch.countDown());
            startLatch.countDown();
            return fut;
        }, (uuid, res, err) -> {
            if (res.values().size() == NODES_CNT - 1 && res.values().stream().allMatch(i -> i == processRes))
                finishLatch.countDown();
            else
                fail("Unexpected process result [res=" + res + ", err=" + err + ']');
        });
        processes.put(grid.name(), dp);
    }
    processes.get(grid(STOP_NODE_IDX).name()).start(UUID.randomUUID(), processRes);
    assertTrue(startLatch.await(TIMEOUT, MILLISECONDS));
    stopGrid(STOP_NODE_IDX);
    assertTrue(finishLatch.await(TIMEOUT, MILLISECONDS));
    assertFalse(failure.get());
}
Also used : IgniteInternalFuture(org.apache.ignite.internal.IgniteInternalFuture) G(org.apache.ignite.internal.util.typedef.G) DistributedProcess(org.apache.ignite.internal.util.distributed.DistributedProcess) GridCommonAbstractTest(org.apache.ignite.testframework.junits.common.GridCommonAbstractTest) EVT_NODE_LEFT(org.apache.ignite.events.EventType.EVT_NODE_LEFT) TEST_PROCESS(org.apache.ignite.internal.util.distributed.DistributedProcess.DistributedProcessType.TEST_PROCESS) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) FailureHandler(org.apache.ignite.failure.FailureHandler) IgniteEx(org.apache.ignite.internal.IgniteEx) Test(org.junit.Test) UUID(java.util.UUID) Ignite(org.apache.ignite.Ignite) MILLISECONDS(java.util.concurrent.TimeUnit.MILLISECONDS) GridTestUtils.runAsync(org.apache.ignite.testframework.GridTestUtils.runAsync) CountDownLatch(java.util.concurrent.CountDownLatch) IgniteConfiguration(org.apache.ignite.configuration.IgniteConfiguration) EVT_NODE_FAILED(org.apache.ignite.events.EventType.EVT_NODE_FAILED) FailureContext(org.apache.ignite.failure.FailureContext) Collections(java.util.Collections) DistributedProcess(org.apache.ignite.internal.util.distributed.DistributedProcess) HashMap(java.util.HashMap) Ignite(org.apache.ignite.Ignite) CountDownLatch(java.util.concurrent.CountDownLatch) GridCommonAbstractTest(org.apache.ignite.testframework.junits.common.GridCommonAbstractTest) Test(org.junit.Test)

Example 28 with MILLISECONDS

use of java.util.concurrent.TimeUnit.MILLISECONDS in project ignite by apache.

the class EventsRemoteSecurityContextCheckTest method checkRemoteListenWithNullFilter.

/**
 */
private void checkRemoteListenWithNullFilter(boolean async) throws Exception {
    for (IgniteEx initiator : initiators()) {
        IgniteCache<Object, Object> cache = initiator.createCache(new CacheConfiguration<>("test_cache_" + INDEX.incrementAndGet()).setCacheMode(REPLICATED));
        CountDownLatch srvNodesListenedLatch = new CountDownLatch(initiator.cluster().forServers().nodes().size());
        IgniteBiPredicate<UUID, ? extends Event> locLsnr = (uuid, e) -> {
            srvNodesListenedLatch.countDown();
            return true;
        };
        UUID lsnrId = async ? initiator.events().remoteListenAsync(locLsnr, null, EVT_CACHE_OBJECT_PUT).get() : initiator.events().remoteListen(locLsnr, null, EVT_CACHE_OBJECT_PUT);
        try {
            cache.put("key", "val");
            assertTrue(srvNodesListenedLatch.await(getTestTimeout(), MILLISECONDS));
        } finally {
            initiator.events().stopRemoteListen(lsnrId);
        }
    }
}
Also used : Arrays(java.util.Arrays) IgniteBiPredicate(org.apache.ignite.lang.IgniteBiPredicate) BiFunction(java.util.function.BiFunction) IgniteEx(org.apache.ignite.internal.IgniteEx) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) IgnitePredicate(org.apache.ignite.lang.IgnitePredicate) Map(java.util.Map) AbstractRemoteSecurityContextCheckTest(org.apache.ignite.internal.processors.security.AbstractRemoteSecurityContextCheckTest) IgniteEvents(org.apache.ignite.IgniteEvents) CacheEvent(org.apache.ignite.events.CacheEvent) EVT_CACHE_OBJECT_PUT(org.apache.ignite.events.EventType.EVT_CACHE_OBJECT_PUT) EventType(org.apache.ignite.events.EventType) Collection(java.util.Collection) Event(org.apache.ignite.events.Event) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Test(org.junit.Test) UUID(java.util.UUID) Ignite(org.apache.ignite.Ignite) MILLISECONDS(java.util.concurrent.TimeUnit.MILLISECONDS) IgniteCache(org.apache.ignite.IgniteCache) REPLICATED(org.apache.ignite.cache.CacheMode.REPLICATED) TimeUnit(java.util.concurrent.TimeUnit) CountDownLatch(java.util.concurrent.CountDownLatch) IgniteConfiguration(org.apache.ignite.configuration.IgniteConfiguration) Ignition(org.apache.ignite.Ignition) CacheConfiguration(org.apache.ignite.configuration.CacheConfiguration) Collections(java.util.Collections) IgniteEx(org.apache.ignite.internal.IgniteEx) CountDownLatch(java.util.concurrent.CountDownLatch) UUID(java.util.UUID) CacheConfiguration(org.apache.ignite.configuration.CacheConfiguration)

Example 29 with MILLISECONDS

use of java.util.concurrent.TimeUnit.MILLISECONDS in project ignite by apache.

the class CacheContinuousQueryFilterDeploymentFailedTest method testContinuousQueryFilterDeploymentFailed.

/**
 * Tests continuous query behavior in case of filter deployment obtaining failure.
 *
 * @throws Exception If failed.
 */
@Test
@SuppressWarnings({ "ThrowableNotThrown" })
public void testContinuousQueryFilterDeploymentFailed() throws Exception {
    startGrids(NODES_CNT - 1);
    IgniteEx cli = startClientGrid(NODES_CNT - 1);
    IgniteCache<Integer, Integer> cache = cli.createCache(DEFAULT_CACHE_NAME);
    ContinuousQuery<Integer, Integer> qry = new ContinuousQuery<>();
    Class<Factory<CacheEntryEventFilter<Integer, Integer>>> rmtFilterFactoryCls = (Class<Factory<CacheEntryEventFilter<Integer, Integer>>>) getExternalClassLoader().loadClass("org.apache.ignite.tests.p2p.CacheDeploymentEntryEventFilterFactory");
    qry.setRemoteFilterFactory(rmtFilterFactoryCls.newInstance());
    spi(grid(1)).blockMessages((node, msg) -> msg instanceof GridDeploymentRequest);
    assertThrowsWithCause(() -> cache.query(qry), CacheException.class);
    assertTrue(stopRoutineLatch.await(getTestTimeout(), MILLISECONDS));
    assertTrue(allGrids().stream().allMatch(g -> ((IgniteEx) g).context().systemView().view(CQ_SYS_VIEW).size() == 0));
}
Also used : Factory(javax.cache.configuration.Factory) TestRecordingCommunicationSpi.spi(org.apache.ignite.internal.TestRecordingCommunicationSpi.spi) GridCommonAbstractTest(org.apache.ignite.testframework.junits.common.GridCommonAbstractTest) GridTestUtils.assertThrowsWithCause(org.apache.ignite.testframework.GridTestUtils.assertThrowsWithCause) TestTcpDiscoverySpi(org.apache.ignite.spi.discovery.tcp.TestTcpDiscoverySpi) Ignition.allGrids(org.apache.ignite.Ignition.allGrids) IgniteEx(org.apache.ignite.internal.IgniteEx) Test(org.junit.Test) MILLISECONDS(java.util.concurrent.TimeUnit.MILLISECONDS) ContinuousQuery(org.apache.ignite.cache.query.ContinuousQuery) IgniteCache(org.apache.ignite.IgniteCache) CountDownLatch(java.util.concurrent.CountDownLatch) IgniteConfiguration(org.apache.ignite.configuration.IgniteConfiguration) CacheEntryEventFilter(javax.cache.event.CacheEntryEventFilter) DiscoveryCustomMessage(org.apache.ignite.internal.managers.discovery.DiscoveryCustomMessage) GridDeploymentRequest(org.apache.ignite.internal.managers.deployment.GridDeploymentRequest) CacheException(javax.cache.CacheException) CQ_SYS_VIEW(org.apache.ignite.internal.processors.continuous.GridContinuousProcessor.CQ_SYS_VIEW) TestRecordingCommunicationSpi(org.apache.ignite.internal.TestRecordingCommunicationSpi) StopRoutineDiscoveryMessage(org.apache.ignite.internal.processors.continuous.StopRoutineDiscoveryMessage) DiscoveryHook(org.apache.ignite.testframework.GridTestUtils.DiscoveryHook) ContinuousQuery(org.apache.ignite.cache.query.ContinuousQuery) IgniteEx(org.apache.ignite.internal.IgniteEx) Factory(javax.cache.configuration.Factory) GridDeploymentRequest(org.apache.ignite.internal.managers.deployment.GridDeploymentRequest) CacheEntryEventFilter(javax.cache.event.CacheEntryEventFilter) GridCommonAbstractTest(org.apache.ignite.testframework.junits.common.GridCommonAbstractTest) Test(org.junit.Test)

Example 30 with MILLISECONDS

use of java.util.concurrent.TimeUnit.MILLISECONDS in project airlift by airlift.

the class TestJwksService method testTimedReload.

@Test
public void testTimedReload() throws InterruptedException {
    AtomicReference<Supplier<Response>> response = new AtomicReference<>(() -> mockResponse(HttpStatus.OK, JSON_UTF_8, EMPTY_KEYS));
    JwksService service = new JwksService(URI.create("http://example.com"), new TestingHttpClient(request -> response.get().get()), new Duration(1, MILLISECONDS));
    assertEmptyKeys(service);
    try {
        // start service
        response.set(() -> mockResponse(HttpStatus.OK, JSON_UTF_8, EMPTY_KEYS));
        service.start();
        while (!service.getKeys().isEmpty()) {
            // noinspection BusyWait
            Thread.sleep(1000);
        }
        response.set(() -> mockResponse(HttpStatus.OK, JSON_UTF_8, TEST_JWKS_RESPONSE));
        while (service.getKeys().isEmpty()) {
            // noinspection BusyWait
            Thread.sleep(1000);
        }
        assertTestKeys(service);
    } finally {
        service.stop();
    }
}
Also used : HttpClient(io.airlift.http.client.HttpClient) TestingHttpClient(io.airlift.http.client.testing.TestingHttpClient) Assert.assertEquals(org.testng.Assert.assertEquals) Test(org.testng.annotations.Test) PublicKey(java.security.PublicKey) MILLISECONDS(java.util.concurrent.TimeUnit.MILLISECONDS) AtomicReference(java.util.concurrent.atomic.AtomicReference) Supplier(java.util.function.Supplier) JSON_UTF_8(com.google.common.net.MediaType.JSON_UTF_8) Duration(io.airlift.units.Duration) HttpStatus(io.airlift.http.client.HttpStatus) Assertions.assertThatThrownBy(org.assertj.core.api.Assertions.assertThatThrownBy) Map(java.util.Map) DAYS(java.util.concurrent.TimeUnit.DAYS) Response(io.airlift.http.client.Response) Assert.assertTrue(org.testng.Assert.assertTrue) TestingResponse.mockResponse(io.airlift.http.client.testing.TestingResponse.mockResponse) URI(java.net.URI) TestingHttpClient(io.airlift.http.client.testing.TestingHttpClient) Supplier(java.util.function.Supplier) AtomicReference(java.util.concurrent.atomic.AtomicReference) Duration(io.airlift.units.Duration) Test(org.testng.annotations.Test)

Aggregations

MILLISECONDS (java.util.concurrent.TimeUnit.MILLISECONDS)55 List (java.util.List)34 Test (org.junit.Test)27 CountDownLatch (java.util.concurrent.CountDownLatch)22 ArrayList (java.util.ArrayList)20 Arrays (java.util.Arrays)14 Optional (java.util.Optional)14 Future (java.util.concurrent.Future)14 SECONDS (java.util.concurrent.TimeUnit.SECONDS)14 Before (org.junit.Before)13 Duration (io.airlift.units.Duration)11 Map (java.util.Map)10 ExecutorService (java.util.concurrent.ExecutorService)8 Context (android.content.Context)7 Math.toIntExact (java.lang.Math.toIntExact)7 Rule (org.junit.Rule)7 Threads.daemonThreadsNamed (com.facebook.airlift.concurrent.Threads.daemonThreadsNamed)6 Cache (com.google.common.cache.Cache)6 CacheBuilder (com.google.common.cache.CacheBuilder)6 IOException (java.io.IOException)6