Skip to content

Instantly share code, notes, and snippets.

@elaatifi
Created December 17, 2015 20:04
Show Gist options
  • Save elaatifi/ade7321a1405c61ff8a9 to your computer and use it in GitHub Desktop.
Save elaatifi/ade7321a1405c61ff8a9 to your computer and use it in GitHub Desktop.
Playing with Orika and Mongo
package mongo.mongo;
import java.util.Arrays;
import java.util.List;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
/**
* Hello world!
*
*/
public class App {
public static void main(String[] args) throws Throwable {
// To directly connect to a single MongoDB server (note that this will
// not auto-discover the primary even
// if it's a member of a replica set:
MongoClient mongoClient = new MongoClient();
MongoMapper mapper = new MongoMapper();
DB db = mongoClient.getDB("test");
DBCollection persons = db.getCollection("persons_");
Person person = new Person();
person.age = 20;
person.name = "Allal";
person.colours = Arrays.asList("yellow","red");
DBObject dbObject = mapper.toDB(person);
System.out.println("person = "+dbObject);
persons.insert(dbObject);
DBObject findOne = persons.findOne();
Person x = mapper.fromDB(findOne, Person.class);
System.out.println("XXX = "+x);
}
public static class Person {
public String name;
public int age;
public List<String> colours;
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + ", colours="
+ colours + "]";
}
}
}
package mongo.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE })
public @interface Entity {
String value() default "";
String concern() default "";
}
package mongo.mongo;
import java.util.Map;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import ma.glasnost.orika.DefaultFieldMapper;
import ma.glasnost.orika.MapperFacade;
import ma.glasnost.orika.converter.ConverterFactory;
import ma.glasnost.orika.impl.DefaultMapperFactory;
import ma.glasnost.orika.impl.util.ClassUtil;
import ma.glasnost.orika.metadata.ClassMapBuilder;
import ma.glasnost.orika.metadata.Property;
import ma.glasnost.orika.metadata.Type;
import ma.glasnost.orika.metadata.TypeFactory;
import ma.glasnost.orika.property.PropertyResolverStrategy;
import mongo.annotation.Entity;
public class MongoMapper {
private MapperFacade mapperFacade;
{
JsonMapperFactory f = new JsonMapperFactory(
new DefaultMapperFactory.Builder());
mapperFacade = f.getMapperFacade();
}
public DBObject toDB(Object object) {
return mapperFacade.map(object, BasicDBObject.class);
}
public <T> T fromDB(DBObject db, Class<T> cls) {
return mapperFacade.map(db, cls);
}
public class JsonMapperFactory extends DefaultMapperFactory {
/**
* Constructs a new instance of DefaultMapperFactory
*
* @param builder
* @param typeMappingStrategy
*/
protected JsonMapperFactory(MapperFactoryBuilder<?, ?> builder) {
super(builder);
addClassMapBuilderFactory(new JsonClassMapBuilderFactory());
}
}
public class JsonClassMapBuilderFactory extends ClassMapBuilder.Factory {
public JsonClassMapBuilderFactory() {
defaults = new DefaultFieldMapper[0];
}
/*
* (non-Javadoc)
*
* @see
* ma.glasnost.orika.metadata.ClassMapBuilderFactory#newClassMapBuilder
* (ma.glasnost.orika.metadata.Type, ma.glasnost.orika.metadata.Type,
* ma.glasnost.orika.property.PropertyResolverStrategy,
* ma.glasnost.orika.DefaultFieldMapper[])
*/
@Override
protected <A, B> ClassMapBuilder<A, B> newClassMapBuilder(
Type<A> aType, Type<B> bType,
ma.glasnost.orika.MapperFactory mapperFactory,
PropertyResolverStrategy propertyResolver,
DefaultFieldMapper[] defaults) {
if (defaults == null)
defaults = new DefaultFieldMapper[0];
final ClassMapBuilder<A, B> builder = super.newClassMapBuilder(
aType, bType, mapperFactory, propertyResolver, defaults);
Map<String, Property> properties;
if (aType.isMap()) {
properties = propertyResolver.getProperties(bType);
} else {
properties = propertyResolver.getProperties(aType);
}
for (Map.Entry<String, Property> e : properties.entrySet()) {
Property modelProperty = e.getValue();
if (!"class".equals(e.getKey())
&& modelProperty.getGetter() != null) {
String setter = String.format("put(\"%s\", %s)",
modelProperty.getName(), "%s");
String getter = String.format("get(\"%s\")",
modelProperty.getName());
Type<?> type = mapJsonType(modelProperty,
mapperFactory.getConverterFactory());
Property jsonProperty = new Property.Builder().type(type)
.expression(modelProperty.getExpression())
.name(modelProperty.getName()).setter(setter)
.getter(getter).build();
/* registering field map in the appropriate direction */
if (isDBObject(aType)) {
if (modelProperty.getSetter() == null) {
builder.fieldMap(jsonProperty, modelProperty, true)
.bToA().add();
} else {
builder.field(jsonProperty, modelProperty);
}
} else {
if (modelProperty.getSetter() == null) {
builder.fieldMap(modelProperty, jsonProperty, true)
.aToB().add();
} else {
builder.field(modelProperty, jsonProperty);
}
}
}
}
return builder;
}
/**
* @param aType
* @return
*/
protected <A> boolean isDBObject(Type<A> aType) {
return DBObject.class.isAssignableFrom(aType.getRawType());
}
@Override
protected <A, B> boolean appliesTo(Type<A> aType, Type<B> bType) {
return isDBObject(aType) || isDBObject(bType);
}
private final Type<?> mapJsonType(Property property,
ConverterFactory converterFactory) {
// final Converter<Object, Object> converter =
// converterFactory.getConverter(property.getType(),
// TypeFactory.valueOf(String.class));
if (property.getType().isPrimitive())
return TypeFactory.valueOf(ClassUtil.getWrapperType(property.getRawType()));
return property.getType();
}
private String collectionForType(Type<?> type) {
Entity entity = type.getRawType().getAnnotation(Entity.class);
assert entity != null : "Need @Entity annotation";
return entity.value();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment