org.bson.codecs.Codec Java Examples

The following examples show how to use org.bson.codecs.Codec. 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: MorphiaCollectionPropertyCodecProvider.java    From morphia with Apache License 2.0 6 votes vote down vote up
@Override
public <T> Codec<T> get(final TypeWithTypeParameters<T> type, final PropertyCodecRegistry registry) {
    if (Collection.class.isAssignableFrom(type.getType())) {
        final List<? extends TypeWithTypeParameters<?>> typeParameters = type.getTypeParameters();
        TypeWithTypeParameters<?> valueType = getType(typeParameters, 0);

        try {
            return new MorphiaCollectionCodec(type, registry, valueType);
        } catch (CodecConfigurationException e) {
            if (valueType.getType().equals(Object.class)) {
                try {
                    return (Codec<T>) registry.get(TypeData.builder(Collection.class).build());
                } catch (CodecConfigurationException e1) {
                    // Ignore and return original exception
                }
            }
            throw e;
        }
    }

    return null;
}
 
Example #2
Source File: ElasticBulkService.java    From mongolastic with MIT License 6 votes vote down vote up
/**
 * 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 #3
Source File: ChangeEvents.java    From stitch-android-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Transforms a {@link ChangeEvent} into one that can be used by a user defined conflict resolver.
 * @param event the event to transform.
 * @param codec the codec to use to transform any documents specific to the collection.
 * @return the transformed {@link ChangeEvent}
 */
static ChangeEvent transformChangeEventForUser(
    final ChangeEvent<BsonDocument> event,
    final Codec codec
) {
  return new ChangeEvent<>(
      event.getId(),
      event.getOperationType(),
      event.getFullDocument() == null ? null : codec.decode(
          sanitizeDocument(event.getFullDocument()).asBsonReader(),
          DecoderContext.builder().build()),
      event.getNamespace(),
      event.getDocumentKey(),
      sanitizeUpdateDescription(event.getUpdateDescription()),
      event.hasUncommittedWrites());
}
 
Example #4
Source File: TupleCodecProviderTest.java    From immutables with Apache License 2.0 6 votes vote down vote up
/**
 * Projection of an optional attribute
 */
@Test
@SuppressWarnings("unchecked")
public void optionalAttribute_nickname() {
  Query query = Query.of(Person.class).addProjections(Matchers.toExpression(PersonCriteria.person.nickName));
  Path idPath = Visitors.toPath(KeyExtractor.defaultFactory().create(Person.class).metadata().keys().get(0));
  TupleCodecProvider provider = new TupleCodecProvider(query, new MongoPathNaming(idPath, PathNaming.defaultNaming()).toExpression());
  Codec<ProjectedTuple> codec = provider.get(ProjectedTuple.class, registry);

  ProjectedTuple tuple1 = codec.decode(new BsonDocumentReader(new BsonDocument("nickName", new BsonString("aaa"))), DecoderContext.builder().build());
  check(tuple1.values()).hasSize(1);
  check((Optional<String>) tuple1.values().get(0)).is(Optional.of("aaa"));

  ProjectedTuple tuple2 = codec.decode(new BsonDocumentReader(new BsonDocument()), DecoderContext.builder().build());
  check(tuple2.values()).hasSize(1);
  check((Optional<String>) tuple2.values().get(0)).is(Optional.empty());
}
 
Example #5
Source File: SetEntityOperator.java    From morphia with Apache License 2.0 6 votes vote down vote up
@Override
public OperationTarget toTarget(final PathTarget pathTarget) {
    return new OperationTarget(null, value()) {
        @Override
        public Object encode(final Mapper mapper) {
            MappedClass mappedClass = mapper.getMappedClass(getValue().getClass());
            if (mappedClass.getVersionField() == null) {
                return super.encode(mapper);
            }

            Codec codec = mapper.getCodecRegistry().get(getValue().getClass());
            DocumentWriter writer = new DocumentWriter();

            codec.encode(writer, getValue(), EncoderContext.builder().build());

            Document document = writer.getDocument();
            document.remove(mappedClass.getVersionField().getMappedFieldName());
            return document;
        }
    };
}
 
Example #6
Source File: EnumPropertyCodecProvider.java    From morphia with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({"unchecked", "rawtypes"})
@Override
public <T> Codec<T> get(final TypeWithTypeParameters<T> type, final PropertyCodecRegistry propertyCodecRegistry) {
    Class<T> clazz = type.getType();
    if (Enum.class.isAssignableFrom(clazz)) {
        try {
            return codecRegistry.get(clazz);
        } catch (CodecConfigurationException e) {
            return (Codec<T>) new EnumCodec(clazz);
        }
    }
    return null;
}
 
Example #7
Source File: CollectionPropertyCodecProvider.java    From morphia with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({"rawtypes", "unchecked"})
@Override
public <T> Codec<T> get(final TypeWithTypeParameters<T> type, final PropertyCodecRegistry registry) {
    if (Collection.class.isAssignableFrom(type.getType()) && type.getTypeParameters().size() == 1) {
        return new CollectionCodec(type.getType(), registry.get(type.getTypeParameters().get(0)));
    } else {
        return null;
    }
}
 
Example #8
Source File: Mapper.java    From morphia with Apache License 2.0 5 votes vote down vote up
/**
 * Converts an entity (POJO) to a Document.  A special field will be added to keep track of the class type.
 *
 * @param entity The POJO
 * @return the Document
 * @morphia.internal
 */
public Document toDocument(final Object entity) {

    final MappedClass mc = getMappedClass(entity.getClass());

    DocumentWriter writer = new DocumentWriter();
    Codec codec = getCodecRegistry().get(mc.getType());
    codec.encode(writer, entity,
        EncoderContext.builder()
                      .build());

    return writer.getDocument();
}
 
Example #9
Source File: FieldModel.java    From morphia with Apache License 2.0 5 votes vote down vote up
FieldModel(final Field field, final String name, final String mappedName, final TypeData<T> typeData,
           final List<Annotation> annotations, final Codec<T> codec, final PropertyAccessor<T> accessor,
           final PropertySerialization<T> serialization) {
    this.field = Objects.requireNonNull(field, Sofia.notNull("field"));
    this.name = Objects.requireNonNull(name, Sofia.notNull("name"));
    this.mappedName = Objects.requireNonNull(mappedName, Sofia.notNull("name"));
    this.typeData = Objects.requireNonNull(typeData, Sofia.notNull("typeData"));
    this.annotations = annotations;
    this.codec = codec;
    this.cachedCodec = codec;
    this.accessor = accessor;
    this.serialization = serialization;

    this.field.setAccessible(true);
}
 
Example #10
Source File: AggregationImpl.java    From morphia with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({"unchecked", "rawtypes"})
private List<Document> getDocuments() {
    return stages.stream()
                 .map(s -> {
                     Codec codec = datastore.getMapper().getCodecRegistry().get(s.getClass());
                     DocumentWriter writer = new DocumentWriter();
                     codec.encode(writer, s, EncoderContext.builder().build());
                     return writer.getDocument();
                 })
                 .collect(Collectors.toList());
}
 
Example #11
Source File: ValueExpression.java    From morphia with Apache License 2.0 5 votes vote down vote up
@Override
public void encode(final Mapper mapper, final BsonWriter writer, final EncoderContext encoderContext) {
    if (getValue() != null) {
        Codec codec = mapper.getCodecRegistry().get(getValue().getClass());
        encoderContext.encodeWithChildContext(codec, writer, getValue());
    } else {
        writer.writeNull();
    }
}
 
Example #12
Source File: PropertyCodecRegistryImpl.java    From morphia with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <S> Codec<S> get(final TypeWithTypeParameters<S> type, final PropertyCodecRegistry propertyCodecRegistry) {
    Class<S> clazz = type.getType();
    if (clazz == codec.getEncoderClass()) {
        return (Codec<S>) codec;
    }
    return codecRegistry.get(type.getType());
}
 
Example #13
Source File: TupleCodecProviderTest.java    From immutables with Apache License 2.0 5 votes vote down vote up
@Test
void localDate() {
  LocalDateHolderCriteria criteria = LocalDateHolderCriteria.localDateHolder;

  Query query = Query.of(TypeHolder.LocalDateHolder.class)
          .addProjections(Matchers.toExpression(criteria.value),  Matchers.toExpression(criteria.nullable), Matchers.toExpression(criteria.optional));

  Path idPath = Visitors.toPath(KeyExtractor.defaultFactory().create(TypeHolder.LocalDateHolder.class).metadata().keys().get(0));
  TupleCodecProvider provider = new TupleCodecProvider(query, new MongoPathNaming(idPath, PathNaming.defaultNaming()).toExpression());
  Codec<ProjectedTuple> codec = provider.get(ProjectedTuple.class, registry);

  LocalDate now = LocalDate.now();
  final long millisEpoch = now.atStartOfDay().toInstant(ZoneOffset.UTC).toEpochMilli();

  BsonDocument doc = new BsonDocument()
          .append("id", new BsonString("id1"))
          .append("value", new BsonDateTime(millisEpoch))
          .append("nullable", BsonNull.VALUE)
          .append("optional", BsonNull.VALUE)
          .append("array", new BsonArray())
          .append("list", new BsonArray());

  ProjectedTuple tuple = codec.decode(new BsonDocumentReader(doc), DecoderContext.builder().build());

  check(tuple.get(Matchers.toExpression(criteria.value))).is(now);
  check(tuple.get(Matchers.toExpression(criteria.nullable))).isNull();
  check(tuple.get(Matchers.toExpression(criteria.optional))).is(Optional.empty());
}
 
Example #14
Source File: JacksonCodecRegistry.java    From immutables with Apache License 2.0 5 votes vote down vote up
@Override
public <T> Codec<T> get(Class<T> clazz) {
  final JavaType javaType = mapper.getTypeFactory().constructType(clazz);
  if (!(mapper.canSerialize(clazz) && mapper.canDeserialize(javaType))) {
    throw new CodecConfigurationException(String.format("%s (javaType: %s) not supported by Jackson Mapper", clazz, javaType));
  }

  return new JacksonCodec<>(clazz, mapper);
}
 
Example #15
Source File: GeoWithinFilter.java    From morphia with Apache License 2.0 5 votes vote down vote up
@Override
public final void encode(final Mapper mapper, final BsonWriter writer, final EncoderContext context) {
    writer.writeStartDocument(field(mapper));
    writer.writeStartDocument(getFilterName());
    writer.writeName("$geometry");

    Object shape = getValue();
    Codec codec = mapper.getCodecRegistry().get(shape.getClass());
    codec.encode(writer, shape, context);

    writer.writeEndDocument();
    writer.writeEndDocument();
}
 
Example #16
Source File: TupleCodecProviderTest.java    From immutables with Apache License 2.0 5 votes vote down vote up
@Test
public void age() {
  Query query = Query.of(Person.class).addProjections(Matchers.toExpression(PersonCriteria.person.age));
  Path idPath = Visitors.toPath(KeyExtractor.defaultFactory().create(Person.class).metadata().keys().get(0));
  TupleCodecProvider provider = new TupleCodecProvider(query, new MongoPathNaming(idPath, PathNaming.defaultNaming()).toExpression());
  Codec<ProjectedTuple> codec = provider.get(ProjectedTuple.class, registry);

  ProjectedTuple tuple = codec.decode(new BsonDocumentReader(new BsonDocument("age", new BsonInt32(10))), DecoderContext.builder().build());

  check(tuple.values()).hasSize(1);
  check(tuple.values().get(0)).asString().is("10");
}
 
Example #17
Source File: KeyCodec.java    From morphia with Apache License 2.0 5 votes vote down vote up
@Override
public void encode(final BsonWriter writer, final Key value, final EncoderContext encoderContext) {
    writer.writeStartDocument();
    String collection = value.getCollection();
    if (collection == null) {
        collection = mapper.getMappedClass(value.getType()).getCollectionName();
    }
    writer.writeString("$ref", collection);
    writer.writeName("$id");
    Codec codec = mapper.getCodecRegistry().get(value.getId().getClass());
    codec.encode(writer, value.getId(), encoderContext);
    writer.writeEndDocument();
}
 
Example #18
Source File: GsonCodecs.java    From immutables with Apache License 2.0 5 votes vote down vote up
/**
 * Gson Factory which gives preference to existing adapters from {@code gson} instance. However,
 * if type is not supported it will query {@link CodecRegistry} to create one (if possible).
 *
 * <p>This allows supporting Bson types by Gson natively (eg. for {@link org.bson.types.ObjectId}).
 *
 * @param registry existing registry which will be used if type is unknown to {@code gson}.
 * @return factory which delegates to {@code registry} for unknown types.
 */
public static TypeAdapterFactory delegatingTypeAdapterFactory(final CodecRegistry registry) {
  Preconditions.checkNotNull(registry, "registry");
  return new TypeAdapterFactory() {
    @Override
    public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
      boolean hasAdapter;
      try {
        TypeAdapter<T> adapter = gson.getDelegateAdapter(this, type);
        hasAdapter = !isReflectiveTypeAdapter(adapter);
      } catch (IllegalArgumentException e) {
        hasAdapter = false;
      }

      if (hasAdapter) {
        return null;
      }

      try {
        @SuppressWarnings("unchecked")
        Codec<T> codec = (Codec<T>) registry.get(type.getRawType());
        return typeAdapterFromCodec(codec);
      } catch (CodecConfigurationException e1) {
        return null;
      }

    }
  };
}
 
Example #19
Source File: EnumCodecProvider.java    From morphia with Apache License 2.0 5 votes vote down vote up
/**
 * Looks up the codec for the type
 *
 * @param type     the type to look up
 * @param registry the registry to use
 * @param <T>      the type of the enum
 * @return the codec if found or null
 */
@Override
@SuppressWarnings("unchecked")
public <T> Codec<T> get(final Class<T> type, final CodecRegistry registry) {
    if (type.isEnum()) {
        return new EnumCodec(type);
    }
    return null;
}
 
Example #20
Source File: JacksonCodecs.java    From immutables with Apache License 2.0 5 votes vote down vote up
private static <T> JsonDeserializer<T> deserializer(final Codec<T> codec) {
  Objects.requireNonNull(codec, "codec");
  return new JsonDeserializer<T>() {
    @Override
    public T deserialize(JsonParser parser, DeserializationContext ctxt) {
      @SuppressWarnings("unchecked")
      final BsonReader reader = ((Wrapper<BsonReader>) parser).unwrap();
      return codec.decode(reader, DecoderContext.builder().build());
    }
  };
}
 
Example #21
Source File: ReferenceCodec.java    From morphia with Apache License 2.0 5 votes vote down vote up
@Override
public void encode(final BsonWriter writer, final Object instance, final EncoderContext encoderContext) {
    Object idValue = collectIdValues(instance);

    if (idValue != null) {
        final Codec codec = getDatastore().getMapper().getCodecRegistry().get(idValue.getClass());
        codec.encode(writer, idValue, encoderContext);
    } else {
        throw new ReferenceException(Sofia.noIdForReference());
    }
}
 
Example #22
Source File: JacksonCodecs.java    From immutables with Apache License 2.0 5 votes vote down vote up
private static <T> Codec<T> findCodecOrNull(CodecRegistry registry, Class<T> type) {
  try {
    return registry.get(type);
  } catch (CodecConfigurationException e) {
    return null;
  }
}
 
Example #23
Source File: TupleCodecProvider.java    From immutables with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <T> Codec<T> get(Class<T> clazz, CodecRegistry registry) {
  if (clazz == ProjectedTuple.class) {
    return (Codec<T>) new TupleCodec(registry, query, naming);
  }
  return null;
}
 
Example #24
Source File: MongoSession.java    From immutables with Apache License 2.0 5 votes vote down vote up
/**
 * Convert generic object to a BsonValue
 */
private BsonValue toBsonValue(Object value) {
  BsonDocumentWriter writer = new BsonDocumentWriter(new BsonDocument());
  writer.writeStartDocument();
  writer.writeName("value");
  Codec<Object> codec = (Codec<Object>) collection.getCodecRegistry().get(value.getClass());
  codec.encode(writer, value, EncoderContext.builder().build());
  writer.writeEndDocument();
  return writer.getDocument().get("value");
}
 
Example #25
Source File: BsonCodecRepoTest.java    From immutables with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked") // hopefully correct
@Override
public <T> Codec<T> get(Class<T> clazz) {
  if (!Somebody.class.isAssignableFrom(clazz)) {
    throw new CodecConfigurationException("Not supported " + clazz);
  }
  return (Codec<T>) this;
}
 
Example #26
Source File: JacksonCodecs.java    From immutables with Apache License 2.0 5 votes vote down vote up
public static Serializers serializers(final CodecRegistry registry) {
  return new Serializers.Base() {
    @Override
    public JsonSerializer<?> findSerializer(SerializationConfig config, JavaType type, BeanDescription beanDesc) {
      try {
        Codec<?> codec = registry.get(type.getRawClass());
        return serializer(codec);
      } catch (CodecConfigurationException e) {
        return null;
      }
    }
  };
}
 
Example #27
Source File: ExpressionCodec.java    From morphia with Apache License 2.0 5 votes vote down vote up
/**
 * @param mapper
 * @param writer
 * @param name
 * @param value
 * @param encoderContext
 * @morphia.internal
 */
public static void writeNamedValue(final Mapper mapper, final BsonWriter writer, final String name, final Object value,
                                   final EncoderContext encoderContext) {
    if (value != null) {
        writer.writeName(name);
        Codec codec = mapper.getCodecRegistry().get(value.getClass());
        encoderContext.encodeWithChildContext(codec, writer, value);
    }
}
 
Example #28
Source File: JacksonCodecs.java    From immutables with Apache License 2.0 5 votes vote down vote up
public static CodecRegistry registryFromMapper(final ObjectMapper mapper) {
  Preconditions.checkNotNull(mapper, "mapper");
  return new CodecRegistry() {
    @Override
    public <T> Codec<T> get(final Class<T> clazz) {
      final JavaType javaType = TypeFactory.defaultInstance().constructType(clazz);
      if (!mapper.canSerialize(clazz) || !mapper.canDeserialize(javaType)) {
        throw new CodecConfigurationException(String.format("%s (javaType: %s) not supported by Jackson Mapper", clazz, javaType));
      }
      return new JacksonCodec<>(clazz, mapper);
    }
  };
}
 
Example #29
Source File: GsonCodecs.java    From immutables with Apache License 2.0 5 votes vote down vote up
/**
 * Given existing {@code Gson} instance builds a {@link CodecRegistry}.
 *
 * @param gson preconfigured instance
 * @return wrapper for {@code gson}.
 */
public static CodecRegistry codecRegistryFromGson(final Gson gson) {
  Preconditions.checkNotNull(gson, "gson");
  return new CodecRegistry() {
    @Override
    public <T> Codec<T> get(Class<T> clazz) {
      return codecFromTypeAdapter(clazz, gson.getAdapter(clazz));
    }
  };
}
 
Example #30
Source File: FruitCodecProvider.java    From quarkus-quickstarts with Apache License 2.0 5 votes vote down vote up
@Override
public <T> Codec<T> get(Class<T> clazz, CodecRegistry registry) {
    if (clazz == Fruit.class) {
        return (Codec<T>) new FruitCodec();
    }
    return null;
}