/** * Creates "writer" which can serialize existing immutable instance into <a href="http://bsonspec.org/">BSON format</a> * consumed by mongo server. */ public static <T> Encoder<T> encoderFor(final Class<T> type, final TypeAdapter<T> adapter) { checkNotNull(type, "type"); checkNotNull(adapter, "adapter"); return new Encoder<T>() { @Override public void encode(org.bson.BsonWriter writer, T value, EncoderContext encoderContext) { try { adapter.write(new org.immutables.mongo.repository.internal.BsonWriter(writer), value); } catch (IOException e) { throw new RuntimeException(String.format("Couldn't write value of class %s: %s", type.getName(), value),e); } } @Override public Class<T> getEncoderClass() { return type; } }; }
/** * 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(); } }
BsonValue toBson() { @SuppressWarnings("unchecked") Encoder<T> encoder = BsonEncoding.encoderFor((Class<T>) value.getClass(), adapter); BsonDocument bson = new BsonDocument(); org.bson.BsonWriter writer = new BsonDocumentWriter(bson); // Bson doesn't allow to write directly scalars / primitives, they have to be embedded in a document. writer.writeStartDocument(); writer.writeName("$"); encoder.encode(writer, value, EncoderContext.builder().build()); writer.writeEndDocument(); writer.flush(); return bson.get("$"); }
@SuppressWarnings("unchecked") private BsonDocument toBsonDocument(final String key, final Object value) { BsonDocumentWriter writer = new BsonDocumentWriter(new BsonDocument()); writer.writeStartDocument(); writer.writeName(key); ((Encoder) database.getCodecRegistry().get(value.getClass())).encode(writer, value, ENCODER_CONTEXT); writer.writeEndDocument(); return writer.getDocument(); }
@Override public String toJson(Encoder<Document> encoder) { throw new UnsupportedOperationException("inner bsonDocument not support toJson(encoder)."); }
@Override public String toJson(JsonWriterSettings writerSettings, Encoder<Document> encoder) { throw new UnsupportedOperationException("inner bsonDocument not support toJson(encoder)."); }