Search in sources :

Example 11 with MongoClient

use of com.mongodb.reactivestreams.client.MongoClient in project MongoSK by Romitou.

the class ExprMongoServer method get.

@SuppressWarnings("unchecked")
@Override
protected MongoSKServer[] get(@Nonnull final Event e) {
    String rawConnectionString = (exprRawConnectionString instanceof VariableString) ? ((VariableString) exprRawConnectionString).toUnformattedString(e) : ((Expression<String>) exprRawConnectionString).getSingle(e);
    if (rawConnectionString == null)
        return new MongoSKServer[0];
    // Validate the connection string.
    ConnectionString connectionString;
    try {
        connectionString = new ConnectionString(rawConnectionString);
    } catch (IllegalArgumentException ex) {
        LoggerHelper.severe("Your connection string is invalid: " + ex.getMessage().toLowerCase());
        return new MongoSKServer[0];
    } catch (MongoClientException ex) {
        LoggerHelper.severe("An error occurred while creating the client: " + ex.getMessage().toLowerCase());
        return new MongoSKServer[0];
    }
    // Create listeners.
    MongoCommandListener mongoCommandListener = new MongoCommandListener();
    // Build the Mongo client settings.
    MongoClientSettings.Builder settings = MongoClientSettings.builder().applyConnectionString(connectionString).applyToSocketSettings(builder -> builder.connectTimeout(CONNECT_TIMEOUT, TimeUnit.MILLISECONDS).readTimeout(READ_TIMEOUT, TimeUnit.MILLISECONDS)).applicationName(connectionString.getApplicationName() == null ? "MongoSK/" + MongoSK.getInstance().getDescription().getVersion() : connectionString.getApplicationName()).addCommandListener(mongoCommandListener);
    MongoClient mongoClient = MongoClients.create(settings.build());
    // Get the most pertinent displayed name for this client.
    String displayedName = connectionString.getApplicationName() == null ? connectionString.getHosts().get(0) : connectionString.getApplicationName();
    // Create the MongoSKServer object.
    MongoSKServer mongoSKServer = new MongoSKServer(displayedName, mongoClient);
    // Add this server to the listeners (we must do this because the client is only created after the builder).
    mongoCommandListener.setMongoSKServer(mongoSKServer);
    // Return the MongoSKServer linked with the listeners.
    return new MongoSKServer[] { mongoSKServer };
}
Also used : MongoClient(com.mongodb.reactivestreams.client.MongoClient) MongoClientException(com.mongodb.MongoClientException) MongoSKServer(fr.romitou.mongosk.elements.MongoSKServer) VariableString(ch.njol.skript.lang.VariableString) MongoCommandListener(fr.romitou.mongosk.listeners.MongoCommandListener) ConnectionString(com.mongodb.ConnectionString) VariableString(ch.njol.skript.lang.VariableString) MongoClientSettings(com.mongodb.MongoClientSettings) ConnectionString(com.mongodb.ConnectionString)

Example 12 with MongoClient

use of com.mongodb.reactivestreams.client.MongoClient in project gravitee-access-management by gravitee-io.

the class MongodbProvider method afterPropertiesSet.

@Override
public void afterPropertiesSet() {
    mongoDBContainer = new MongoDBContainer(DockerImageName.parse("mongo:4.0.10"));
    mongoDBContainer.withEnv("MONGO_INITDB_DATABASE", databaseName);
    mongoDBContainer.start();
    // cluster configuration
    ClusterSettings clusterSettings = ClusterSettings.builder().hosts(Collections.singletonList(new ServerAddress(mongoDBContainer.getHost(), mongoDBContainer.getFirstMappedPort()))).build();
    // codec configuration
    CodecRegistry pojoCodecRegistry = fromRegistries(MongoClients.getDefaultCodecRegistry(), fromProviders(PojoCodecProvider.builder().automatic(true).build()));
    MongoClientSettings settings = MongoClientSettings.builder().applyToClusterSettings(builder1 -> builder1.applySettings(clusterSettings)).codecRegistry(pojoCodecRegistry).writeConcern(WriteConcern.ACKNOWLEDGED).build();
    mongoClient = MongoClients.create(settings);
    mongoDatabase = mongoClient.getDatabase(databaseName);
}
Also used : MongoDBContainer(org.testcontainers.containers.MongoDBContainer) ServerAddress(com.mongodb.ServerAddress) PojoCodecProvider(org.bson.codecs.pojo.PojoCodecProvider) DockerImageName(org.testcontainers.utility.DockerImageName) CodecRegistries.fromProviders(org.bson.codecs.configuration.CodecRegistries.fromProviders) ClusterSettings(com.mongodb.connection.ClusterSettings) MongoClients(com.mongodb.reactivestreams.client.MongoClients) CodecRegistry(org.bson.codecs.configuration.CodecRegistry) InitializingBean(org.springframework.beans.factory.InitializingBean) MongoDBContainer(org.testcontainers.containers.MongoDBContainer) MongoClient(com.mongodb.reactivestreams.client.MongoClient) MongoDatabase(com.mongodb.reactivestreams.client.MongoDatabase) DisposableBean(org.springframework.beans.factory.DisposableBean) MongoClientSettings(com.mongodb.MongoClientSettings) WriteConcern(com.mongodb.WriteConcern) Collections(java.util.Collections) CodecRegistries.fromRegistries(org.bson.codecs.configuration.CodecRegistries.fromRegistries) ClusterSettings(com.mongodb.connection.ClusterSettings) ServerAddress(com.mongodb.ServerAddress) MongoClientSettings(com.mongodb.MongoClientSettings) CodecRegistry(org.bson.codecs.configuration.CodecRegistry)

Example 13 with MongoClient

use of com.mongodb.reactivestreams.client.MongoClient in project gravitee-access-management by gravitee-io.

the class MongoFactory method getObject.

@Override
public MongoClient getObject() throws Exception {
    // Client settings
    MongoClientSettings.Builder builder = MongoClientSettings.builder();
    builder.writeConcern(WriteConcern.ACKNOWLEDGED);
    CodecRegistry defaultCodecRegistry = MongoClients.getDefaultCodecRegistry();
    CodecRegistry pojoCodecRegistry = fromProviders(PojoCodecProvider.builder().automatic(true).build());
    builder.codecRegistry(fromRegistries(defaultCodecRegistry, pojoCodecRegistry));
    // Trying to get the MongoClientURI if uri property is defined
    String uri = readPropertyValue(propertyPrefix + "uri");
    if (uri != null && !uri.isEmpty()) {
        // The builder can be configured with default options, which may be overridden by options specified in
        // the URI string.
        MongoClientSettings settings = builder.applyConnectionString(new ConnectionString(uri)).build();
        return MongoClients.create(settings);
    } else {
        // Advanced configuration
        SocketSettings.Builder socketBuilder = SocketSettings.builder();
        ClusterSettings.Builder clusterBuilder = ClusterSettings.builder();
        ConnectionPoolSettings.Builder connectionPoolBuilder = ConnectionPoolSettings.builder();
        ServerSettings.Builder serverBuilder = ServerSettings.builder();
        SslSettings.Builder sslBuilder = SslSettings.builder();
        Integer connectTimeout = readPropertyValue(propertyPrefix + "connectTimeout", Integer.class, 1000);
        Integer maxWaitTime = readPropertyValue(propertyPrefix + "maxWaitTime", Integer.class);
        Integer socketTimeout = readPropertyValue(propertyPrefix + "socketTimeout", Integer.class, 1000);
        Integer maxConnectionLifeTime = readPropertyValue(propertyPrefix + "maxConnectionLifeTime", Integer.class);
        Integer maxConnectionIdleTime = readPropertyValue(propertyPrefix + "maxConnectionIdleTime", Integer.class);
        // We do not want to wait for a server
        Integer serverSelectionTimeout = readPropertyValue(propertyPrefix + "serverSelectionTimeout", Integer.class, 1000);
        Integer minHeartbeatFrequency = readPropertyValue(propertyPrefix + "minHeartbeatFrequency", Integer.class);
        String description = readPropertyValue(propertyPrefix + "description", String.class, "gravitee.io");
        Integer heartbeatFrequency = readPropertyValue(propertyPrefix + "heartbeatFrequency", Integer.class);
        Boolean sslEnabled = readPropertyValue(propertyPrefix + "sslEnabled", Boolean.class);
        String keystore = readPropertyValue(propertyPrefix + "keystore", String.class);
        String keystorePassword = readPropertyValue(propertyPrefix + "keystorePassword", String.class);
        String keyPassword = readPropertyValue(propertyPrefix + "keyPassword", String.class);
        if (maxWaitTime != null)
            connectionPoolBuilder.maxWaitTime(maxWaitTime, TimeUnit.MILLISECONDS);
        if (connectTimeout != null)
            socketBuilder.connectTimeout(connectTimeout, TimeUnit.MILLISECONDS);
        if (socketTimeout != null)
            socketBuilder.readTimeout(socketTimeout, TimeUnit.MILLISECONDS);
        if (maxConnectionLifeTime != null)
            connectionPoolBuilder.maxConnectionLifeTime(maxConnectionLifeTime, TimeUnit.MILLISECONDS);
        if (maxConnectionIdleTime != null)
            connectionPoolBuilder.maxConnectionIdleTime(maxConnectionIdleTime, TimeUnit.MILLISECONDS);
        if (minHeartbeatFrequency != null)
            serverBuilder.minHeartbeatFrequency(minHeartbeatFrequency, TimeUnit.MILLISECONDS);
        if (description != null)
            builder.applicationName(description);
        if (heartbeatFrequency != null)
            serverBuilder.heartbeatFrequency(heartbeatFrequency, TimeUnit.MILLISECONDS);
        if (sslEnabled != null)
            sslBuilder.enabled(sslEnabled);
        if (keystore != null) {
            try {
                SSLContext ctx = SSLContext.getInstance("TLS");
                KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
                KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
                ks.load(new FileInputStream(keystore), keystorePassword.toCharArray());
                keyManagerFactory.init(ks, keyPassword.toCharArray());
                ctx.init(keyManagerFactory.getKeyManagers(), null, null);
                sslBuilder.context(ctx);
            } catch (Exception e) {
                logger.error(e.getCause().toString());
                throw new IllegalStateException("Error creating the keystore for mongodb", e);
            }
        }
        if (serverSelectionTimeout != null)
            clusterBuilder.serverSelectionTimeout(serverSelectionTimeout, TimeUnit.MILLISECONDS);
        // credentials option
        String username = readPropertyValue(propertyPrefix + "username");
        String password = readPropertyValue(propertyPrefix + "password");
        MongoCredential credentials = null;
        if (username != null || password != null) {
            String authSource = readPropertyValue(propertyPrefix + "authSource", String.class, "gravitee-am");
            credentials = MongoCredential.createCredential(username, authSource, password.toCharArray());
            builder.credential(credentials);
        }
        // clustering option
        List<ServerAddress> seeds;
        int serversCount = getServersCount();
        if (serversCount == 0) {
            String host = readPropertyValue(propertyPrefix + "host", String.class, "localhost");
            int port = readPropertyValue(propertyPrefix + "port", int.class, 27017);
            seeds = Collections.singletonList(new ServerAddress(host, port));
        } else {
            seeds = new ArrayList<>(serversCount);
            for (int i = 0; i < serversCount; i++) {
                seeds.add(buildServerAddress(i));
            }
        }
        clusterBuilder.hosts(seeds);
        SocketSettings socketSettings = socketBuilder.build();
        ClusterSettings clusterSettings = clusterBuilder.build();
        ConnectionPoolSettings connectionPoolSettings = connectionPoolBuilder.build();
        ServerSettings serverSettings = serverBuilder.build();
        SslSettings sslSettings = sslBuilder.build();
        MongoClientSettings settings = builder.applyToClusterSettings(builder1 -> builder1.applySettings(clusterSettings)).applyToSocketSettings(builder1 -> builder1.applySettings(socketSettings)).applyToConnectionPoolSettings(builder1 -> builder1.applySettings(connectionPoolSettings)).applyToServerSettings(builder1 -> builder1.applySettings(serverSettings)).applyToSslSettings(builder1 -> builder1.applySettings(sslSettings)).build();
        return MongoClients.create(settings);
    }
}
Also used : SSLContext(javax.net.ssl.SSLContext) LoggerFactory(org.slf4j.LoggerFactory) Autowired(org.springframework.beans.factory.annotation.Autowired) MongoClients(com.mongodb.reactivestreams.client.MongoClients) CodecRegistry(org.bson.codecs.configuration.CodecRegistry) BsonReader(org.bson.BsonReader) MongoClient(com.mongodb.reactivestreams.client.MongoClient) ArrayList(java.util.ArrayList) FactoryBean(org.springframework.beans.factory.FactoryBean) com.mongodb(com.mongodb) com.mongodb.connection(com.mongodb.connection) DecoderContext(org.bson.codecs.DecoderContext) CodecRegistries.fromRegistries(org.bson.codecs.configuration.CodecRegistries.fromRegistries) EncoderContext(org.bson.codecs.EncoderContext) Logger(org.slf4j.Logger) PojoCodecProvider(org.bson.codecs.pojo.PojoCodecProvider) CodecRegistries.fromProviders(org.bson.codecs.configuration.CodecRegistries.fromProviders) KeyManagerFactory(javax.net.ssl.KeyManagerFactory) CodecRegistries(org.bson.codecs.configuration.CodecRegistries) KeyStore(java.security.KeyStore) FileInputStream(java.io.FileInputStream) UserNotificationStatus(io.gravitee.am.model.notification.UserNotificationStatus) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) Environment(org.springframework.core.env.Environment) Codec(org.bson.codecs.Codec) BsonWriter(org.bson.BsonWriter) Collections(java.util.Collections) CodecRegistry(org.bson.codecs.configuration.CodecRegistry) SSLContext(javax.net.ssl.SSLContext) KeyStore(java.security.KeyStore) FileInputStream(java.io.FileInputStream) KeyManagerFactory(javax.net.ssl.KeyManagerFactory)

Example 14 with MongoClient

use of com.mongodb.reactivestreams.client.MongoClient in project immutables by immutables.

the class MongoInstance method create.

static MongoInstance create() {
    final String uri = System.getProperty("mongo");
    if (uri != null) {
        // connect to remote mongo server
        return new MongoInstance(MongoClients.create(uri));
    }
    final MongoServer server = new MongoServer(new MemoryBackend());
    final InetSocketAddress address = server.bind();
    final Closer closer = Closer.create();
    closer.register(server::shutdownNow);
    final MongoClient client = MongoClients.create(String.format("mongodb://127.0.0.1:%d", address.getPort()));
    return new MongoInstance(client, closer);
}
Also used : Closer(com.google.common.io.Closer) MongoClient(com.mongodb.reactivestreams.client.MongoClient) MemoryBackend(de.bwaldvogel.mongo.backend.memory.MemoryBackend) InetSocketAddress(java.net.InetSocketAddress) MongoServer(de.bwaldvogel.mongo.MongoServer)

Example 15 with MongoClient

use of com.mongodb.reactivestreams.client.MongoClient in project mongo-java-driver by mongodb.

the class ClientSideEncryptionAutoEncryptionSettingsTour method main.

/**
 * Run this main method to see the output of this quick example.
 *
 * Requires the mongodb-crypt library in the class path and mongocryptd on the system path.
 *
 * @param args ignored args
 */
public static void main(final String[] args) {
    // This would have to be the same master key as was used to create the encryption key
    final byte[] localMasterKey = new byte[96];
    new SecureRandom().nextBytes(localMasterKey);
    Map<String, Map<String, Object>> kmsProviders = new HashMap<String, Map<String, Object>>() {

        {
            put("local", new HashMap<String, Object>() {

                {
                    put("key", localMasterKey);
                }
            });
        }
    };
    String keyVaultNamespace = "admin.datakeys";
    ClientEncryptionSettings clientEncryptionSettings = ClientEncryptionSettings.builder().keyVaultMongoClientSettings(MongoClientSettings.builder().applyConnectionString(new ConnectionString("mongodb://localhost")).build()).keyVaultNamespace(keyVaultNamespace).kmsProviders(kmsProviders).build();
    ClientEncryption clientEncryption = ClientEncryptions.create(clientEncryptionSettings);
    ObservableSubscriber<BsonBinary> dataKeySubscriber = new OperationSubscriber<>();
    clientEncryption.createDataKey("local", new DataKeyOptions()).subscribe(dataKeySubscriber);
    dataKeySubscriber.await();
    String base64DataKeyId = Base64.getEncoder().encodeToString(dataKeySubscriber.getReceived().get(0).getData());
    final String dbName = "test";
    final String collName = "coll";
    AutoEncryptionSettings autoEncryptionSettings = AutoEncryptionSettings.builder().keyVaultNamespace(keyVaultNamespace).kmsProviders(kmsProviders).schemaMap(new HashMap<String, BsonDocument>() {

        {
            put(dbName + "." + collName, // Need a schema that references the new data key
            BsonDocument.parse("{" + "  properties: {" + "    encryptedField: {" + "      encrypt: {" + "        keyId: [{" + "          \"$binary\": {" + "            \"base64\": \"" + base64DataKeyId + "\"," + "            \"subType\": \"04\"" + "          }" + "        }]," + "        bsonType: \"string\"," + "        algorithm: \"AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic\"" + "      }" + "    }" + "  }," + "  \"bsonType\": \"object\"" + "}"));
        }
    }).build();
    MongoClientSettings clientSettings = MongoClientSettings.builder().autoEncryptionSettings(autoEncryptionSettings).build();
    MongoClient mongoClient = MongoClients.create(clientSettings);
    MongoCollection<Document> collection = mongoClient.getDatabase("test").getCollection("coll");
    ObservableSubscriber<Void> successSubscriber = new OperationSubscriber<>();
    collection.drop().subscribe(successSubscriber);
    successSubscriber.await();
    ObservableSubscriber<InsertOneResult> insertOneSubscriber = new OperationSubscriber<>();
    collection.insertOne(new Document("encryptedField", "123456789")).subscribe(insertOneSubscriber);
    insertOneSubscriber.await();
    ObservableSubscriber<Document> documentSubscriber = new PrintDocumentSubscriber();
    collection.find().first().subscribe(documentSubscriber);
    documentSubscriber.await();
    // release resources
    mongoClient.close();
}
Also used : PrintDocumentSubscriber(reactivestreams.helpers.SubscriberHelpers.PrintDocumentSubscriber) HashMap(java.util.HashMap) ClientEncryption(com.mongodb.reactivestreams.client.vault.ClientEncryption) ConnectionString(com.mongodb.ConnectionString) Document(org.bson.Document) BsonDocument(org.bson.BsonDocument) DataKeyOptions(com.mongodb.client.model.vault.DataKeyOptions) MongoClient(com.mongodb.reactivestreams.client.MongoClient) ClientEncryptionSettings(com.mongodb.ClientEncryptionSettings) InsertOneResult(com.mongodb.client.result.InsertOneResult) BsonBinary(org.bson.BsonBinary) OperationSubscriber(reactivestreams.helpers.SubscriberHelpers.OperationSubscriber) SecureRandom(java.security.SecureRandom) MongoClientSettings(com.mongodb.MongoClientSettings) AutoEncryptionSettings(com.mongodb.AutoEncryptionSettings) ConnectionString(com.mongodb.ConnectionString) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

MongoClient (com.mongodb.reactivestreams.client.MongoClient)29 MongoClientSettings (com.mongodb.MongoClientSettings)10 Test (org.junit.Test)10 ServerAddress (com.mongodb.ServerAddress)8 InsertOneResult (com.mongodb.client.result.InsertOneResult)7 Document (org.bson.Document)7 OperationSubscriber (reactivestreams.helpers.SubscriberHelpers.OperationSubscriber)7 MongoClients (com.mongodb.reactivestreams.client.MongoClients)6 ConnectionString (com.mongodb.ConnectionString)5 MongoDatabase (com.mongodb.reactivestreams.client.MongoDatabase)5 CodecRegistry (org.bson.codecs.configuration.CodecRegistry)5 ClusterSettings (com.mongodb.connection.ClusterSettings)4 SecureRandom (java.security.SecureRandom)4 HashMap (java.util.HashMap)4 Map (java.util.Map)4 CodecRegistries.fromProviders (org.bson.codecs.configuration.CodecRegistries.fromProviders)4 CodecRegistries.fromRegistries (org.bson.codecs.configuration.CodecRegistries.fromRegistries)4 PojoCodecProvider (org.bson.codecs.pojo.PojoCodecProvider)4 ClientEncryptionSettings (com.mongodb.ClientEncryptionSettings)3 MongoCredential (com.mongodb.MongoCredential)3