use of org.bson.BsonString in project drill by apache.
the class MongoAggregateUtils method getAggregateOperations.
public static List<Bson> getAggregateOperations(Aggregate aggregate, RelDataType rowType) {
List<String> inNames = mongoFieldNames(rowType);
List<String> outNames = mongoFieldNames(aggregate.getRowType());
Object id;
if (aggregate.getGroupSet().cardinality() == 1) {
String inName = inNames.get(aggregate.getGroupSet().nth(0));
id = "$" + inName;
} else {
List<BsonElement> elements = StreamSupport.stream(aggregate.getGroupSet().spliterator(), false).map(inNames::get).map(inName -> new BsonElement(inName, new BsonString("$" + inName))).collect(Collectors.toList());
id = new BsonDocument(elements);
}
int outNameIndex = aggregate.getGroupSet().cardinality();
List<BsonField> accumList = new ArrayList<>();
for (AggregateCall aggCall : aggregate.getAggCallList()) {
accumList.add(bsonAggregate(inNames, outNames.get(outNameIndex++), aggCall));
}
List<Bson> operationsList = new ArrayList<>();
operationsList.add(Aggregates.group(id, accumList).toBsonDocument());
List<BsonElement> projectFields = new ArrayList<>();
if (aggregate.getGroupSet().cardinality() == 1) {
for (int index = 0; index < outNames.size(); index++) {
String outName = outNames.get(index);
projectFields.add(new BsonElement(maybeQuote(outName), new BsonString("$" + (index == 0 ? "_id" : outName))));
}
} else {
projectFields.add(new BsonElement("_id", new BsonInt32(0)));
for (int group : aggregate.getGroupSet()) {
projectFields.add(new BsonElement(maybeQuote(outNames.get(group)), new BsonString("$_id." + outNames.get(group))));
}
outNameIndex = aggregate.getGroupSet().cardinality();
for (AggregateCall ignored : aggregate.getAggCallList()) {
String outName = outNames.get(outNameIndex++);
projectFields.add(new BsonElement(maybeQuote(outName), new BsonString("$" + outName)));
}
}
if (!aggregate.getGroupSet().isEmpty()) {
operationsList.add(Aggregates.project(new BsonDocument(projectFields)).toBsonDocument());
}
return operationsList;
}
use of org.bson.BsonString in project pinpoint by naver.
the class WritecontextTest method parseBsonArrayWithValues.
@Test
public void parseBsonArrayWithValues() throws IOException {
BsonValue a = new BsonString("stest");
BsonValue b = new BsonDouble(111);
BsonValue c = new BsonBoolean(true);
BsonDocument document = new BsonDocument().append("int32", new BsonInt32(12)).append("int64", new BsonInt64(77L)).append("bo\"olean", new BsonBoolean(true)).append("date", new BsonDateTime(new Date().getTime())).append("double", new BsonDouble(12.3)).append("string", new BsonString("pinpoint")).append("objectId", new BsonObjectId(new ObjectId())).append("code", new BsonJavaScript("int i = 10;")).append("codeWithScope", new BsonJavaScriptWithScope("int x = y", new BsonDocument("y", new BsonInt32(1)))).append("regex", new BsonRegularExpression("^test.*regex.*xyz$", "big")).append("symbol", new BsonSymbol("wow")).append("timestamp", new BsonTimestamp(0x12345678, 5)).append("undefined", new BsonUndefined()).append("binary1", new BsonBinary(new byte[] { (byte) 0xe0, 0x4f, (byte) 0xd0, 0x20 })).append("oldBinary", new BsonBinary(BsonBinarySubType.OLD_BINARY, new byte[] { 1, 1, 1, 1, 1 })).append("arrayInt", new BsonArray(Arrays.asList(a, b, c, new BsonInt32(7)))).append("document", new BsonDocument("a", new BsonInt32(77))).append("dbPointer", new BsonDbPointer("db.coll", new ObjectId())).append("null", new BsonNull()).append("decimal128", new BsonDecimal128(new Decimal128(55)));
BasicDBObject query = new BasicDBObject();
query.put("ComplexBson", document);
logger.debug("document:{}", document);
NormalizedBson stringStringValue = MongoUtil.parseBson(new Object[] { query }, true);
logger.debug("val:{}", stringStringValue);
List list = objectMapper.readValue("[" + stringStringValue.getNormalizedBson() + "]", List.class);
Assert.assertEquals(list.size(), 1);
Map<String, ?> query1Map = (Map<String, ?>) list.get(0);
checkValue(query1Map);
}
use of org.bson.BsonString in project mongo-java-driver by mongodb.
the class EnumCodecTest method shouldDecodeEnum.
@Test
public void shouldDecodeEnum() {
Codec<SimpleEnum> codec = new EnumCodec<>(SimpleEnum.class);
SimpleEnum decodedValue = getDecodedValue(new BsonString(SimpleEnum.BRAVO.name()), codec);
assertEquals(SimpleEnum.BRAVO, decodedValue);
}
use of org.bson.BsonString in project mongo-java-driver by mongodb.
the class FindPublisherImplTest method shouldBuildTheExpectedOperation.
@DisplayName("Should build the expected FindOperation")
@Test
void shouldBuildTheExpectedOperation() {
configureBatchCursor();
TestOperationExecutor executor = createOperationExecutor(asList(getBatchCursor(), getBatchCursor()));
FindPublisher<Document> publisher = new FindPublisherImpl<>(null, createMongoOperationPublisher(executor), new Document());
FindOperation<Document> expectedOperation = new FindOperation<>(NAMESPACE, getDefaultCodecRegistry().get(Document.class)).batchSize(Integer.MAX_VALUE).retryReads(true).filter(new BsonDocument());
// default input should be as expected
Flux.from(publisher).blockFirst();
assertOperationIsTheSameAs(expectedOperation, executor.getReadOperation());
assertEquals(ReadPreference.primary(), executor.getReadPreference());
// Should apply settings
publisher.filter(new Document("filter", 1)).sort(Sorts.ascending("sort")).projection(new Document("projection", 1)).maxTime(10, SECONDS).maxAwaitTime(20, SECONDS).batchSize(100).limit(100).skip(10).cursorType(CursorType.NonTailable).oplogReplay(false).noCursorTimeout(false).partial(false).collation(COLLATION).comment("my comment").hintString("a_1").min(new Document("min", 1)).max(new Document("max", 1)).returnKey(false).showRecordId(false).allowDiskUse(false);
expectedOperation.allowDiskUse(false).batchSize(100).collation(COLLATION).comment("my comment").cursorType(CursorType.NonTailable).filter(new BsonDocument("filter", new BsonInt32(1))).hint(new BsonString("a_1")).limit(100).max(new BsonDocument("max", new BsonInt32(1))).maxAwaitTime(20000, MILLISECONDS).maxTime(10000, MILLISECONDS).min(new BsonDocument("min", new BsonInt32(1))).projection(new BsonDocument("projection", new BsonInt32(1))).returnKey(false).showRecordId(false).skip(10).secondaryOk(false).sort(new BsonDocument("sort", new BsonInt32(1)));
configureBatchCursor();
Flux.from(publisher).blockFirst();
assertOperationIsTheSameAs(expectedOperation, executor.getReadOperation());
assertEquals(ReadPreference.primary(), executor.getReadPreference());
}
use of org.bson.BsonString in project mongo-java-driver by mongodb.
the class ClientSideEncryptionExplicitEncryptionOnlyTour 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);
}
});
}
};
MongoNamespace keyVaultNamespace = new MongoNamespace("encryption.testKeyVault");
MongoClientSettings clientSettings = MongoClientSettings.builder().autoEncryptionSettings(AutoEncryptionSettings.builder().keyVaultNamespace(keyVaultNamespace.getFullName()).kmsProviders(kmsProviders).bypassAutoEncryption(true).build()).build();
MongoClient mongoClient = MongoClients.create(clientSettings);
// Set up the key vault for this example
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));
// Automatically decrypts the encrypted field.
System.out.println(collection.find().first().toJson());
// release resources
clientEncryption.close();
mongoClient.close();
}
Aggregations