Search in sources :

Example 26 with BsonString

use of org.bson.BsonString in project mongo-java-driver by mongodb.

the class ClientSideEncryptionExplicitEncryptionAndDecryptionTour method main.

/**
 * Run this main method to see the output of this quick example.
 *
 * @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);
                }
            });
        }
    };
    MongoClientSettings clientSettings = MongoClientSettings.builder().build();
    MongoClient mongoClient = MongoClients.create(clientSettings);
    // Set up the key vault for this example
    MongoNamespace keyVaultNamespace = new MongoNamespace("encryption.testKeyVault");
    MongoCollection<Document> keyVaultCollection = mongoClient.getDatabase(keyVaultNamespace.getDatabaseName()).getCollection(keyVaultNamespace.getCollectionName());
    keyVaultCollection.drop();
    // Ensure that two data keys cannot share the same keyAltName.
    keyVaultCollection.createIndex(Indexes.ascending("keyAltNames"), new IndexOptions().unique(true).partialFilterExpression(Filters.exists("keyAltNames")));
    MongoCollection<Document> collection = mongoClient.getDatabase("test").getCollection("coll");
    // Clear old data
    collection.drop();
    // Create the ClientEncryption instance
    ClientEncryptionSettings clientEncryptionSettings = ClientEncryptionSettings.builder().keyVaultMongoClientSettings(MongoClientSettings.builder().applyConnectionString(new ConnectionString("mongodb://localhost")).build()).keyVaultNamespace(keyVaultNamespace.getFullName()).kmsProviders(kmsProviders).build();
    ClientEncryption clientEncryption = ClientEncryptions.create(clientEncryptionSettings);
    BsonBinary dataKeyId = clientEncryption.createDataKey("local", new DataKeyOptions());
    // Explicitly encrypt a field
    BsonBinary encryptedFieldValue = clientEncryption.encrypt(new BsonString("123456789"), new EncryptOptions("AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic").keyId(dataKeyId));
    collection.insertOne(new Document("encryptedField", encryptedFieldValue));
    Document doc = collection.find().first();
    System.out.println(doc.toJson());
    // Explicitly decrypt the field
    System.out.println(clientEncryption.decrypt(new BsonBinary(doc.get("encryptedField", Binary.class).getData())));
    // release resources
    clientEncryption.close();
    mongoClient.close();
}
Also used : HashMap(java.util.HashMap) IndexOptions(com.mongodb.client.model.IndexOptions) BsonBinary(org.bson.BsonBinary) ClientEncryption(com.mongodb.client.vault.ClientEncryption) SecureRandom(java.security.SecureRandom) BsonString(org.bson.BsonString) ConnectionString(com.mongodb.ConnectionString) MongoClientSettings(com.mongodb.MongoClientSettings) MongoNamespace(com.mongodb.MongoNamespace) Document(org.bson.Document) DataKeyOptions(com.mongodb.client.model.vault.DataKeyOptions) MongoClient(com.mongodb.client.MongoClient) ClientEncryptionSettings(com.mongodb.ClientEncryptionSettings) EncryptOptions(com.mongodb.client.model.vault.EncryptOptions) BsonString(org.bson.BsonString) ConnectionString(com.mongodb.ConnectionString) HashMap(java.util.HashMap) Map(java.util.Map)

Example 27 with BsonString

use of org.bson.BsonString in project mongo-java-driver by mongodb.

the class QueryProtocol method asFindCommandDocument.

private BsonDocument asFindCommandDocument(final ByteBufferBsonOutput bsonOutput, final int firstDocumentPosition) {
    BsonDocument command = new BsonDocument(FIND_COMMAND_NAME, new BsonString(namespace.getCollectionName()));
    boolean isExplain = false;
    List<ByteBufBsonDocument> documents = ByteBufBsonDocument.createList(bsonOutput, firstDocumentPosition);
    ByteBufBsonDocument rawQueryDocument = documents.get(0);
    for (Map.Entry<String, BsonValue> cur : rawQueryDocument.entrySet()) {
        String commandFieldName = META_OPERATOR_TO_COMMAND_FIELD_MAP.get(cur.getKey());
        if (commandFieldName != null) {
            command.append(commandFieldName, cur.getValue());
        } else if (cur.getKey().equals("$explain")) {
            isExplain = true;
        }
    }
    if (command.size() == 1) {
        command.append("filter", rawQueryDocument);
    }
    if (documents.size() == 2) {
        command.append("projection", documents.get(1));
    }
    if (skip != 0) {
        command.append("skip", new BsonInt32(skip));
    }
    if (withLimitAndBatchSize) {
        if (limit != 0) {
            command.append("limit", new BsonInt32(limit));
        }
        if (batchSize != 0) {
            command.append("batchSize", new BsonInt32(batchSize));
        }
    }
    if (tailableCursor) {
        command.append("tailable", BsonBoolean.valueOf(tailableCursor));
    }
    if (noCursorTimeout) {
        command.append("noCursorTimeout", BsonBoolean.valueOf(noCursorTimeout));
    }
    if (oplogReplay) {
        command.append("oplogReplay", BsonBoolean.valueOf(oplogReplay));
    }
    if (awaitData) {
        command.append("awaitData", BsonBoolean.valueOf(awaitData));
    }
    if (partial) {
        command.append("allowPartialResults", BsonBoolean.valueOf(partial));
    }
    if (isExplain) {
        command = new BsonDocument(EXPLAIN_COMMAND_NAME, command);
    }
    return command;
}
Also used : BsonInt32(org.bson.BsonInt32) BsonDocument(org.bson.BsonDocument) BsonString(org.bson.BsonString) BsonString(org.bson.BsonString) HashMap(java.util.HashMap) Map(java.util.Map) BsonValue(org.bson.BsonValue)

Example 28 with BsonString

use of org.bson.BsonString in project mongo-java-driver by mongodb.

the class QueryProtocol method asFindCommandResponseDocument.

private BsonDocument asFindCommandResponseDocument(final ResponseBuffers responseBuffers, final QueryResult<T> queryResult, final boolean isExplain) {
    List<ByteBufBsonDocument> rawResultDocuments = Collections.emptyList();
    if (responseBuffers.getReplyHeader().getNumberReturned() > 0) {
        responseBuffers.reset();
        rawResultDocuments = ByteBufBsonDocument.createList(responseBuffers);
    }
    if (isExplain) {
        BsonDocument explainCommandResponseDocument = new BsonDocument("ok", new BsonDouble(1));
        explainCommandResponseDocument.putAll(rawResultDocuments.get(0));
        return explainCommandResponseDocument;
    } else {
        BsonDocument cursorDocument = new BsonDocument("id", queryResult.getCursor() == null ? new BsonInt64(0) : new BsonInt64(queryResult.getCursor().getId())).append("ns", new BsonString(namespace.getFullName())).append("firstBatch", new BsonArray(rawResultDocuments));
        return new BsonDocument("cursor", cursorDocument).append("ok", new BsonDouble(1));
    }
}
Also used : BsonInt64(org.bson.BsonInt64) BsonDocument(org.bson.BsonDocument) BsonString(org.bson.BsonString) BsonArray(org.bson.BsonArray) BsonDouble(org.bson.BsonDouble)

Example 29 with BsonString

use of org.bson.BsonString in project mongo-java-driver by mongodb.

the class GetMoreProtocol method asGetMoreCommandResponseDocument.

private BsonDocument asGetMoreCommandResponseDocument(final QueryResult<T> queryResult, final ResponseBuffers responseBuffers) {
    List<ByteBufBsonDocument> rawResultDocuments = Collections.emptyList();
    if (responseBuffers.getReplyHeader().getNumberReturned() != 0) {
        responseBuffers.reset();
        rawResultDocuments = ByteBufBsonDocument.createList(responseBuffers);
    }
    BsonDocument cursorDocument = new BsonDocument("id", queryResult.getCursor() == null ? new BsonInt64(0) : new BsonInt64(queryResult.getCursor().getId())).append("ns", new BsonString(namespace.getFullName())).append("nextBatch", new BsonArray(rawResultDocuments));
    return new BsonDocument("cursor", cursorDocument).append("ok", new BsonDouble(1));
}
Also used : BsonInt64(org.bson.BsonInt64) BsonDocument(org.bson.BsonDocument) BsonString(org.bson.BsonString) BsonArray(org.bson.BsonArray) BsonDouble(org.bson.BsonDouble)

Example 30 with BsonString

use of org.bson.BsonString in project mongo-java-driver by mongodb.

the class InternalStreamConnectionInitializer method createHelloCommand.

private BsonDocument createHelloCommand(final Authenticator authenticator, final InternalConnection connection) {
    BsonDocument helloCommandDocument = new BsonDocument(getHandshakeCommandName(), new BsonInt32(1)).append("helloOk", BsonBoolean.TRUE);
    if (clientMetadataDocument != null) {
        helloCommandDocument.append("client", clientMetadataDocument);
    }
    if (clusterConnectionMode == ClusterConnectionMode.LOAD_BALANCED) {
        helloCommandDocument.append("loadBalanced", BsonBoolean.TRUE);
    }
    if (!requestedCompressors.isEmpty()) {
        BsonArray compressors = new BsonArray(this.requestedCompressors.size());
        for (MongoCompressor cur : this.requestedCompressors) {
            compressors.add(new BsonString(cur.getName()));
        }
        helloCommandDocument.append("compression", compressors);
    }
    if (checkSaslSupportedMechs) {
        MongoCredential credential = authenticator.getMongoCredential();
        helloCommandDocument.append("saslSupportedMechs", new BsonString(credential.getSource() + "." + credential.getUserName()));
    }
    if (authenticator instanceof SpeculativeAuthenticator) {
        BsonDocument speculativeAuthenticateDocument = ((SpeculativeAuthenticator) authenticator).createSpeculativeAuthenticateCommand(connection);
        if (speculativeAuthenticateDocument != null) {
            helloCommandDocument.append("speculativeAuthenticate", speculativeAuthenticateDocument);
        }
    }
    return helloCommandDocument;
}
Also used : BsonInt32(org.bson.BsonInt32) BsonDocument(org.bson.BsonDocument) MongoCredential(com.mongodb.MongoCredential) BsonString(org.bson.BsonString) BsonArray(org.bson.BsonArray) MongoCompressor(com.mongodb.MongoCompressor)

Aggregations

BsonString (org.bson.BsonString)168 BsonDocument (org.bson.BsonDocument)146 BsonInt32 (org.bson.BsonInt32)54 BsonArray (org.bson.BsonArray)48 Test (org.junit.Test)33 BsonValue (org.bson.BsonValue)31 Document (org.bson.Document)28 BsonInt64 (org.bson.BsonInt64)27 ArrayList (java.util.ArrayList)23 Map (java.util.Map)14 MongoClientSettings (com.mongodb.MongoClientSettings)13 BsonBinary (org.bson.BsonBinary)13 BsonDouble (org.bson.BsonDouble)13 EncryptOptions (com.mongodb.client.model.vault.EncryptOptions)12 HashMap (java.util.HashMap)12 MongoNamespace (com.mongodb.MongoNamespace)11 Test (org.junit.jupiter.api.Test)11 List (java.util.List)10 DataKeyOptions (com.mongodb.client.model.vault.DataKeyOptions)9 BsonBoolean (org.bson.BsonBoolean)9