Search in sources :

Example 21 with MILLISECONDS

use of java.util.concurrent.TimeUnit.MILLISECONDS in project mongo-java-driver by mongodb.

the class KeyManagementService method decryptKey.

Mono<Void> decryptKey(final MongoKeyDecryptor keyDecryptor) {
    SocketSettings socketSettings = SocketSettings.builder().connectTimeout(timeoutMillis, MILLISECONDS).readTimeout(timeoutMillis, MILLISECONDS).build();
    StreamFactory streamFactory = tlsChannelStreamFactoryFactory.create(socketSettings, SslSettings.builder().enabled(true).context(kmsProviderSslContextMap.get(keyDecryptor.getKmsProvider())).build());
    ServerAddress serverAddress = new ServerAddress(keyDecryptor.getHostName());
    LOGGER.info("Connecting to KMS server at " + serverAddress);
    return Mono.<Void>create(sink -> {
        Stream stream = streamFactory.create(serverAddress);
        stream.openAsync(new AsyncCompletionHandler<Void>() {

            @Override
            public void completed(final Void ignored) {
                streamWrite(stream, keyDecryptor, sink);
            }

            @Override
            public void failed(final Throwable t) {
                stream.close();
                sink.error(t);
            }
        });
    }).onErrorMap(this::unWrapException);
}
Also used : ServerAddress(com.mongodb.ServerAddress) SslSettings(com.mongodb.connection.SslSettings) StreamFactory(com.mongodb.connection.StreamFactory) ByteBuf(org.bson.ByteBuf) SSLContext(javax.net.ssl.SSLContext) MongoKeyDecryptor(com.mongodb.crypt.capi.MongoKeyDecryptor) CompletionHandler(java.nio.channels.CompletionHandler) Mono(reactor.core.publisher.Mono) MonoSink(reactor.core.publisher.MonoSink) MongoSocketException(com.mongodb.MongoSocketException) MILLISECONDS(java.util.concurrent.TimeUnit.MILLISECONDS) AsynchronousChannelStream(com.mongodb.internal.connection.AsynchronousChannelStream) Collections.singletonList(java.util.Collections.singletonList) List(java.util.List) SocketSettings(com.mongodb.connection.SocketSettings) Loggers(com.mongodb.diagnostics.logging.Loggers) Closeable(java.io.Closeable) Map(java.util.Map) Stream(com.mongodb.connection.Stream) ByteBufNIO(org.bson.ByteBufNIO) AsyncCompletionHandler(com.mongodb.connection.AsyncCompletionHandler) Logger(com.mongodb.diagnostics.logging.Logger) TlsChannelStreamFactoryFactory(com.mongodb.connection.TlsChannelStreamFactoryFactory) AsyncCompletionHandler(com.mongodb.connection.AsyncCompletionHandler) StreamFactory(com.mongodb.connection.StreamFactory) ServerAddress(com.mongodb.ServerAddress) AsynchronousChannelStream(com.mongodb.internal.connection.AsynchronousChannelStream) Stream(com.mongodb.connection.Stream) SocketSettings(com.mongodb.connection.SocketSettings)

Example 22 with MILLISECONDS

use of java.util.concurrent.TimeUnit.MILLISECONDS in project mongo-java-driver by mongodb.

the class AbstractUnifiedTest method executeOperations.

private void executeOperations(final BsonArray operations, final boolean throwExceptions) {
    FailPoint failPoint = null;
    ServerAddress currentPrimary = null;
    try {
        for (BsonValue cur : operations) {
            final BsonDocument operation = cur.asDocument();
            String operationName = operation.getString("name").getValue();
            BsonValue expectedResult = operation.get("result");
            String receiver = operation.getString("object").getValue();
            ClientSession clientSession = receiver.startsWith("session") ? sessionsMap.get(receiver) : null;
            if (clientSession == null) {
                clientSession = operation.getDocument("arguments", new BsonDocument()).containsKey("session") ? sessionsMap.get(operation.getDocument("arguments").getString("session").getValue()) : null;
            }
            try {
                if (operationName.equals("startTransaction")) {
                    BsonDocument arguments = operation.getDocument("arguments", new BsonDocument());
                    if (arguments.containsKey("options")) {
                        TransactionOptions transactionOptions = createTransactionOptions(arguments.getDocument("options"));
                        nonNullClientSession(clientSession).startTransaction(transactionOptions);
                    } else {
                        nonNullClientSession(clientSession).startTransaction();
                    }
                } else if (operationName.equals("commitTransaction")) {
                    nonNullClientSession(clientSession).commitTransaction();
                } else if (operationName.equals("abortTransaction")) {
                    nonNullClientSession(clientSession).abortTransaction();
                } else if (operationName.equals("withTransaction")) {
                    final BsonDocument arguments = operation.getDocument("arguments", new BsonDocument());
                    TransactionOptions transactionOptions = null;
                    if (arguments.containsKey("options")) {
                        transactionOptions = createTransactionOptions(arguments.getDocument("options"));
                    }
                    if (transactionOptions == null) {
                        nonNullClientSession(clientSession).withTransaction(new TransactionBody<Object>() {

                            @Override
                            public Void execute() {
                                executeOperations(arguments.getDocument("callback").getArray("operations"), true);
                                return null;
                            }
                        });
                    } else {
                        nonNullClientSession(clientSession).withTransaction(new TransactionBody<Object>() {

                            @Override
                            public Void execute() {
                                executeOperations(arguments.getDocument("callback").getArray("operations"), true);
                                return null;
                            }
                        }, transactionOptions);
                    }
                } else if (operationName.equals("targetedFailPoint")) {
                    assertNull(failPoint);
                    failPoint = new TargetedFailPoint(operation);
                    failPoint.executeFailPoint();
                } else if (operationName.equals("configureFailPoint")) {
                    assertNull(failPoint);
                    failPoint = new FailPoint(operation);
                    failPoint.executeFailPoint();
                } else if (operationName.equals("startThread")) {
                    String target = operation.getDocument("arguments").getString("name").getValue();
                    executorServiceMap.put(target, Executors.newSingleThreadExecutor());
                } else if (operationName.equals("runOnThread")) {
                    String target = operation.getDocument("arguments").getString("name").getValue();
                    ExecutorService executorService = executorServiceMap.get(target);
                    Callable<Exception> callable = createCallable(operation.getDocument("arguments").getDocument("operation"));
                    futureMap.put(target, executorService.submit(callable));
                } else if (operationName.equals("wait")) {
                    Thread.sleep(operation.getDocument("arguments").getNumber("ms").longValue());
                } else if (operationName.equals("waitForThread")) {
                    String target = operation.getDocument("arguments").getString("name").getValue();
                    Exception exceptionFromFuture = futureMap.remove(target).get(5, SECONDS);
                    if (exceptionFromFuture != null) {
                        throw exceptionFromFuture;
                    }
                } else if (operationName.equals("waitForEvent")) {
                    String event = operation.getDocument("arguments").getString("event").getValue();
                    int count = operation.getDocument("arguments").getNumber("count").intValue();
                    long timeoutMillis = TimeUnit.SECONDS.toMillis(5);
                    switch(event) {
                        case "PoolClearedEvent":
                            connectionPoolListener.waitForEvent(ConnectionPoolClearedEvent.class, count, timeoutMillis, MILLISECONDS);
                            break;
                        case "PoolReadyEvent":
                            connectionPoolListener.waitForEvent(ConnectionPoolReadyEvent.class, count, timeoutMillis, MILLISECONDS);
                            break;
                        case "ServerMarkedUnknownEvent":
                            serverListener.waitForEvent(ServerType.UNKNOWN, count, timeoutMillis, MILLISECONDS);
                            break;
                        default:
                            throw new UnsupportedOperationException("Unsupported event type: " + event);
                    }
                } else if (operationName.equals("assertEventCount")) {
                    String event = operation.getDocument("arguments").getString("event").getValue();
                    int expectedCount = operation.getDocument("arguments").getNumber("count").intValue();
                    int actualCount = -1;
                    switch(event) {
                        case "PoolClearedEvent":
                            actualCount = connectionPoolListener.countEvents(ConnectionPoolClearedEvent.class);
                            break;
                        case "PoolReadyEvent":
                            actualCount = connectionPoolListener.countEvents(ConnectionPoolReadyEvent.class);
                            break;
                        case "ServerMarkedUnknownEvent":
                            actualCount = serverListener.countEvents(ServerType.UNKNOWN);
                            break;
                        default:
                            throw new UnsupportedOperationException("Unsupported event type: " + event);
                    }
                    assertEquals(event + " counts not equal", expectedCount, actualCount);
                } else if (operationName.equals("recordPrimary")) {
                    currentPrimary = getCurrentPrimary();
                } else if (operationName.equals("waitForPrimaryChange")) {
                    long startTimeMillis = System.currentTimeMillis();
                    int timeoutMillis = operation.getDocument("arguments").getNumber("timeoutMS").intValue();
                    ServerAddress newPrimary = getCurrentPrimary();
                    while (newPrimary == null || newPrimary.equals(currentPrimary)) {
                        if (startTimeMillis + timeoutMillis <= System.currentTimeMillis()) {
                            fail("Timed out waiting for primary change");
                        }
                        // noinspection BusyWait
                        Thread.sleep(50);
                        newPrimary = getCurrentPrimary();
                    }
                } else if (operationName.equals("runAdminCommand")) {
                    collectionHelper.runAdminCommand(operation.getDocument("arguments").getDocument("command"));
                } else if (operationName.equals("assertSessionPinned")) {
                    final BsonDocument arguments = operation.getDocument("arguments", new BsonDocument());
                    assertNotNull(sessionsMap.get(arguments.getString("session").getValue()).getPinnedServerAddress());
                } else if (operationName.equals("assertSessionUnpinned")) {
                    final BsonDocument arguments = operation.getDocument("arguments", new BsonDocument());
                    assertNull(sessionsMap.get(arguments.getString("session").getValue()).getPinnedServerAddress());
                } else if (operationName.equals("assertSessionTransactionState")) {
                    final BsonDocument arguments = operation.getDocument("arguments", new BsonDocument());
                    ClientSession session = sessionsMap.get(arguments.getString("session").getValue());
                    String state = arguments.getString("state").getValue();
                    if (state.equals("starting") || state.equals("in_progress")) {
                        assertTrue(session.hasActiveTransaction());
                    } else {
                        assertFalse(session.hasActiveTransaction());
                    }
                } else if (operationName.equals("endSession")) {
                    clientSession.close();
                } else if (operation.getBoolean("error", BsonBoolean.FALSE).getValue()) {
                    try {
                        helper.getOperationResults(operation, clientSession);
                        fail("Error expected but none thrown");
                    } catch (Exception e) {
                    // Expected failure ignore
                    }
                } else if (operationName.equals("assertDifferentLsidOnLastTwoCommands")) {
                    List<CommandEvent> events = lastTwoCommandEvents();
                    String eventsJson = commandListener.getCommandStartedEvents().stream().map(e -> ((CommandStartedEvent) e).getCommand().toJson()).collect(Collectors.joining(", "));
                    assertNotEquals(eventsJson, ((CommandStartedEvent) events.get(0)).getCommand().getDocument("lsid"), ((CommandStartedEvent) events.get(1)).getCommand().getDocument("lsid"));
                } else if (operationName.equals("assertSameLsidOnLastTwoCommands")) {
                    List<CommandEvent> events = lastTwoCommandEvents();
                    String eventsJson = commandListener.getCommandStartedEvents().stream().map(e -> ((CommandStartedEvent) e).getCommand().toJson()).collect(Collectors.joining(", "));
                    assertEquals(eventsJson, ((CommandStartedEvent) events.get(0)).getCommand().getDocument("lsid"), ((CommandStartedEvent) events.get(1)).getCommand().getDocument("lsid"));
                } else if (operationName.equals("assertSessionDirty")) {
                    assertNotNull(clientSession);
                    assertNotNull(clientSession.getServerSession());
                    assertTrue(clientSession.getServerSession().isMarkedDirty());
                } else if (operationName.equals("assertSessionNotDirty")) {
                    assertNotNull(clientSession);
                    assertNotNull(clientSession.getServerSession());
                    assertFalse(clientSession.getServerSession().isMarkedDirty());
                } else if (operationName.equals("assertCollectionExists")) {
                    assertCollectionExists(operation, true);
                } else if (operationName.equals("assertCollectionNotExists")) {
                    assertCollectionExists(operation, false);
                } else if (operationName.equals("assertIndexExists")) {
                    assertIndexExists(operation, true);
                } else if (operationName.equals("assertIndexNotExists")) {
                    assertIndexExists(operation, false);
                } else {
                    BsonDocument actualOutcome = helper.getOperationResults(operation, clientSession);
                    if (expectedResult != null) {
                        BsonValue actualResult = actualOutcome.get("result");
                        if (actualResult.isDocument()) {
                            if (((BsonDocument) actualResult).containsKey("recoveryToken")) {
                                ((BsonDocument) actualResult).remove("recoveryToken");
                            }
                        }
                        assertEquals("Expected operation result differs from actual", expectedResult, actualResult);
                    }
                }
                assertFalse(String.format("Expected error '%s' but none thrown for operation %s", getErrorContainsField(expectedResult), operationName), hasErrorContainsField(expectedResult));
                assertFalse(String.format("Expected error code '%s' but none thrown for operation %s", getErrorCodeNameField(expectedResult), operationName), hasErrorCodeNameField(expectedResult));
            } catch (RuntimeException e) {
                if (!assertExceptionState(e, expectedResult, operationName) || throwExceptions) {
                    throw e;
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    } finally {
        if (failPoint != null) {
            failPoint.disableFailPoint();
        }
    }
}
Also used : Document(org.bson.Document) ServerDescription(com.mongodb.connection.ServerDescription) ClusterFixture.getConnectionString(com.mongodb.ClusterFixture.getConnectionString) BsonValue(org.bson.BsonValue) Collections.singletonList(java.util.Collections.singletonList) MongoWriteConcernException(com.mongodb.MongoWriteConcernException) StreamFactoryFactory(com.mongodb.connection.StreamFactoryFactory) Future(java.util.concurrent.Future) ClusterFixture.isSharded(com.mongodb.ClusterFixture.isSharded) Fixture.getMongoClientSettingsBuilder(com.mongodb.client.Fixture.getMongoClientSettingsBuilder) SocketSettings(com.mongodb.connection.SocketSettings) BsonArray(org.bson.BsonArray) After(org.junit.After) Map(java.util.Map) ServerType(com.mongodb.connection.ServerType) ClusterFixture.getMultiMongosConnectionString(com.mongodb.ClusterFixture.getMultiMongosConnectionString) Assert.fail(org.junit.Assert.fail) ReadConcern(com.mongodb.ReadConcern) Parameterized(org.junit.runners.Parameterized) CommandMonitoringTestHelper.assertEventsEquality(com.mongodb.client.CommandMonitoringTestHelper.assertEventsEquality) CommandEvent(com.mongodb.event.CommandEvent) CollectionHelper(com.mongodb.client.test.CollectionHelper) MongoException(com.mongodb.MongoException) MILLISECONDS(java.util.concurrent.TimeUnit.MILLISECONDS) ConnectionPoolClearedEvent(com.mongodb.event.ConnectionPoolClearedEvent) Collectors(java.util.stream.Collectors) Executors(java.util.concurrent.Executors) List(java.util.List) Block(com.mongodb.Block) Assert.assertFalse(org.junit.Assert.assertFalse) TestConnectionPoolListener(com.mongodb.internal.connection.TestConnectionPoolListener) Assume.assumeTrue(org.junit.Assume.assumeTrue) MongoClientSettings(com.mongodb.MongoClientSettings) ReadPreference(com.mongodb.ReadPreference) CommandMonitoringTestHelper.getExpectedEvents(com.mongodb.client.CommandMonitoringTestHelper.getExpectedEvents) BsonBoolean(org.bson.BsonBoolean) Assume.assumeFalse(org.junit.Assume.assumeFalse) MongoCommandException(com.mongodb.MongoCommandException) ClusterSettings(com.mongodb.connection.ClusterSettings) RunWith(org.junit.runner.RunWith) HashMap(java.util.HashMap) Callable(java.util.concurrent.Callable) BsonString(org.bson.BsonString) ServerSettings(com.mongodb.connection.ServerSettings) BsonDocument(org.bson.BsonDocument) ArrayList(java.util.ArrayList) TransactionOptions(com.mongodb.TransactionOptions) TestCommandListener(com.mongodb.internal.connection.TestCommandListener) CreateCollectionOptions(com.mongodb.client.model.CreateCollectionOptions) DocumentCodec(org.bson.codecs.DocumentCodec) Fixture.getMongoClient(com.mongodb.client.Fixture.getMongoClient) Math.toIntExact(java.lang.Math.toIntExact) ExecutorService(java.util.concurrent.ExecutorService) Before(org.junit.Before) ServerAddress(com.mongodb.ServerAddress) ClusterFixture.setDirectConnection(com.mongodb.ClusterFixture.setDirectConnection) MongoNamespace(com.mongodb.MongoNamespace) Assert.assertNotNull(org.junit.Assert.assertNotNull) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) BsonDocumentCodec(org.bson.codecs.BsonDocumentCodec) ClusterFixture.isDataLakeTest(com.mongodb.ClusterFixture.isDataLakeTest) Assert.assertNotEquals(org.junit.Assert.assertNotEquals) TimeUnit(java.util.concurrent.TimeUnit) ConnectionPoolReadyEvent(com.mongodb.event.ConnectionPoolReadyEvent) ConnectionString(com.mongodb.ConnectionString) Assert.assertNull(org.junit.Assert.assertNull) ClientSessionOptions(com.mongodb.ClientSessionOptions) ReadConcernLevel(com.mongodb.ReadConcernLevel) ClusterFixture.serverVersionAtLeast(com.mongodb.ClusterFixture.serverVersionAtLeast) Nullable(com.mongodb.lang.Nullable) BsonInt32(org.bson.BsonInt32) WriteConcern(com.mongodb.WriteConcern) CommandStartedEvent(com.mongodb.event.CommandStartedEvent) SECONDS(java.util.concurrent.TimeUnit.SECONDS) Assert.assertEquals(org.junit.Assert.assertEquals) ServerAddress(com.mongodb.ServerAddress) ClusterFixture.getConnectionString(com.mongodb.ClusterFixture.getConnectionString) ClusterFixture.getMultiMongosConnectionString(com.mongodb.ClusterFixture.getMultiMongosConnectionString) BsonString(org.bson.BsonString) ConnectionString(com.mongodb.ConnectionString) Callable(java.util.concurrent.Callable) MongoWriteConcernException(com.mongodb.MongoWriteConcernException) MongoException(com.mongodb.MongoException) MongoCommandException(com.mongodb.MongoCommandException) BsonDocument(org.bson.BsonDocument) TransactionOptions(com.mongodb.TransactionOptions) CommandStartedEvent(com.mongodb.event.CommandStartedEvent) ExecutorService(java.util.concurrent.ExecutorService) CommandEvent(com.mongodb.event.CommandEvent) Collections.singletonList(java.util.Collections.singletonList) List(java.util.List) ArrayList(java.util.ArrayList) BsonValue(org.bson.BsonValue)

Example 23 with MILLISECONDS

use of java.util.concurrent.TimeUnit.MILLISECONDS in project mongo-java-driver by mongodb.

the class AbstractUnifiedTest method setUp.

@Before
public void setUp() {
    assumeFalse(skipTest);
    assumeTrue("Skipping test: " + definition.getString("skipReason", new BsonString("")).getValue(), !definition.containsKey("skipReason"));
    assumeFalse("Skipping test of count", filename.equals("count.json"));
    collectionHelper = new CollectionHelper<Document>(new DocumentCodec(), new MongoNamespace(databaseName, collectionName));
    collectionHelper.killAllSessions();
    if (!isDataLakeTest()) {
        collectionHelper.create(collectionName, new CreateCollectionOptions(), WriteConcern.MAJORITY);
    }
    if (!data.isEmpty()) {
        List<BsonDocument> documents = new ArrayList<BsonDocument>();
        for (BsonValue document : data) {
            documents.add(document.asDocument());
        }
        collectionHelper.insertDocuments(documents, WriteConcern.MAJORITY);
    }
    if (definition.containsKey("failPoint")) {
        collectionHelper.runAdminCommand(definition.getDocument("failPoint"));
    }
    final BsonDocument clientOptions = definition.getDocument("clientOptions", new BsonDocument());
    connectionString = getConnectionString();
    useMultipleMongoses = definition.getBoolean("useMultipleMongoses", BsonBoolean.FALSE).getValue();
    if (useMultipleMongoses) {
        assumeTrue(isSharded());
        connectionString = getMultiMongosConnectionString();
        assumeTrue("The system property org.mongodb.test.transaction.uri is not set.", connectionString != null);
    }
    MongoClientSettings.Builder builder = getMongoClientSettingsBuilder().applyConnectionString(connectionString).addCommandListener(commandListener).applyToClusterSettings(clusterSettingsBuilder -> {
        if (clientOptions.containsKey("serverSelectionTimeoutMS")) {
            clusterSettingsBuilder.serverSelectionTimeout(clientOptions.getNumber("serverSelectionTimeoutMS").longValue(), MILLISECONDS);
        }
        if (clientOptions.containsKey("directConnection")) {
            setDirectConnection(clusterSettingsBuilder);
        }
    }).applyToSocketSettings(new Block<SocketSettings.Builder>() {

        @Override
        public void apply(final SocketSettings.Builder builder) {
            builder.readTimeout(clientOptions.getInt32("socketTimeoutMS", new BsonInt32(toIntExact(SECONDS.toMillis(5)))).getValue(), MILLISECONDS);
            if (clientOptions.containsKey("connectTimeoutMS")) {
                builder.connectTimeout(clientOptions.getNumber("connectTimeoutMS").intValue(), MILLISECONDS);
            }
        }
    }).writeConcern(getWriteConcern(clientOptions)).readConcern(getReadConcern(clientOptions)).readPreference(getReadPreference(clientOptions)).retryWrites(clientOptions.getBoolean("retryWrites", BsonBoolean.FALSE).getValue()).retryReads(false).applyToConnectionPoolSettings(poolSettingsBuilder -> {
        poolSettingsBuilder.addConnectionPoolListener(connectionPoolListener);
        if (clientOptions.containsKey("minPoolSize")) {
            poolSettingsBuilder.minSize(clientOptions.getInt32("minPoolSize").getValue());
        }
    }).applyToServerSettings(new Block<ServerSettings.Builder>() {

        @Override
        public void apply(final ServerSettings.Builder builder) {
            builder.heartbeatFrequency(50, MILLISECONDS);
            builder.minHeartbeatFrequency(MIN_HEARTBEAT_FREQUENCY_MS, MILLISECONDS);
            builder.addServerListener(serverListener);
        }
    });
    if (clientOptions.containsKey("heartbeatFrequencyMS")) {
        builder.applyToServerSettings(new Block<ServerSettings.Builder>() {

            @Override
            public void apply(final ServerSettings.Builder builder) {
                builder.heartbeatFrequency(clientOptions.getInt32("heartbeatFrequencyMS").intValue(), MILLISECONDS);
            }
        });
    }
    if (clientOptions.containsKey("appname")) {
        builder.applicationName(clientOptions.getString("appname").getValue());
    }
    if (clientOptions.containsKey("w")) {
        if (clientOptions.isString("w")) {
            builder.writeConcern(new WriteConcern(clientOptions.getString("w").getValue()));
        } else if (clientOptions.isNumber("w")) {
            builder.writeConcern(new WriteConcern(clientOptions.getNumber("w").intValue()));
        }
    }
    StreamFactoryFactory streamFactoryFactory = getStreamFactoryFactory();
    if (streamFactoryFactory != null) {
        builder.streamFactoryFactory(streamFactoryFactory);
    }
    mongoClient = createMongoClient(builder.build());
    database = mongoClient.getDatabase(databaseName);
    if (useMultipleMongoses) {
        // non-transactional distinct operation to avoid StaleDbVersion error
        runDistinctOnEachNode();
    }
    helper = new JsonPoweredCrudTestHelper(description, database, database.getCollection(collectionName, BsonDocument.class), null, mongoClient);
    sessionsMap = new HashMap<>();
    lsidMap = new HashMap<>();
    if (createSessions && serverVersionAtLeast(3, 6)) {
        ClientSession sessionZero = createSession("session0");
        ClientSession sessionOne = createSession("session1");
        sessionsMap.put("session0", sessionZero);
        sessionsMap.put("session1", sessionOne);
        lsidMap.put("session0", sessionZero.getServerSession().getIdentifier());
        lsidMap.put("session1", sessionOne.getServerSession().getIdentifier());
    }
}
Also used : Document(org.bson.Document) ServerDescription(com.mongodb.connection.ServerDescription) ClusterFixture.getConnectionString(com.mongodb.ClusterFixture.getConnectionString) BsonValue(org.bson.BsonValue) Collections.singletonList(java.util.Collections.singletonList) MongoWriteConcernException(com.mongodb.MongoWriteConcernException) StreamFactoryFactory(com.mongodb.connection.StreamFactoryFactory) Future(java.util.concurrent.Future) ClusterFixture.isSharded(com.mongodb.ClusterFixture.isSharded) Fixture.getMongoClientSettingsBuilder(com.mongodb.client.Fixture.getMongoClientSettingsBuilder) SocketSettings(com.mongodb.connection.SocketSettings) BsonArray(org.bson.BsonArray) After(org.junit.After) Map(java.util.Map) ServerType(com.mongodb.connection.ServerType) ClusterFixture.getMultiMongosConnectionString(com.mongodb.ClusterFixture.getMultiMongosConnectionString) Assert.fail(org.junit.Assert.fail) ReadConcern(com.mongodb.ReadConcern) Parameterized(org.junit.runners.Parameterized) CommandMonitoringTestHelper.assertEventsEquality(com.mongodb.client.CommandMonitoringTestHelper.assertEventsEquality) CommandEvent(com.mongodb.event.CommandEvent) CollectionHelper(com.mongodb.client.test.CollectionHelper) MongoException(com.mongodb.MongoException) MILLISECONDS(java.util.concurrent.TimeUnit.MILLISECONDS) ConnectionPoolClearedEvent(com.mongodb.event.ConnectionPoolClearedEvent) Collectors(java.util.stream.Collectors) Executors(java.util.concurrent.Executors) List(java.util.List) Block(com.mongodb.Block) Assert.assertFalse(org.junit.Assert.assertFalse) TestConnectionPoolListener(com.mongodb.internal.connection.TestConnectionPoolListener) Assume.assumeTrue(org.junit.Assume.assumeTrue) MongoClientSettings(com.mongodb.MongoClientSettings) ReadPreference(com.mongodb.ReadPreference) CommandMonitoringTestHelper.getExpectedEvents(com.mongodb.client.CommandMonitoringTestHelper.getExpectedEvents) BsonBoolean(org.bson.BsonBoolean) Assume.assumeFalse(org.junit.Assume.assumeFalse) MongoCommandException(com.mongodb.MongoCommandException) ClusterSettings(com.mongodb.connection.ClusterSettings) RunWith(org.junit.runner.RunWith) HashMap(java.util.HashMap) Callable(java.util.concurrent.Callable) BsonString(org.bson.BsonString) ServerSettings(com.mongodb.connection.ServerSettings) BsonDocument(org.bson.BsonDocument) ArrayList(java.util.ArrayList) TransactionOptions(com.mongodb.TransactionOptions) TestCommandListener(com.mongodb.internal.connection.TestCommandListener) CreateCollectionOptions(com.mongodb.client.model.CreateCollectionOptions) DocumentCodec(org.bson.codecs.DocumentCodec) Fixture.getMongoClient(com.mongodb.client.Fixture.getMongoClient) Math.toIntExact(java.lang.Math.toIntExact) ExecutorService(java.util.concurrent.ExecutorService) Before(org.junit.Before) ServerAddress(com.mongodb.ServerAddress) ClusterFixture.setDirectConnection(com.mongodb.ClusterFixture.setDirectConnection) MongoNamespace(com.mongodb.MongoNamespace) Assert.assertNotNull(org.junit.Assert.assertNotNull) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) BsonDocumentCodec(org.bson.codecs.BsonDocumentCodec) ClusterFixture.isDataLakeTest(com.mongodb.ClusterFixture.isDataLakeTest) Assert.assertNotEquals(org.junit.Assert.assertNotEquals) TimeUnit(java.util.concurrent.TimeUnit) ConnectionPoolReadyEvent(com.mongodb.event.ConnectionPoolReadyEvent) ConnectionString(com.mongodb.ConnectionString) Assert.assertNull(org.junit.Assert.assertNull) ClientSessionOptions(com.mongodb.ClientSessionOptions) ReadConcernLevel(com.mongodb.ReadConcernLevel) ClusterFixture.serverVersionAtLeast(com.mongodb.ClusterFixture.serverVersionAtLeast) Nullable(com.mongodb.lang.Nullable) BsonInt32(org.bson.BsonInt32) WriteConcern(com.mongodb.WriteConcern) CommandStartedEvent(com.mongodb.event.CommandStartedEvent) SECONDS(java.util.concurrent.TimeUnit.SECONDS) Assert.assertEquals(org.junit.Assert.assertEquals) Fixture.getMongoClientSettingsBuilder(com.mongodb.client.Fixture.getMongoClientSettingsBuilder) DocumentCodec(org.bson.codecs.DocumentCodec) BsonDocumentCodec(org.bson.codecs.BsonDocumentCodec) ArrayList(java.util.ArrayList) Document(org.bson.Document) BsonDocument(org.bson.BsonDocument) SocketSettings(com.mongodb.connection.SocketSettings) BsonInt32(org.bson.BsonInt32) ServerSettings(com.mongodb.connection.ServerSettings) MongoClientSettings(com.mongodb.MongoClientSettings) MongoNamespace(com.mongodb.MongoNamespace) BsonDocument(org.bson.BsonDocument) BsonString(org.bson.BsonString) WriteConcern(com.mongodb.WriteConcern) CreateCollectionOptions(com.mongodb.client.model.CreateCollectionOptions) Block(com.mongodb.Block) StreamFactoryFactory(com.mongodb.connection.StreamFactoryFactory) BsonValue(org.bson.BsonValue) Before(org.junit.Before)

Example 24 with MILLISECONDS

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

the class SessionCallbackBuilderTest method allowedCommand_withoutPlaylist_disallowsSkipTo.

@Test
public void allowedCommand_withoutPlaylist_disallowsSkipTo() throws Exception {
    int testRewindIncrementMs = 100;
    int testFastForwardIncrementMs = 100;
    try (MediaSession session = createMediaSession(sessionPlayerConnector, new SessionCallbackBuilder(context, sessionPlayerConnector).setRatingCallback((mediaSession, controller, mediaId, rating) -> SessionResult.RESULT_ERROR_BAD_VALUE).setRewindIncrementMs(testRewindIncrementMs).setFastForwardIncrementMs(testFastForwardIncrementMs).setMediaItemProvider(new SessionCallbackBuilder.MediaIdMediaItemProvider()).build())) {
        assertPlayerResultSuccess(sessionPlayerConnector.setMediaItem(TestUtils.createMediaItem()));
        assertPlayerResultSuccess(sessionPlayerConnector.prepare());
        CountDownLatch latch = new CountDownLatch(1);
        OnConnectedListener listener = (controller, allowedCommands) -> {
            List<Integer> disallowedCommandCodes = Arrays.asList(SessionCommand.COMMAND_CODE_PLAYER_SKIP_TO_PLAYLIST_ITEM, SessionCommand.COMMAND_CODE_PLAYER_SKIP_TO_PREVIOUS_PLAYLIST_ITEM, SessionCommand.COMMAND_CODE_PLAYER_SKIP_TO_NEXT_PLAYLIST_ITEM);
            assertDisallowedCommands(disallowedCommandCodes, allowedCommands);
            latch.countDown();
        };
        try (MediaController controller = createConnectedController(session, listener, null)) {
            assertThat(latch.await(CONTROLLER_COMMAND_WAIT_TIME_MS, MILLISECONDS)).isTrue();
            assertSessionResultFailure(controller.skipToNextPlaylistItem());
            assertSessionResultFailure(controller.skipToPreviousPlaylistItem());
            assertSessionResultFailure(controller.skipToPlaylistItem(0));
        }
    }
}
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) ArrayList(java.util.ArrayList) List(java.util.List) CountDownLatch(java.util.concurrent.CountDownLatch) LargeTest(androidx.test.filters.LargeTest) Test(org.junit.Test)

Example 25 with MILLISECONDS

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

the class SessionCallbackBuilderTest method setDisconnectedCallback_afterDisconnect_receivesOnDisconnected.

@Test
public void setDisconnectedCallback_afterDisconnect_receivesOnDisconnected() throws Exception {
    CountDownLatch disconnectedLatch = new CountDownLatch(1);
    SessionCallbackBuilder.DisconnectedCallback disconnectCallback = (session, controllerInfo) -> disconnectedLatch.countDown();
    try (MediaSession session = createMediaSession(sessionPlayerConnector, new SessionCallbackBuilder(context, sessionPlayerConnector).setDisconnectedCallback(disconnectCallback).build())) {
        try (MediaController controller = createConnectedController(session)) {
        }
        assertThat(disconnectedLatch.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) CountDownLatch(java.util.concurrent.CountDownLatch) LargeTest(androidx.test.filters.LargeTest) Test(org.junit.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