Java 类org.bson.codecs.configuration.CodecRegistry 实例源码

项目:polymorphia    文件:CodecResolverTest.java   
@Bean()
public static CodecRegistry getCodecRegistry() {
    return CodecRegistries.fromRegistries(
            CodecRegistries.fromProviders(
                    new EnumCodecProvider(),
                    PojoCodecProvider.builder()
                            .register(CodecResolverTest.class)
                            .registerCodecResolver((CodecResolver) (type, typeCodecRegistry, codecConfiguration) -> {
                                if (TypeUtils.isAssignable(type, Base.class)) {
                                    return new DocumentCodec((Class<? extends Base>) type, typeCodecRegistry, codecConfiguration);
                                }
                                return null;
                            })
                            .build()
            ),
            MongoClient.getDefaultCodecRegistry());
}
项目:GitHub    文件:Repositories.java   
protected Repository(
    RepositorySetup configuration,
    String collectionName,
    Class<T> type) {

  this.configuration = checkNotNull(configuration, "configuration");
  checkNotNull(collectionName, "collectionName");
  checkNotNull(type, "type");

  final TypeAdapter<T> adapter = checkAdapter(configuration.gson.getAdapter(type), type);
  final MongoCollection<Document> collection = configuration.database.getCollection(collectionName);
  // combine default and immutables codec registries
  final CodecRegistry registry = CodecRegistries.fromRegistries(collection.getCodecRegistry(), BsonEncoding.registryFor(type, adapter));

  this.collection = collection
      .withCodecRegistry(registry)
      .withDocumentClass(type);
}
项目:GitHub    文件:BsonEncoding.java   
/**
 * "Smart" registry just for this particular {@code type}. It is typically composed with existing
 * registries using {@link org.bson.codecs.configuration.CodecRegistries#fromRegistries(CodecRegistry...)} method.
 */
public static <T> CodecRegistry registryFor(final Class<T> type, final TypeAdapter<T> adapter) {
  return new CodecRegistry() {
    @SuppressWarnings("unchecked")
    @Override
    public <X> Codec<X> get(Class<X> clazz) {
      // TODO is this a safe assumption with polymorphism (in repositories) ?
      if (type.isAssignableFrom(clazz)) {
        return (Codec<X>) codecFor(type, adapter);
      } else {
        // let other registries decide
        throw new CodecConfigurationException(String.format("Type %s not supported by this registry", type.getName()));
      }
    }
  };
}
项目:datatree-adapters    文件:JsonBson.java   
@SuppressWarnings("unchecked")
@Override
public <T> Codec<T> get(Class<T> clazz, CodecRegistry registry) {
    if (clazz == BigDecimal.class) {
        return (Codec<T>) bigDecimalCodec;
    }
    if (clazz == BigInteger.class) {
        return (Codec<T>) bigIntegerCodec;
    }
    if (clazz == InetAddress.class || clazz == Inet4Address.class || clazz == Inet6Address.class) {
        return (Codec<T>) inetAddressCodec;
    }
    if (clazz.isArray()) {
        return (Codec<T>) arrayCodec;
    }
    return null;
}
项目:polymorphia    文件:PojoCodecProvider.java   
@Override
public <T> Codec<T> get(Class<T> clazz, CodecRegistry registry) {
    // if clazz has type parameters, we warn the user that generic class definitions are problematic
    Codec<T> codec = pojoContext.get(clazz, registry);
    if (codec instanceof TypeCodec) {
        if (clazz != null && clazz.getTypeParameters().length > 0) {
            LOGGER.warn("Generic classes will only be encoded/decoded with their upper bounds! " +
                    "We could prohibit handling of the pojo codec for those generic classes, " +
                    "but then user would loose flexibility when subclassing such classes. Class: " + clazz.toGenericString());
        }
        TypeCodec typeCodec = (TypeCodec) codec;
        // generate dynamic proxy to add CollectibleCodec functionality
        if (typeCodec.isCollectible()) {
            LOGGER.debug("Enhancing {} to be collectible codec.", typeCodec);
            Class[] proxyInterfaces = new Class[]{CollectibleCodec.class};
            CollectibleCodec collectibleCodec = (CollectibleCodec) Proxy.newProxyInstance(
                    PojoCodecProvider.class.getClassLoader(),
                    proxyInterfaces,
                    new CollectibleCodecDelegator(typeCodec));

            return collectibleCodec;
        }
    }
    return codec;
}
项目:polymorphia    文件:ExternalIdCodecProviderTest.java   
@Bean()
public static CodecRegistry getCodecRegistry() {
    return CodecRegistries.fromRegistries(
            CodecRegistries.fromProviders(
                    new EnumCodecProvider(),
                    PojoCodecProvider.builder()
                            .register(Pojo.class.getPackage().getName())
                            .registerCodecResolver((CodecResolver) (type, typeCodecRegistry, codecConfiguration) -> {
                                if (TypeUtils.isAssignable(type, CustomId.class)) {
                                    return new CustomIdCodec((Class<CustomId>)type, typeCodecRegistry, codecConfiguration);
                                }
                                return null;
                            }).build()
            ),
            MongoClient.getDefaultCodecRegistry());
}
项目:java-code-gen    文件:ExtraCodecProvider.java   
@SuppressWarnings("unchecked")
@Override
public <T> Codec<T> get(Class<T> clazz, CodecRegistry registry) {
    // Optimistic get to avoid using dynamic memory
    Codec<?> ret = codecs.get(clazz);
    if (ret != null) {
        return (Codec<T>) ret;
    }
    if (clazz.isEnum()) {
        return (Codec<T>) codecs.computeIfAbsent(clazz, c -> new EnumCodec<>((Class<? extends Enum>) c));
    }
    if (clazz.isArray()) {
        Class<?> componentType = clazz.getComponentType();
        Codec componentCodec = get(componentType, registry);
        if (componentCodec != null) {
            return (Codec<T>) codecs.computeIfAbsent(clazz, c -> new ArrayCodec(clazz, componentCodec));
        }
    }
    return registry.get(clazz);
}
项目:mongolastic    文件:ElasticBulkService.java   
/**
 * 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();
    }
}
项目:edison-microservice    文件:MongoProperties.java   
public MongoClientOptions toMongoClientOptions(final CodecRegistry codecRegistry) {
    return builder()
            .sslEnabled(sslEnabled)
            .codecRegistry(codecRegistry)
            .readPreference(ReadPreference.valueOf(readPreference))
            .connectTimeout(connectTimeout)
            .serverSelectionTimeout(serverSelectionTimeout)
            .cursorFinalizerEnabled(true)
            .maxWaitTime(maxWaitTime)
            .maxConnectionLifeTime(connectionpool.getMaxLifeTime())
            .threadsAllowedToBlockForConnectionMultiplier(connectionpool.getBlockedConnectionMultiplier())
            .maxConnectionIdleTime(connectionpool.getMaxIdleTime())
            .minConnectionsPerHost(connectionpool.getMinSize())
            .connectionsPerHost(connectionpool.getMaxSize())
            .build();
}
项目:verbum-domini    文件:PersistenceManagerImpl.java   
private CodecRegistry buildCodecRegistries() {
    Codec<Document> defaultDocumentCodec = MongoClient.getDefaultCodecRegistry().get(Document.class);

    CodecRegistry codecRegistry = CodecRegistries.fromRegistries(
        MongoClient.getDefaultCodecRegistry(),
        CodecRegistries.fromCodecs(
            new BibleCodec(defaultDocumentCodec),
            new BookCodec(defaultDocumentCodec),
            new ChapterCodec(defaultDocumentCodec),
            new VerseCodec(defaultDocumentCodec),
            new UserCodec(defaultDocumentCodec)
        )
    );

    return codecRegistry;
}
项目:bsoncodec-apt    文件:UnknownCodecDelegate.java   
@Override
public void addEncodeStatements(TypeMirror type, CodeGeneratorContext ctx) {
    ctx.builder()
            .addStatement("Codec codec = this.registry.get($L.getClass())",
                    ctx.getter())
            .addStatement("encoderContext.encodeWithChildContext(codec, writer, $L)",
                    ctx.getter());

    // ctx.builder()
    // .addAnnotation(AnnotationSpec.builder(SuppressWarnings.class)
    // .addMember("value", "$S", "unchecked")
    // .addMember("value", "$S", "rawtypes").build());

    ctx.instanceFields().add(ImmutableInstanceField.builder()
            .type(ClassName.get(CodecRegistry.class)).name("registry").build());

    ctx.instanceFields()
            .add(ImmutableInstanceField.builder()
                    .type(ClassName.get(BsonTypeClassMap.class))
                    .name("bsonTypeClassMap").build());

}
项目:oap    文件:MongoStorage.java   
@SuppressWarnings( "unchecked" )
public MongoStorage( oap.storage.MongoClient mongoClient, String database, String table,
                     LockStrategy lockStrategy ) {
    super( IdentifierBuilder
        .annotation()
        .suggestion( ar -> ObjectId.get().toString() )
        .size( 24 )
        .idOptions()
        .build(), lockStrategy );
    this.database = mongoClient.getDatabase( database );


    final Object o = new TypeReference<Metadata<T>>() {};
    final CodecRegistry codecRegistry = CodecRegistries.fromRegistries(
        CodecRegistries.fromCodecs( new JsonCodec<>( ( TypeReference<Metadata> ) o,
            Metadata.class, ( m ) -> identifier.get( ( T ) m.object ) ) ),
        this.database.getCodecRegistry()
    );

    final Object metadataMongoCollection = this.database
        .getCollection( table, Metadata.class )
        .withCodecRegistry( codecRegistry );
    this.collection = ( MongoCollection<Metadata<T>> ) metadataMongoCollection;

    load();
}
项目:mongodb-rdbms-sync    文件:SyncConnectionInfo.java   
@Override
public <TDocument> BsonDocument toBsonDocument(Class<TDocument> arg0,
        CodecRegistry codecRegistry) {
    System.out.println("toBsonDocument called");
    return new BsonDocumentWrapper<SyncConnectionInfo>(this,
            codecRegistry.get(SyncConnectionInfo.class));
}
项目:polymorphia    文件:EnumCodecProvider.java   
@Override
public <T> Codec<T> get(Class<T> clazz, CodecRegistry registry) {
    if (clazz.isEnum()) {
        return new EnumCodec(clazz);
    }
    return null;
}
项目:polymorphia    文件:TypeCodecProviderTest.java   
@Bean()
public static CodecRegistry getCodecRegistry() {
    return CodecRegistries.fromRegistries(
            CodecRegistries.fromProviders(
                    new EnumCodecProvider(),
                    PojoCodecProvider.builder()
                            .register(TypeCodecProviderTest.class)
                            .register(new CustomTypeCodecProvider(), new SetOfStringTypeCodecProvider())
                            .build()
            ),
            MongoClient.getDefaultCodecRegistry());
}
项目:polymorphia    文件:NoDiscriminatorForPolymorphicLeafClassesTest.java   
@Bean()
public static CodecRegistry getCodecRegistry() {
    return CodecRegistries.fromRegistries(
            CodecRegistries.fromProviders(
                    new EnumCodecProvider(),
                    PojoCodecProvider.builder()
                            .register(NoDiscriminatorForPolymorphicLeafClassesTest.class)
                            .build()
            ),
            MongoClient.getDefaultCodecRegistry());
}
项目:polymorphia    文件:TypesModelPackageTest.java   
@Bean()
public static CodecRegistry getCodecRegistry() {
    return CodecRegistries.fromRegistries(
            CodecRegistries.fromProviders(
                    new EnumCodecProvider(),
                    PojoCodecProvider.builder().register("de.bild.codec.model").build()
            ),
            MongoClient.getDefaultCodecRegistry());
}
项目:polymorphia    文件:PolymorphicTest.java   
@Bean()
public static CodecRegistry getCodecRegistry() {
    return CodecRegistries.fromRegistries(
            CodecRegistries.fromProviders(
                    new EnumCodecProvider(),
                    PojoCodecProvider.builder().register(PolymorphicTest.class).build()
            ),
            MongoClient.getDefaultCodecRegistry());
}
项目:polymorphia    文件:UpdateTest.java   
@Bean()
public static CodecRegistry getCodecRegistry() {
    return CodecRegistries.fromRegistries(
            CodecRegistries.fromProviders(
                    new EnumCodecProvider(),
                    PojoCodecProvider.builder()
                            .register(UpdateTest.class)
                            .build()
            ),
            MongoClient.getDefaultCodecRegistry());
}
项目:polymorphia    文件:PolymorphicReflectionCodecTest.java   
@Test(expected = IllegalArgumentException.class)
public void testFieldNameLikeDiscriminatorKey() {
    PojoCodecProvider pojoCodecProvider = PojoCodecProvider.builder().
            register(Shape.class).
            register(ClassWithReservedFieldName.class).
            build();

    assertNotNull(pojoCodecProvider);
    CodecRegistry pojoCodecRegistry = fromRegistries(fromProviders(pojoCodecProvider), MongoClient.getDefaultCodecRegistry());
    MongoCollection<Shape> documents = mongoClient.getDatabase(DB_NAME)
            .getCollection("documents")
            .withCodecRegistry(pojoCodecRegistry)
            .withDocumentClass(Shape.class);
    documents.insertOne(new ClassWithReservedFieldName());
}
项目:polymorphia    文件:NullHandlingTest.java   
@Bean()
public static CodecRegistry getCodecRegistry() {
    return CodecRegistries.fromRegistries(
            CodecRegistries.fromProviders(
                    new EnumCodecProvider(),
                    PojoCodecProvider.builder()
                            .register(NullHandlingTest.class)
                            .encodeNulls(false)
                            .decodeUndefinedHandlingStrategy(DecodeUndefinedHandlingStrategy.Strategy.KEEP_POJO_DEFAULT)
                            .encodeNullHandlingStrategy(EncodeNullHandlingStrategy.Strategy.KEEP_NULL)
                            .build()
            ),
            MongoClient.getDefaultCodecRegistry());
}
项目:polymorphia    文件:NonRegisteredModelClassTest.java   
@Bean()
public static CodecRegistry getCodecRegistry() {
    return CodecRegistries.fromRegistries(
            CodecRegistries.fromProviders(
                    new EnumCodecProvider(),
                    PojoCodecProvider.builder()
                            .register("de.bild.codec.nonregisteredmodel.model")
                            .build()
            ),
            MongoClient.getDefaultCodecRegistry());
}
项目:polymorphia    文件:Tutorial.java   
/**
 *
 * @return a CodecRegistry build from the model package and the DefaultCodecRegistry from the mongo driver
 */
public static CodecRegistry getCodecRegistry() {
    return CodecRegistries.fromRegistries(
            CodecRegistries.fromProviders(
                    new EnumCodecProvider(),
                    PojoCodecProvider.builder()
                            .register("de.bild.codec.tutorial.model")
                            .build()
            ),
            MongoClient.getDefaultCodecRegistry());
}
项目:polymorphia    文件:ExternalIdCodecProviderTest.java   
@Bean()
public static CodecRegistry getCodecRegistry() {
    return CodecRegistries.fromRegistries(
            CodecRegistries.fromProviders(
                    new EnumCodecProvider(),
                    new CustomIdCodecProvider(),
                    PojoCodecProvider.builder()
                            .register(Pojo.class.getPackage().getName())
                            .ignoreTypesAnnotatedWith(IgnoreAnnotation.class)
                            .build()
            ),
            MongoClient.getDefaultCodecRegistry());
}
项目:polymorphia    文件:ExternalIdCodecProviderTest.java   
@Override
public <T> Codec<T> get(Class<T> clazz, CodecRegistry codecRegistry) {
    if (CustomId.class.isAssignableFrom(clazz)) {
        return (Codec<T>)new CustomIdCodec();
    }
    return null;
}
项目:polymorphia    文件:SpecialFieldsMapCodecTest.java   
@Bean
public static CodecRegistry getCodecRegistry() {
    return CodecRegistries.fromRegistries(
            CodecRegistries.fromProviders(
                    new EnumCodecProvider(),
                    PojoCodecProvider.builder().register(SpecialFieldsMapCodecTest.class).build()
            ),
            MongoClient.getDefaultCodecRegistry());
}
项目:polymorphia    文件:IdTest.java   
@Bean()
public static CodecRegistry getCodecRegistry() {
    return CodecRegistries.fromRegistries(
            CodecRegistries.fromProviders(
                    new EnumCodecProvider(),
                    PojoCodecProvider.builder().register(IdTest.class.getPackage().getName()).build()
            ),
            MongoClient.getDefaultCodecRegistry());
}
项目:polymorphia    文件:ListTypeCodecTest.java   
@Bean()
public static CodecRegistry getCodecRegistry() {
    return CodecRegistries.fromRegistries(
            CodecRegistries.fromProviders(
                    new EnumCodecProvider(),
                    PojoCodecProvider.builder().register(ListTypeCodecTest.class).build()
            ),
            MongoClient.getDefaultCodecRegistry());
}
项目:polymorphia    文件:MongoClientOptionsConfig.java   
@Autowired
public MongoClientOptionsConfig(Optional<CodecRegistry> codecRegistry) {
    MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
    if (codecRegistry.isPresent()) {
        builder.codecRegistry(codecRegistry.get());
    }
    this.mongoClientOptions = builder.build();
}
项目:polymorphia    文件:BaseTest.java   
@Bean()
public static CodecRegistry getCodecRegistry() {
    return CodecRegistries.fromRegistries(
            CodecRegistries.fromProviders(
                    new EnumCodecProvider(),
                    PojoCodecProvider.builder().register(BaseTest.class).build()
            ),
            MongoClient.getDefaultCodecRegistry());
}
项目:polymorphia    文件:PreSaveHookTest.java   
@Bean()
public static CodecRegistry getCodecRegistry() {
    return CodecRegistries.fromRegistries(
            CodecRegistries.fromProviders(
                    new EnumCodecProvider(),
                    PojoCodecProvider.builder().register(PreSaveHookTest.class).build()
            ),
            MongoClient.getDefaultCodecRegistry());
}
项目:polymorphia    文件:ExternalIdCodecProviderTest.java   
@Bean()
public static CodecRegistry getCodecRegistry() {
    return CodecRegistries.fromRegistries(
            CodecRegistries.fromProviders(
                    new EnumCodecProvider(),
                    new CustomIdCodecProvider(),
                    PojoCodecProvider.builder()
                            .register(Pojo.class.getPackage().getName())
                            .ignoreTypesAnnotatedWith(IgnoreType.class)
                            .build()
            ),
            MongoClient.getDefaultCodecRegistry());
}
项目:polymorphia    文件:ExternalIdCodecProviderTest.java   
@Override
public <T> Codec<T> get(Class<T> clazz, CodecRegistry codecRegistry) {
    if (CustomId.class.isAssignableFrom(clazz)) {
        return (Codec<T>)new CustomIdCodec();
    }
    return null;
}
项目:polymorphia    文件:TestEnums.java   
@Bean()
public static CodecRegistry getCodecRegistry() {
    return CodecRegistries.fromRegistries(
            CodecRegistries.fromProviders(
                    new EnumCodecProvider(),
                    PojoCodecProvider.builder()
                            .register("de.bild.codec.enums.model")
                            .build()
            ),
            MongoClient.getDefaultCodecRegistry());
}
项目:digital-display-garden-iteration-2-spraguesanborn    文件:UserControllerSpec.java   
private BsonArray parseJsonArray(String json) {
    final CodecRegistry codecRegistry
            = CodecRegistries.fromProviders(Arrays.asList(
            new ValueCodecProvider(),
            new BsonValueCodecProvider(),
            new DocumentCodecProvider()));

    JsonReader reader = new JsonReader(json);
    BsonArrayCodec arrayReader = new BsonArrayCodec(codecRegistry);

    return arrayReader.decode(reader, DecoderContext.builder().build());
}
项目:digital-display-garden-iteration-2-spraguesanborn    文件:FlowerControllerSpec.java   
private BsonArray parseJsonArray(String json) {
    final CodecRegistry codecRegistry
            = CodecRegistries.fromProviders(Arrays.asList(
            new ValueCodecProvider(),
            new BsonValueCodecProvider(),
            new DocumentCodecProvider()));

    JsonReader reader = new JsonReader(json);
    BsonArrayCodec arrayReader = new BsonArrayCodec(codecRegistry);

    return arrayReader.decode(reader, DecoderContext.builder().build());
}
项目:otus-api    文件:ParticipantCodecProvider.java   
@SuppressWarnings("unchecked")
@Override
public <T> Codec<T> get(Class<T> clazz, CodecRegistry registry) {
    if (clazz == Participant.class) {
        return (Codec<T>) new ParticipantCodec();
    }
    return null;
}
项目:otus-api    文件:OtusCodecProvider.java   
@SuppressWarnings("unchecked")
@Override
public <T> Codec<T> get(Class<T> clazz, CodecRegistry registry) {
    if (clazz == Participant.class) {
        return (Codec<T>) new ParticipantCodec();
    }
    if (clazz == User.class) {
        return (Codec<T>) new UserCodec();
    }
    if (clazz == FileUploader.class) {
        return (Codec<T>) new FileUploaderCodec();
    }
    return null;
}
项目:otus-api    文件:MongoDBFactory.java   
@ApplicationScoped
@Produces
public MongoDatabase getMongoDB() {
    MongoCredential credential = MongoCredential.createCredential(username, database, password.toCharArray());

    CodecRegistry codecRegistry = CodecRegistries.fromRegistries(
            CodecRegistries.fromProviders(new OtusCodecProvider()), MongoClient.getDefaultCodecRegistry());

    MongoClientOptions options = MongoClientOptions.builder().codecRegistry(codecRegistry).build();

    ServerAddress serverAddress = new ServerAddress(host, port);

    return new MongoClient(serverAddress, Arrays.asList(credential), options).getDatabase(database);
}
项目:mongo-obj-framework    文件:SmofParser.java   
public SmofParser(SmofDispatcher dispatcher, CodecRegistry registry) {
    this.context = SmofTypeContext.create();
    this.registry = registry;
    serContext = SerializationContext.create();
    parsers = SmofParserPool.create(this, dispatcher);
    lazyLoader = LazyLoader.create(dispatcher);
}