org.bson.codecs.configuration.CodecRegistry Java Examples
The following examples show how to use
org.bson.codecs.configuration.CodecRegistry.
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: MongoCursorIsClosedTest.java From immutables with Apache License 2.0 | 6 votes |
@Before @SuppressWarnings("unchecked") public void setUp() throws Exception { MongoDatabase db = mock(MongoDatabase.class); MongoCollection<Entity> collection = mock(MongoCollection.class); when(db.getCollection(anyString(), any(Class.class))).thenReturn(collection); when(collection.withCodecRegistry(any(CodecRegistry.class))).thenReturn(collection); RepositorySetup setup = RepositorySetup.builder().database(db) .executor(MoreExecutors.newDirectExecutorService()) .gson(new GsonBuilder().registerTypeAdapterFactory(new GsonAdaptersEntity()).create()) .build(); this.repository = new EntityRepository(setup); FindIterable<Entity> iterable = mock(FindIterable.class); when(collection.find(any(Bson.class))).thenReturn(iterable); MongoCursor<Entity> cursor = mock(MongoCursor.class); when(iterable.iterator()).thenReturn(cursor); this.cursor = cursor; }
Example #2
Source File: EntityDecoder.java From morphia with Apache License 2.0 | 6 votes |
@SuppressWarnings("unchecked") protected Codec<T> getCodecFromDocument(final BsonReader reader, final boolean useDiscriminator, final String discriminatorKey, final CodecRegistry registry, final DiscriminatorLookup discriminatorLookup, final Codec<T> defaultCodec) { Codec<T> codec = null; if (useDiscriminator) { BsonReaderMark mark = reader.getMark(); try { reader.readStartDocument(); while (codec == null && reader.readBsonType() != BsonType.END_OF_DOCUMENT) { if (discriminatorKey.equals(reader.readName())) { codec = (Codec<T>) registry.get(discriminatorLookup.lookup(reader.readString())); } else { reader.skipValue(); } } } catch (Exception e) { throw new CodecConfigurationException(String.format("Failed to decode '%s'. Decoding errored with: %s", morphiaCodec.getEntityModel().getName(), e.getMessage()), e); } finally { mark.reset(); } } return codec != null ? codec : defaultCodec; }
Example #3
Source File: Mapper.java From morphia with Apache License 2.0 | 6 votes |
/** * Converts a Document back to a type-safe java object (POJO) * * @param <T> the type of the entity * @param type the target type * @param document the Document containing the document from mongodb * @return the new entity * @morphia.internal */ public <T> T fromDocument(final Class<T> type, final Document document) { if (document == null) { return null; } Class<T> aClass = type; if (document.containsKey(options.getDiscriminatorKey())) { aClass = getClass(document); } CodecRegistry codecRegistry = getCodecRegistry(); DocumentReader reader = new DocumentReader(document); return codecRegistry .get(aClass) .decode(reader, DecoderContext.builder().build()); }
Example #4
Source File: DataSynchronizer.java From stitch-android-sdk with Apache License 2.0 | 6 votes |
public <T> T findOne( final MongoNamespace namespace, final BsonDocument filter, final BsonDocument projection, final BsonDocument sort, final Class<T> resultClass, final CodecRegistry codecRegistry ) { this.waitUntilInitialized(); ongoingOperationsGroup.enter(); final Lock lock = this.syncConfig.getNamespaceConfig(namespace).getLock().writeLock(); lock.lock(); try { return getLocalCollection(namespace, resultClass, codecRegistry) .find(filter) .limit(1) .projection(projection) .sort(sort) .first(); } finally { lock.unlock(); ongoingOperationsGroup.exit(); } }
Example #5
Source File: MorphiaCodecProvider.java From morphia with Apache License 2.0 | 6 votes |
/** * Creates a codec that uses an existing entity for loading rather than creating a new instance. * * @param entity the entity to refresh * @param registry the codec registry * @param <T> the entity type * @return the new codec */ @SuppressWarnings("unchecked") public <T> Codec<T> getRefreshCodec(final T entity, final CodecRegistry registry) { MappedClass mappedClass = mapper.getMappedClass(entity.getClass()); return new MorphiaCodec<T>(datastore, mappedClass, propertyCodecProviders, mapper.getDiscriminatorLookup(), registry) { @Override protected EntityDecoder<T> getDecoder() { return new EntityDecoder<>(this) { @Override protected MorphiaInstanceCreator<T> getInstanceCreator(final EntityModel<T> classModel) { return new MorphiaInstanceCreator<>() { @Override public T getInstance() { return entity; } @Override public <S> void set(final S value, final FieldModel<S> model) { model.getAccessor().set(getInstance(), value); } }; } }; } }; }
Example #6
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 #7
Source File: JacksonCodec.java From mongo-jackson-codec with Apache License 2.0 | 5 votes |
public JacksonCodec(ObjectMapper bsonObjectMapper, CodecRegistry codecRegistry, Class<T> type) { this.bsonObjectMapper = bsonObjectMapper; this.rawBsonDocumentCodec = codecRegistry.get(RawBsonDocument.class); this.type = type; }
Example #8
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 #9
Source File: CoreStitchServiceClientImpl.java From stitch-android-sdk with Apache License 2.0 | 5 votes |
public <T> T callFunction( final String name, final List<?> args, final Class<T> resultClass, final CodecRegistry codecRegistry) { return requestClient.doAuthenticatedRequest( getCallServiceFunctionRequest(name, args, null), resultClass, codecRegistry); }
Example #10
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 #11
Source File: BsonUtils.java From stitch-android-sdk with Apache License 2.0 | 5 votes |
public static <T> BsonDocument toBsonDocumentOrNull( final Bson document, final Class<T> documentClass, final CodecRegistry codecRegistry ) { return document == null ? null : document.toBsonDocument(documentClass, codecRegistry); }
Example #12
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 #13
Source File: UnitTestEmbeddedMongoClientFactory.java From stitch-android-sdk with Apache License 2.0 | 5 votes |
@Override protected MongoClient createClient(final String dbPath, final CodecRegistry codecRegistry) { return MongoClients.create(MongoClientSettings.builder() .dbPath(dbPath) .codecRegistry(codecRegistry) .build()); }
Example #14
Source File: JacksonCodecsTest.java From immutables with Apache License 2.0 | 5 votes |
@SuppressWarnings("unchecked") private static <T> T writeThenRead(CodecRegistry registry, ObjectMapper mapper, T value) throws IOException { BasicOutputBuffer buffer = new BasicOutputBuffer(); BsonWriter writer = new BsonBinaryWriter(buffer); registry.get((Class<T>) value.getClass()).encode(writer, value, EncoderContext.builder().build()); BsonBinaryReader reader = new BsonBinaryReader(ByteBuffer.wrap(buffer.toByteArray())); IOContext ioContext = new IOContext(new BufferRecycler(), null, false); BsonParser parser = new BsonParser(ioContext, 0, reader); return mapper.readValue(parser, (Class<T>) value.getClass()); }
Example #15
Source File: MongoImpl.java From core-ng-project with Apache License 2.0 | 5 votes |
private MongoDatabase createDatabase(CodecRegistry registry) { if (uri == null) throw new Error("uri must not be null"); String database = uri.getDatabase(); if (database == null) throw new Error("uri must have database, uri=" + uri); var watch = new StopWatch(); try { connectionPoolSettings.maxWaitTime(timeoutInMs, TimeUnit.MILLISECONDS); // pool checkout timeout var socketSettings = SocketSettings.builder() .connectTimeout((int) timeoutInMs, TimeUnit.MILLISECONDS) .readTimeout((int) timeoutInMs, TimeUnit.MILLISECONDS) .build(); var clusterSettings = ClusterSettings.builder() .serverSelectionTimeout(timeoutInMs * 3, TimeUnit.MILLISECONDS) // able to try 3 servers .build(); var settings = MongoClientSettings.builder() .applicationName(LogManager.APP_NAME) .codecRegistry(registry) .applyToConnectionPoolSettings(builder -> builder.applySettings(connectionPoolSettings.build())) .applyToSocketSettings(builder -> builder.applySettings(socketSettings)) .applyToClusterSettings(builder -> builder.applySettings(clusterSettings)) .applyConnectionString(uri) .build(); mongoClient = MongoClients.create(settings); return mongoClient.getDatabase(database); } finally { logger.info("create mongo client, uri={}, elapsed={}", uri, watch.elapsed()); } }
Example #16
Source File: CoreStitchServiceClientImpl.java From stitch-android-sdk with Apache License 2.0 | 5 votes |
public <T> T callFunction( final String name, final List<?> args, final @Nullable Long requestTimeout, final Class<T> resultClass, final CodecRegistry codecRegistry) { return requestClient.doAuthenticatedRequest( getCallServiceFunctionRequest(name, args, requestTimeout), resultClass, codecRegistry); }
Example #17
Source File: JacksonCodecsTest.java From immutables with Apache License 2.0 | 5 votes |
/** * Reading directly {@link Document} */ @Test public void document() throws IOException { final CodecRegistry registry = JacksonCodecs.registryFromMapper(mapper); Document expected = new Document("a", 1); Document actual= registry.get(Document.class).decode(new BsonDocumentReader(expected.toBsonDocument(BsonDocument.class, registry)), DecoderContext.builder().build()); check(actual).is(expected); }
Example #18
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 #19
Source File: StitchServiceClientImpl.java From stitch-android-sdk with Apache License 2.0 | 5 votes |
@Override public <ResultT> Task<ResultT> callFunction( final String name, final List<?> args, final Class<ResultT> resultClass, final CodecRegistry codecRegistry) { return dispatcher.dispatchTask( new Callable<ResultT>() { @Override public ResultT call() { return proxy.callFunction(name, args, null, resultClass, codecRegistry); } }); }
Example #20
Source File: MapperCodecProvider.java From mongo-mapper with Apache License 2.0 | 5 votes |
@Override public <T> Codec<T> get(final Class<T> clazz, final CodecRegistry registry) { EntityInfo info = entityMap.get(clazz); // CodecProvider returns null if it's not a provider for the requresed Class. if (info == null) { return null; } // Create codec for given class. return new EntityCodec<>(clazz, info); }
Example #21
Source File: JacksonCodec.java From EDDI with Apache License 2.0 | 5 votes |
public JacksonCodec(ObjectMapper bsonObjectMapper, CodecRegistry codecRegistry, Class<T> type) { this.bsonObjectMapper = bsonObjectMapper; this.rawBsonDocumentCodec = codecRegistry.get(RawBsonDocument.class); this.type = type; }
Example #22
Source File: StitchServiceClientImpl.java From stitch-android-sdk with Apache License 2.0 | 5 votes |
@Override public <ResultT> ResultT callFunction( final String name, final List<?> args, final Class<ResultT> resultClass, final CodecRegistry codecRegistry) { return proxy.callFunction(name, args, null, resultClass, codecRegistry); }
Example #23
Source File: MongoConfig.java From XBDD with Apache License 2.0 | 5 votes |
@Bean public MongoClient legacyMongoClient() { final CodecRegistry pojoCodecRegistry = fromRegistries(MongoClient.getDefaultCodecRegistry(), fromProviders(PojoCodecProvider.builder().automatic(true).build())); final MongoClientOptions options = MongoClientOptions.builder().codecRegistry(pojoCodecRegistry).build(); final MongoCredential credentials = MongoCredential.createScramSha1Credential(this.username, "admin", this.password.toCharArray()); return new MongoClient(new ServerAddress(this.host, NumberUtils.toInt(this.port)), credentials, options); }
Example #24
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 #25
Source File: JacksonCodecs.java From immutables with Apache License 2.0 | 5 votes |
private static <T> Codec<T> findCodecOrNull(CodecRegistry registry, Class<T> type) { try { return registry.get(type); } catch (CodecConfigurationException e) { return null; } }
Example #26
Source File: StitchAppClientImpl.java From stitch-android-sdk with Apache License 2.0 | 5 votes |
@Override public <ResultT> ResultT callFunction( final String name, final List<?> args, final Class<ResultT> resultClass, final CodecRegistry codecRegistry ) { return coreClient.callFunction(name, args, null, resultClass, codecRegistry); }
Example #27
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 #28
Source File: AndroidEmbeddedMongoClientFactory.java From stitch-android-sdk with Apache License 2.0 | 5 votes |
@Override protected MongoClient createClient(final String dbPath, final CodecRegistry codecRegistry) { return MongoClients.create(MongoClientSettings.builder() .dbPath(dbPath) .codecRegistry(codecRegistry) .build()); }
Example #29
Source File: StitchAppClientImpl.java From stitch-android-sdk with Apache License 2.0 | 5 votes |
@Override public <ResultT> Task<ResultT> callFunction( final String name, final List<?> args, final Class<ResultT> resultClass, final CodecRegistry codecRegistry ) { return dispatcher.dispatchTask( new Callable<ResultT>() { @Override public ResultT call() { return coreClient.callFunction(name, args, null, resultClass, codecRegistry); } }); }
Example #30
Source File: CoreStitchServiceClientImpl.java From stitch-android-sdk with Apache License 2.0 | 5 votes |
public CoreStitchServiceClientImpl( final StitchAuthRequestClient requestClient, final StitchServiceRoutes routes, final String name, final CodecRegistry codecRegistry ) { notNull("codecRegistry", codecRegistry); this.requestClient = requestClient; this.serviceRoutes = routes; this.serviceName = name; this.codecRegistry = codecRegistry; this.serviceBinders = new ConcurrentHashMap<>(); this.allocatedStreams = new ConcurrentHashMap<>(); }