Long story short: Is it possible to write a type converter for a 3rd party library class with Morphia?
Long story: I'm new to Morphia. I have an entity class which contains a field typed javax.activation.MimeType. When I try to save instances of my class, Morphia complains it "can't serialize class javax.activation.MimeType". I tried writing a TypeConverter and adding it to the list of converters but it didn't work. Here are the code pieces:
Entity.class
@Entity
@Converters(MimeTypeConverter.class)
public class Entity {
@Id ObjectId id;
String name;
javax.activation.MimeType mimeType;
}
MimeTypeConverter.class
public class MimeTypeConverter extends TypeConverter {
@Override
public Object decode(Class targetClass,
Object fromDBObject,
MappedField optionalExtraInfo) {
MimeType mimetype;
BasicDBObject dbObject = (BasicDBObject) fromDBObject;
String mimeString = dbObject.getString("mimeType");
try{
mimetype = new MimeType(mimeString);
} catch(MimeTypeParseException ex){
mimetype = new MimeType();
}
return mimetype;
}
@Override
public Object encode(Object value, MappedField optionalExtraInfo) {
MimeType mimetype = (MimeType) value;
return mimetype.getBaseType();
}
@Override
public Class[] getSupportTypes() {
return new Class[]{MimeType.class};
}
}
Test Case
Morphia morphia = new Morphia().map(Entity.class);
morphia.getMapper().getConverters().addConverter(new MimeTypeConverter());
Datastore ds = morphia.createDatastore(new MongoClient(), "test"); //UnknownHostException
Entity entity = new Entity();
entity.name = "test name";
entity.mimeType = new MimeType("text/plain"); //MimeTypeParseException
ds.save(entity); // FAILS WITH ERROR HERE
I want MimeType class to serialize in "foo/bar" style, and deserialize from it. Is that possible?