MongoDB Morphia in OSGi

Morphia is an object-document mapping (ODM) library for MongoDB. It may be considered as the lightweight alternative of Spring Data MongoDB or as a richer version of Jongo. Compared to Spring Data MongoDB, Morphia is simpler to setup in a non-Spring environment and it has far fewer dependencies. On the other hand, it lacks Spring Data’s uniform repository interface, and its convention-over-configuration approach that can boost productivity once a basic configuration has been setup.

The Morphia core JAR is OSGi-ready. However enabling entity class resolution in Morphia when running in OSGi requires some extra steps.

Class loading in Morphia

Morphia’s approach to entity class resolution is extensible. It delegates object construction to an instance that implements the org.mongodb.morphia.ObjectFactory interface. Morphia also provides a default implementation – org.mongodb.morphia.mapping.DefaultCreator, which given a com.mongodb.DBObject raw object, it reads its ‘className’ field, resolves the class and instantiates the respective POJO.

Fortunately, DefaultCreator delegates class resolution to a separate protected method which uses the thread-context class loader (TCCL). Although the TCCL should usually be aware of the entity classes since it is typically called from the DAO layer, this may not always be the case. E.g. in Karaf, during a Blueprint container instantiation, the TCCL is not the instantiating bundle class loader, but Karaf’s bootstrap classloader. Overriding the class loading method and delegating to an OSGi-aware classloader provides a more consistent solution.

Entity class resolution in OSGi with Morphia

Here’s a customized version of the DefaultCreator that swaps the TCCL class loader with the bundle context class loader:

public class BundleObjectFactory extends DefaultCreator {
	private BundleContext bundleContext;
	
	@Override
	protected ClassLoader getClassLoaderForClass() {
		ClassLoader cl = ((BundleWiring)bundleContext.getBundle().adapt(
			BundleWiring.class)).getClassLoader();
		
		return cl;
	}

	public BundleObjectFactory(BundleContext bundleContext) {
		super();
		this.bundleContext = bundleContext;
	}
}

A customized instance of the Morphia class can be created through a factory:

public class MorphiaFactory {
	private BundleContext bundleContext;	
	private List<String> classes;
	
	private Class<?> loadClass(String className) throws ClassNotFoundException {
		ClassLoader cl = ((BundleWiring)bundleContext.getBundle().adapt(
			BundleWiring.class)).getClassLoader();
		return cl.loadClass(className);
	}
	
	private Mapper getMapper() {
		Mapper mapper = new Mapper();	
		mapper.getOptions().objectFactory = new BundleObjectFactory(bundleContext);		
		return mapper;
	}
	
	private List<Class<?>> getClassObjects(List<String> classNames) 
		throws ClassNotFoundException {
		if (classNames == null || classNames.size() == 0)
			return null;
		
		List<Class<?>> classObjs = new ArrayList<>();
		for (String className:classNames) {
			classObjs.add(loadClass(className));
		}		
		return classObjs;
	}
	
	@SuppressWarnings("rawtypes")
	public Morphia get() throws ClassNotFoundException {
		Mapper mapper = getMapper();	
		List<Class<?>> classObjs = getClassObjects(classes);
		
		Morphia morphia = new Morphia(mapper, new HashSet<Class>(classObjs));	
		return morphia;
	}

	public void setBundleContext(BundleContext bundleContext) {
		this.bundleContext = bundleContext;
	}

	public void setClasses(List<String> classes) {
		this.classes = classes;
	}
}

Blueprint setup

Bringing it all together, using Blueprint for instantiation and wiring, the resulting configuration is:

<blueprint default-activation="eager"
	xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:cm="http://aries.apache.org/blueprint/xmlns/blueprint-cm/v1.0.0">
	
	<cm:property-placeholder persistent-id="io.modio.blog.osgi.morphia"/>

	<bean id="mongoClient" class="com.mongodb.MongoClient">
		<argument value="${io.modio.blog.osgi.morphia.mongodb.host}"/>
		<argument value="${io.modio.blog.osgi.morphia.mongodb.port}"/>
	</bean>
	
	<bean id="morphiaFactory" class="io.modio.blog.osgi.morphia.MorphiaFactory">
		<property name="bundleContext" ref="blueprintBundleContext"/>
		<property name="classes">
			<list>
				<value>io.modio.blog.osgi.morphia.entity.Acl</value>
				<value>io.modio.blog.osgi.morphia.Principal</value>
			</list>
		</property>
	</bean>
	<bean id="morphia" factory-ref="morphiaFactory" factory-method="get"/>
	
	<bean id="datastoreFactory" class="io.modio.blog.osgi.morphia.DatastoreFactory">
		<property name="mongoClient" ref="mongoClient"/>
		<property name="morphia" ref="morphia"/>
		<property name="database" value="${io.modio.blog.osgi.morphia.mongodb.db}"/>
	</bean>
	<bean id="datastore" factory-ref="datastoreFactory" factory-method="get"/>
	
	<!-- DAOs -->	
	<bean id="aclDao" class="io.modio.blog.osgi.morphia.dao.AclDaoImpl">
		<argument ref="datastore"/>
	</bean>
	<bean id="principalDao" class="io.modio.blog.osgi.morphia.dao.PrincipalDaoImpl">
		<argument ref="datastore"/>
	</bean>
        
	<!-- Services -->
	<service ref="aclDao" interface="io.modio.blog.osgi.morphia.dao.AclDao"/>	
	<service ref="principalDao" interface="io.modio.blog.osgi.morphia.dao.PrincipalDao"/>
</blueprint>

The configuration above includes two sample DAOs that implement a simple authentication/authorization service using MongoDB as the persistent store.

The implementation of DatastoreFactory is straight-forward:

public class DatastoreFactory {
	private MongoClient mongoClient;	
	private Morphia morphia;
	private String database;
	
	public Datastore get() {
		return morphia.createDatastore(mongoClient, database);
	}

	/** get/set methods */
	...
}

Morphia Karaf feature

When deployed in Karaf, it is useful to group all Morphia’s dependencies into a single reusable feature that can then be referenced from other features:

<feature name="morphia" version="0.108" resolver="(obr)">
	<feature version="[1.9.13,2)">jackson</feature>
		
	<bundle dependency="true">mvn:org.mongodb/mongo-java-driver/2.12.2</bundle>
	<bundle>wrap:mvn:com.thoughtworks.proxytoys/proxytoys/1.0</bundle>
	<bundle>mvn:org.mongodb.morphia/morphia/0.108</bundle>
</feature>

2 thoughts on “MongoDB Morphia in OSGi

  • Hello John, do you happen to have a working demo of this? It would be a great help as I’d love to use Morphia/MongoDB in Karaf 3.0.2. But I’m unable to get it to work.

  • Hey John,
    I am studying masters and doing my master thesis.
    I have been trying to work with mongodb with morphia in Apache karaf so it would be nice if you can send me the sample code relating this.

    Regards
    Lipu

Leave a Reply

Your email address will not be published. Required fields are marked *