org.bson.codecs.configuration.CodecRegistries Java Examples
The following examples show how to use
org.bson.codecs.configuration.CodecRegistries.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CoreStitchAuth.java From stitch-android-sdk with Apache License 2.0 | 6 votes |
/** * Performs a request against Stitch using the provided {@link StitchAuthRequest} object, and * decodes the JSON body of the response into a T value as specified by the provided class type. * The type will be decoded using the codec found for T in the codec registry given. * If the provided type is not supported by the codec registry to be used, the method will throw * a {@link org.bson.codecs.configuration.CodecConfigurationException}. * * @param stitchReq the request to perform. * @param resultClass the class that the JSON response should be decoded as. * @param codecRegistry the codec registry used for de/serialization. * @param <T> the type into which the JSON response will be decoded into. * @return the decoded value. */ public <T> T doAuthenticatedRequest( final StitchAuthRequest stitchReq, final Class<T> resultClass, final CodecRegistry codecRegistry ) { final Response response = doAuthenticatedRequest(stitchReq); try { final String bodyStr = IoUtils.readAllToString(response.getBody()); final JsonReader bsonReader = new JsonReader(bodyStr); // We must check this condition because the decoder will throw trying to decode null if (bsonReader.readBsonType() == BsonType.NULL) { return null; } final CodecRegistry newReg = CodecRegistries.fromRegistries(BsonUtils.DEFAULT_CODEC_REGISTRY, codecRegistry); return newReg.get(resultClass).decode(bsonReader, DecoderContext.builder().build()); } catch (final Exception e) { throw new StitchRequestException(e, StitchRequestErrorCode.DECODING_ERROR); } }
Example #2
Source File: MongoClientWrapper.java From mongowp with Apache License 2.0 | 6 votes |
@Inject public MongoClientWrapper(MongoClientConfiguration configuration) throws UnreachableMongoServerException { try { MongoClientOptions options = toMongoClientOptions(configuration); ImmutableList<MongoCredential> credentials = toMongoCredentials(configuration); testAddress(configuration.getHostAndPort(), options); this.configuration = configuration; this.driverClient = new com.mongodb.MongoClient( new ServerAddress( configuration.getHostAndPort().getHostText(), configuration.getHostAndPort().getPort()), credentials, options ); version = calculateVersion(); codecRegistry = CodecRegistries.fromCodecs(new DocumentCodec()); closed = false; } catch (com.mongodb.MongoException ex) { throw new UnreachableMongoServerException(configuration.getHostAndPort(), ex); } }
Example #3
Source File: PersistenceManager.java From clouditor with Apache License 2.0 | 6 votes |
private PersistenceManager() { var factory = new BsonFactory(); var module = new SimpleModule(); // the default Jackson Java 8 time (de)serializer are not compatible with MongoDB module.addSerializer(Instant.class, new BsonInstantSerializer()); module.addDeserializer(Instant.class, new BsonInstantDeserializer()); var mapper = new ObjectMapper(factory); ObjectMapperResolver.configureObjectMapper(mapper); mapper.registerModule(module); this.codecRegistry = CodecRegistries.fromRegistries( MongoClient.getDefaultCodecRegistry(), fromProviders(new JacksonCodecProvider(mapper))); }
Example #4
Source File: ElasticBulkService.java From mongolastic with MIT License | 6 votes |
/** * Customizations for the document.toJson output. * <p> * http://mongodb.github.io/mongo-java-driver/3.0/bson/codecs/ * * @return the toJson encoder. */ private Encoder<Document> getEncoder() { ArrayList<Codec<?>> codecs = new ArrayList<>(); if (config.getElastic().getDateFormat() != null) { // Replace default DateCodec class to use the custom date formatter. codecs.add(new CustomDateCodec(config.getElastic().getDateFormat())); } if (config.getElastic().getLongToString()) { // Replace default LongCodec class codecs.add(new CustomLongCodec()); } if (codecs.size() > 0) { BsonTypeClassMap bsonTypeClassMap = new BsonTypeClassMap(); CodecRegistry codecRegistry = CodecRegistries.fromRegistries( CodecRegistries.fromCodecs(codecs), MongoClient.getDefaultCodecRegistry()); return new DocumentCodec(codecRegistry, bsonTypeClassMap); } else { return new DocumentCodec(); } }
Example #5
Source File: EntityCodecs.java From core-ng-project with Apache License 2.0 | 5 votes |
@SuppressWarnings({"unchecked", "rawtypes"}) CodecRegistry codecRegistry() { List<Codec<?>> codecs = new ArrayList<>(this.codecs.values()); codecs.add(new LocalDateTimeCodec()); codecs.add(new ZonedDateTimeCodec()); for (Class<? extends Enum<?>> enumClass : enumClasses) { codecs.add(new EnumCodec(enumClass)); } return CodecRegistries.fromCodecs(codecs); }
Example #6
Source File: BsonModule.java From immutables with Apache License 2.0 | 5 votes |
private static CodecRegistry defaultRegistry() { CodecRegistry standard = CodecRegistries.fromProviders( new BsonValueCodecProvider(), new Jsr310CodecProvider()); // avoid codecs for String / Long / Boolean etc. They're already handled by jackson // choose the ones which need to be serialized in non-JSON format (BSON) CodecRegistry others = CodecRegistries.fromCodecs(new ObjectIdCodec(), new DateCodec(), new UuidCodec(), new Decimal128Codec(), new PatternCodec(), new BigDecimalCodec(), new ByteArrayCodec()); return CodecRegistries.fromRegistries(standard, others); }
Example #7
Source File: JavaTimeTest.java From immutables with Apache License 2.0 | 5 votes |
@Before public void setUp() { CodecRegistry registry = CodecRegistries.fromProviders(new Jsr310CodecProvider()); TypeAdapterFactory factory = GsonCodecs.delegatingTypeAdapterFactory(registry); TypeAdapter<Date> dateTypeAdapter = GsonCodecs.typeAdapterFromCodec(new DateCodec()); gson = new GsonBuilder().registerTypeAdapter(Date.class, dateTypeAdapter).registerTypeAdapterFactory(factory).create(); }
Example #8
Source File: BsonCodecRepoTest.java From immutables with Apache License 2.0 | 5 votes |
@Test public void basic() { LocalCodec codecAndStrategy = new LocalCodec(); CodecRegistry registry = CodecRegistries.fromRegistries(codecAndStrategy, MongoClient.getDefaultCodecRegistry()); RepositorySetup.FieldNamingStrategy strategy = new RepositorySetup.FieldNamingStrategy() { @Override public String translateName(Member member) { return "date".equals(member.getName()) ? "dateChanged" : member.getName(); } }; RepositorySetup setup = RepositorySetup.builder() .executor(MoreExecutors.newDirectExecutorService()) .database(context.database()) .codecRegistry(registry, strategy) .build(); SomebodyRepository repository = new SomebodyRepository(setup); ImmutableSomebody somebody = ImmutableSomebody.builder().id(new ObjectId()).date(new Date()).prop1("prop1").build(); repository.insert(somebody) .getUnchecked(); check(repository.findById(somebody.id()).fetchAll().getUnchecked()).hasAll(somebody); check(repository.find(repository.criteria().prop1(somebody.prop1())).fetchAll().getUnchecked()).hasAll(somebody); check(repository.find(repository.criteria().prop1("unknown")).fetchAll().getUnchecked()).isEmpty(); check(repository.find(repository.criteria().date(somebody.date())).fetchAll().getUnchecked()).hasAll(somebody); check(repository.find(repository.criteria().date(new Date(somebody.date().getTime() + 1))) .fetchAll().getUnchecked()).isEmpty(); }
Example #9
Source File: MongoStorageAdapter.java From Prism with MIT License | 5 votes |
/** * Establish connections to the database * * @return Whether we could connect properly */ @Override public boolean connect() throws Exception { ServerAddress address = new ServerAddress(Prism.getInstance().getConfig().getStorageCategory().getAddress(), ServerAddress.defaultPort()); MongoCredential credential = MongoCredential.createCredential( Prism.getInstance().getConfig().getStorageCategory().getUsername(), databaseName, Prism.getInstance().getConfig().getStorageCategory().getPassword().toCharArray() ); CodecRegistry codecRegistry = CodecRegistries.fromRegistries( MongoClient.getDefaultCodecRegistry(), CodecRegistries.fromCodecs(new PrimitiveArrayCodec()) ); mongoClient = new MongoClient(address, credential, MongoClientOptions.builder().codecRegistry(codecRegistry).build()); // @todo support auth: boolean auth = db.authenticate(myUserName, myPassword); // Connect to the database database = mongoClient.getDatabase(databaseName); // Create indexes try { getCollection(collectionEventRecordsName).createIndex( new Document("Location.X", 1).append("Location.Z", 1).append("Location.Y", 1).append("Created", -1)); getCollection(collectionEventRecordsName).createIndex(new Document("Created", -1).append("EventName", 1)); // TTL IndexOptions options = new IndexOptions().expireAfter(0L, TimeUnit.SECONDS); getCollection(collectionEventRecordsName).createIndex(new Document("Expires", 1), options); return true; } catch (Exception e) { e.printStackTrace(); return false; } }
Example #10
Source File: AbstractMongoIT.java From mongo-mapper with Apache License 2.0 | 5 votes |
@Before public void setUp() throws Exception { CodecRegistry codecRegistry = CodecRegistries.fromProviders(MongoMapper.getProviders()); MongoClientOptions settings = MongoClientOptions.builder().codecRegistry(codecRegistry).build(); String port = System.getProperty("embedMongoPort"); Assert.assertNotNull("Please, set system property 'embedMongoPort' to run this test outside Maven.", port); client = new MongoClient(new ServerAddress("127.0.0.1", Integer.parseInt(port)), settings); dbName = "mapper_test" + UUID.randomUUID(); db = client.getDatabase(dbName); }
Example #11
Source File: EntityCodec.java From mongo-mapper with Apache License 2.0 | 5 votes |
public EntityCodec(Class<T> clazz, EntityInfo info) { this.clazz = clazz; this.info = info; idGenerator = Assertions.notNull("idGenerator", new ObjectIdGenerator()); registry = CodecRegistries.fromProviders(MongoMapper.getProviders()); documentCodec = new DocumentCodec(registry, new BsonTypeClassMap()); bsonTypeClassMap = new BsonTypeClassMap(); }
Example #12
Source File: SharedFongoResource.java From baleen with Apache License 2.0 | 5 votes |
@Override protected boolean doInitialize( ResourceSpecifier aSpecifier, Map<String, Object> aAdditionalParams) throws ResourceInitializationException { // Work whether it's a list of DB Objects or a single if ("{}".equals(fongoData) || "[]".equals(fongoData) || Strings.isNullOrEmpty(fongoData)) { return true; } if (fongoData.trim().startsWith("[")) { CodecRegistry codecRegistry = CodecRegistries.fromProviders( Arrays.asList( new ValueCodecProvider(), new BsonValueCodecProvider(), new DocumentCodecProvider())); JsonReader reader = new JsonReader(fongoData); BsonArrayCodec arrayReader = new BsonArrayCodec(codecRegistry); BsonArray docArray = arrayReader.decode(reader, DecoderContext.builder().build()); for (BsonValue doc : docArray.getValues()) { fongo .getDatabase(BALEEN) .getCollection(fongoCollection) .insertOne(Document.parse(doc.asDocument().toJson())); } } else if (fongoData.trim().startsWith("{")) { Document data = Document.parse(fongoData); fongo.getDatabase(BALEEN).getCollection(fongoCollection).insertOne(data); } else { getMonitor().error("Unsupported type"); throw new ResourceInitializationException(); } return true; }
Example #13
Source File: ReactiveMongoNativeJavaDriverQueryExecutor.java From mongodb-aggregate-query-support with Apache License 2.0 | 5 votes |
private <T> Flux<T> adaptPipeline(QueryProvider queryProvider, Class<T> outputClass, Flux<Document> retval) { String key = queryProvider.getQueryResultKey(); return retval.flatMapIterable(d -> getNestedDocumentList(key, d)) .map(d -> d.toBsonDocument(Document.class, CodecRegistries.fromCodecs(new DocumentCodec()))) .map((d) -> deserialize(outputClass, d)) .doOnError(e -> LOGGER.error("Exception extracting results from document for key {}/output class {}", key, outputClass, e)); }
Example #14
Source File: ReactiveMongoNativeJavaDriverQueryExecutor.java From mongodb-aggregate-query-support with Apache License 2.0 | 5 votes |
private <T> Mono<T> adaptPipeline(QueryProvider queryProvider, Class<T> outputClass, Mono<Document> retval) { String key = queryProvider.getQueryResultKey(); if (BeanUtils.isSimpleValueType(outputClass)) { return retval.map(d -> d.get(key, outputClass)) .doOnError(e -> LOGGER.error("Exception while extracting results from document for key {}", key, e)); } return retval.map(d -> (Document) getDocumentForKey(key, d, false)) .map(d -> d.toBsonDocument(Document.class, CodecRegistries.fromCodecs(new DocumentCodec()))) .map((d) -> deserialize(outputClass, d)) .doOnError(e -> LOGGER.error("Exception while extracting results from document for key {}", key, e)); }
Example #15
Source File: StitchObjectMapper.java From stitch-android-sdk with Apache License 2.0 | 5 votes |
/** * Applies the given codec registry to be used alongside the default codec registry. * * @param codecRegistry the codec registry to merge in. * @return an {@link StitchObjectMapper} with the merged codec registries. */ public StitchObjectMapper withCodecRegistry(final CodecRegistry codecRegistry) { // We can't detect if their codecRegistry has any duplicate providers. There's also a chance // that putting ours first may prevent decoding of some of their classes if for example they // have their own way of decoding an Integer. final CodecRegistry newReg = CodecRegistries.fromRegistries(BsonUtils.DEFAULT_CODEC_REGISTRY, codecRegistry); return new StitchObjectMapper(this, newReg); }
Example #16
Source File: StitchClientConfiguration.java From stitch-android-sdk with Apache License 2.0 | 5 votes |
/** * Merges the provided codec registry with the default codec registry. * * @param codecRegistry the codec registry to merge with the default registry. * @return the builder. */ public Builder withCodecRegistry(final CodecRegistry codecRegistry) { // We can't detect if their codecRegistry has any duplicate providers. There's also a chance // that putting ours first may prevent decoding of some of their classes if for example they // have their own way of decoding an Integer. this.codecRegistry = CodecRegistries.fromRegistries(BsonUtils.DEFAULT_CODEC_REGISTRY, codecRegistry); return this; }
Example #17
Source File: CoreRemoteMongoCollectionUnitTests.java From stitch-android-sdk with Apache License 2.0 | 5 votes |
@Test public void testWithCodecRegistry() { final CoreRemoteMongoCollection<Document> coll1 = getCollection(); final CodecRegistry myReg = CodecRegistries.fromRegistries(BsonUtils.DEFAULT_CODEC_REGISTRY); final CoreRemoteMongoCollection<Document> coll2 = coll1.withCodecRegistry(myReg); assertEquals(myReg, coll2.getCodecRegistry()); assertNotEquals(myReg, coll1.getCodecRegistry()); }
Example #18
Source File: DataSynchronizer.java From stitch-android-sdk with Apache License 2.0 | 5 votes |
private void initialize() { this.configDb = localClient.getDatabase("sync_config" + instanceKey) .withCodecRegistry(CodecRegistries.fromRegistries( CodecRegistries.fromCodecs( InstanceSynchronizationConfig.configCodec, NamespaceSynchronizationConfig.configCodec, CoreDocumentSynchronizationConfig.configCodec), BsonUtils.DEFAULT_CODEC_REGISTRY)); this.instancesColl = configDb .getCollection("instances", InstanceSynchronizationConfig.class); if (instancesColl.countDocuments() == 0) { this.syncConfig = new InstanceSynchronizationConfig(configDb); instancesColl.insertOne(this.syncConfig); } else { if (instancesColl.find().first() == null) { throw new IllegalStateException("expected to find instance configuration"); } this.syncConfig = new InstanceSynchronizationConfig(configDb); } this.instanceChangeStreamListener = new InstanceChangeStreamListenerImpl( syncConfig, service, networkMonitor, authMonitor); for (final MongoNamespace ns : this.syncConfig.getSynchronizedNamespaces()) { this.instanceChangeStreamListener.addNamespace(ns); } }
Example #19
Source File: MongoImpl.java From core-ng-project with Apache License 2.0 | 4 votes |
public void initialize() { registry = CodecRegistries.fromRegistries(MongoClientSettings.getDefaultCodecRegistry(), codecs.codecRegistry()); database = createDatabase(registry); }
Example #20
Source File: CoreStitchAuthUnitTests.java From stitch-android-sdk with Apache License 2.0 | 4 votes |
@Test public void testDoAuthenticatedRequestWithCustomCodecRegistry() { final StitchRequestClient requestClient = getMockedRequestClient(); final StitchAuthRoutes routes = new StitchAppRoutes("my_app-12345").getAuthRoutes(); final StitchAuth auth = new StitchAuth( requestClient, routes, new MemoryStorage()); final CodecRegistry registry = CodecRegistries.fromRegistries( BsonUtils.DEFAULT_CODEC_REGISTRY, CodecRegistries.fromCodecs(new CustomType.Codec())); auth.loginWithCredentialInternal(new AnonymousCredential()); final StitchAuthDocRequest.Builder reqBuilder = new StitchAuthDocRequest.Builder(); reqBuilder.withPath("giveMeData"); reqBuilder.withDocument(new Document()); reqBuilder.withMethod(Method.POST); final String rawInt = "{\"$numberInt\": \"42\"}"; // Check that primitive return types can be decoded. doReturn(new Response(rawInt)).when(requestClient).doRequest(any(StitchRequest.class)); assertEquals(42, (int) auth.doAuthenticatedRequest( reqBuilder.build(), Integer.class, registry)); doReturn(new Response(rawInt)).when(requestClient).doRequest(any(StitchRequest.class)); assertEquals(42, (int) auth.doAuthenticatedRequest( reqBuilder.build(), new IntegerCodec())); final ObjectId expectedObjectId = new ObjectId(); final String docRaw = String.format( "{\"_id\": {\"$oid\": \"%s\"}, \"intValue\": {\"$numberInt\": \"42\"}}", expectedObjectId.toHexString()); // Check that BSON documents returned as extended JSON can be decoded into BSON // documents. doReturn(new Response(docRaw)).when(requestClient).doRequest(any(StitchRequest.class)); Document doc = auth.doAuthenticatedRequest(reqBuilder.build(), Document.class, registry); assertEquals(expectedObjectId, doc.getObjectId("_id")); assertEquals(42, (int) doc.getInteger("intValue")); doReturn(new Response(docRaw)).when(requestClient).doRequest(any(StitchRequest.class)); doc = auth.doAuthenticatedRequest(reqBuilder.build(), new DocumentCodec()); assertEquals(expectedObjectId, doc.getObjectId("_id")); assertEquals(42, (int) doc.getInteger("intValue")); // Check that a custom type can be decoded without providing a codec, as long as that codec // is registered in the CoreStitchAuth's configuration. doReturn(new Response(docRaw)).when(requestClient).doRequest(any(StitchRequest.class)); final CustomType ct = auth.doAuthenticatedRequest( reqBuilder.build(), CustomType.class, registry); assertEquals(expectedObjectId, ct.getId()); assertEquals(42, ct.getIntValue()); }
Example #21
Source File: BsonUtils.java From stitch-android-sdk with Apache License 2.0 | 4 votes |
public static <T> BsonDocument documentToBsonDocument( final T document, final Codec<T> codec ) { return documentToBsonDocument(document, CodecRegistries.fromCodecs(codec)); }
Example #22
Source File: MongoClientOptionsParser.java From vertx-mongo-client with Apache License 2.0 | 4 votes |
public MongoClientOptionsParser(Vertx vertx, JsonObject config) { Objects.requireNonNull(config); MongoClientSettings.Builder options = MongoClientSettings.builder(); options.codecRegistry(CodecRegistries.fromRegistries(commonCodecRegistry, CodecRegistries.fromCodecs(new JsonObjectCodec(config)))); // All parsers should support connection_string first String cs = config.getString("connection_string"); ConnectionString connectionString = (cs == null) ? null : new ConnectionString(cs); String csDatabase = (connectionString != null) ? connectionString.getDatabase() : null; this.database = csDatabase != null ? csDatabase : config.getString("db_name", MongoClient.DEFAULT_DB_NAME); // ClusterSettings ClusterSettings clusterSettings = new ClusterSettingsParser(connectionString, config).settings(); options.applyToClusterSettings(builder -> builder.applySettings(clusterSettings)); // ConnectionPoolSettings ConnectionPoolSettings connectionPoolSettings = new ConnectionPoolSettingsParser(connectionString, config).settings(); options.applyToConnectionPoolSettings(builder -> builder.applySettings(connectionPoolSettings)); // Credentials // The previous mongo client supported credentials list but their new implementation supports only // one credentials. The deprecated code path resorts to using the last credentials if a list is passed // we are doing the same here. List<MongoCredential> credentials = new CredentialListParser(config).credentials(); if (!credentials.isEmpty()) options.credential(credentials.get(credentials.size() - 1)); // SocketSettings SocketSettings socketSettings = new SocketSettingsParser(connectionString, config).settings(); options.applyToSocketSettings(builder -> builder.applySettings(socketSettings)); // Transport type new StreamTypeParser(config).streamFactory().ifPresent(options::streamFactoryFactory); // SSLSettings SslSettings sslSettings = new SSLSettingsParser(connectionString, config).settings(vertx); options.applyToSslSettings(builder -> builder.applySettings(sslSettings)); // WriteConcern WriteConcern writeConcern = new WriteConcernParser(connectionString, config).writeConcern(); if (writeConcern != null) { options.writeConcern(writeConcern); } // ReadConcern maybeReadConcern(connectionString, config).ifPresent(options::readConcern); // ReadPreference ReadPreference readPreference = new ReadPreferenceParser(connectionString, config).readPreference(); if (readPreference != null) { options.readPreference(readPreference); } // ServerSettings ServerSettings serverSettings = new ServerSettingsParser(config).settings(); options.applyToServerSettings(builder -> builder.applySettings(serverSettings)); this.settings = options.build(); }
Example #23
Source File: TestMongoClient.java From jframe with Apache License 2.0 | 4 votes |
public void testDriverStatus() { CodecRegistry codecRegistry = CodecRegistries.fromRegistries( CodecRegistries.fromCodecs(new UuidCodec( UuidRepresentation.STANDARD)), MongoClient .getDefaultCodecRegistry()); mongoClient.getDatabase("lech_rent").drop(); MongoDatabase rent = mongoClient.getDatabase("lech_rent") .withCodecRegistry(codecRegistry); // rent.createCollection("driver_status", new CreateCollectionOptions() // .capped(true).sizeInBytes(0x100000)); MongoCollection<Document> status = rent.getCollection("driver_status"); status.deleteMany(Filters.eq("mobile", "18616020610")); if (status.count() == 0) { } status.createIndex(new Document("mobile", "text")); // status.createIndex(new Document("no", "text")); for (final Document index : status.listIndexes()) { System.out.println(index.toJson()); } Document doc = new Document("loc", new Document("type", "Point").append("coordinates", Arrays.asList(-73.97, 40.77))).append("no", "dno") .append("usrImg", "/usr/driver.png") .append("mobile", "18616020610").append("status", 7) .append("car", new Document("no", "A00001")); status.insertOne(doc); // status.createIndex(keys); doc = status.find(Filters.eq("mobile", "18616020610")).first(); System.out.println(doc.get("loc", Document.class).get("coordinates")); System.out.println(doc.get("loc", Document.class).get("coordinates", ArrayList.class)); System.out.println(doc.get("car", Document.class)); // System.out.println(doc.get("loc", Document.class)); // UpdateResult updateResult = status.updateOne(Filters.eq("mobile", // "18616020610"), new Document("$set", new Document("car", // new Document("no", "A00002")))); doc = status.find(Filters.eq("mobile", "18616020610")).first(); System.out.println(doc.get("car", Document.class)); // updateResult = status.updateMany(Filters.lt("i", 100), new Document( // "$inc", new Document("i", 100))); // System.out.println(updateResult.getModifiedCount()); // DeleteResult deleteResult = status.deleteOne(Filters.eq("i", 110)); // System.out.println(deleteResult.getDeletedCount()); // 2. Ordered bulk operation - order is guarenteed // status.bulkWrite(Arrays.asList(new InsertOneModel<>(new // Document("_id", // 4)), new InsertOneModel<>(new Document("_id", 5)), // new InsertOneModel<>(new Document("_id", 6)), // new UpdateOneModel<>(new Document("_id", 1), new Document( // "$set", new Document("x", 2))), new DeleteOneModel<>( // new Document("_id", 2)), // new ReplaceOneModel<>(new Document("_id", 3), new Document( // "_id", 3).append("x", 4)))); // 2. Unordered bulk operation - no guarantee of order of operation // status.bulkWrite(Arrays.asList(new InsertOneModel<>(new // Document("_id", // 4)), new InsertOneModel<>(new Document("_id", 5)), // new InsertOneModel<>(new Document("_id", 6)), // new UpdateOneModel<>(new Document("_id", 1), new Document( // "$set", new Document("x", 2))), new DeleteOneModel<>( // new Document("_id", 2)), // new ReplaceOneModel<>(new Document("_id", 3), new Document( // "_id", 3).append("x", 4))), new BulkWriteOptions() // .ordered(false)); }
Example #24
Source File: JacksonCodecs.java From immutables with Apache License 2.0 | 4 votes |
/** * Create {@link CodecRegistry} adapter on the top of existing mapper instance */ public static CodecRegistry registryFromMapper(final ObjectMapper mapper) { Objects.requireNonNull(mapper, "mapper"); return CodecRegistries.fromRegistries(new NativeCodecRegistry(mapper), JacksonCodecRegistry.of(mapper)); }
Example #25
Source File: JacksonCodecs.java From immutables with Apache License 2.0 | 4 votes |
/** * Create module from existing provider */ public static Module module(CodecProvider provider) { return module(CodecRegistries.fromProviders(provider)); }
Example #26
Source File: TodoListActivity.java From stitch-android-sdk with Apache License 2.0 | 4 votes |
@Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_todo_list); // Set up Stitch and local MongoDB mobile client final StitchAppClient client = Stitch.getDefaultAppClient(); final RemoteMongoClient mongoClient = client.getServiceClient( RemoteMongoClient.factory, "mongodb-atlas"); // Set up collections items = mongoClient .getDatabase(TodoItem.TODO_LIST_DATABASE) .getCollection(TodoItem.TODO_LIST_COLLECTION, TodoItem.class) .withCodecRegistry(CodecRegistries.fromRegistries( BsonUtils.DEFAULT_CODEC_REGISTRY, CodecRegistries.fromCodecs(TodoItem.codec))); lists = mongoClient .getDatabase(TODO_LISTS_DATABASE) .getCollection(TODO_LISTS_COLLECTION); // Configure sync to be remote wins on both collections meaning and conflict that occurs should // prefer the remote version as the resolution. final SyncConfiguration syncConfig = new SyncConfiguration.Builder() .withConflictHandler(DefaultSyncConflictResolvers.remoteWins()) .withChangeEventListener(itemUpdateListener) .withExceptionListener((documentId, error) -> Log.e(TAG, error.getLocalizedMessage())) .build(); items.sync().configure(syncConfig); lists.sync().configure(syncConfig); // Set up recycler view for to-do items final RecyclerView todoRecyclerView = findViewById(R.id.rv_todo_items); final RecyclerView.LayoutManager todoLayoutManager = new LinearLayoutManager(this); todoRecyclerView.setLayoutManager(todoLayoutManager); // Set up adapter todoAdapter = new TodoAdapter( new ArrayList<>(), new TodoAdapter.ItemUpdater() { @Override public void updateChecked(final ObjectId itemId, final boolean isChecked) { final Document updateDoc = new Document("$set", new Document(TodoItem.Fields.CHECKED, isChecked)); if (isChecked) { updateDoc.append("$currentDate", new Document(TodoItem.Fields.DONE_DATE, true)); } else { updateDoc.append("$unset", new Document(TodoItem.Fields.DONE_DATE, "")); } items.sync().updateOne(new Document("_id", itemId), updateDoc); } @Override public void updateTask(final ObjectId itemId, final String currentTask) { showEditItemDialog(itemId, currentTask); } }); todoRecyclerView.setAdapter(todoAdapter); // Start with the current local items todoAdapter.replaceItems(getItems(), false); doLogin(); }
Example #27
Source File: BsonUtils.java From stitch-android-sdk with Apache License 2.0 | 3 votes |
/** * Parses the provided extended JSON string and decodes it into a T value as specified by the * provided class type. The type will decoded using the codec found for the type in the provided * codec registry. If the provided type is not supported by the provided codec registry, the * method will throw a {@link org.bson.codecs.configuration.CodecConfigurationException}. * * @param json the JSON string to parse. * @param valueClass the class that the JSON string should be decoded into. * @param codecRegistry the codec registry to use to find the codec for the provided class. * @param <T> the type into which the JSON string is decoded. * @return the decoded value. */ public static <T> T parseValue( final String json, final Class<T> valueClass, final CodecRegistry codecRegistry) { final JsonReader bsonReader = new JsonReader(json); bsonReader.readBsonType(); // We can't detect if their codecRegistry has any duplicate providers. There's also a chance // that putting ours first may prevent decoding of some of their classes if for example they // have their own way of decoding an Integer. final CodecRegistry newReg = CodecRegistries.fromRegistries(BsonUtils.DEFAULT_CODEC_REGISTRY, codecRegistry); return newReg.get(valueClass).decode(bsonReader, DecoderContext.builder().build()); }