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();
}
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;
}
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));
}
}
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));
}
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;
}
Aggregations