Implementing a Spring custom namespace for Olingo

Spring is a lightweight container that implements dependency injection. It provides a convenient and extensible way to implement DSLs within its XML configuration to make easier configurations of particular issues.

Olingo is a Java library that implements the Open Data Protocol (OData). Its version 4 provides support for version 3 and 4 of the OData specification at both client and server sides.

We will describe here how to implement such a custom namespace on a real-world use case to easily configure the Olingo server side. This post is based on a contribution for Olingo. The following issue in JIRA contains the source code in attachment: (OLINGO-562).

Lets begin by designing our custom namespace.

Designing the custom namespace

We need first to have a look at the Olingo code to create an HTTP handler.

The first part consists in the création of the service metadata, as described below:

OData odata = OData.newInstance();
EdmProvider edmProvider = getEdmProvider();

EdmxReference reference = new EdmxReference(
reference.addInclude(new EdmxReferenceInclude(
        "Org.OData.Core.V1", "Core"));
List<EdmxReference> references = Arrays.asList(reference);
ServiceMetadata serviceMetadata = odata.createServiceMetadata(
                                                 edmProvider, references);

Then we can create the handler and register all processors for requests. The following code describes this:

List<Processor> odataProcessors = (...)
ODataHttpHandler dataHandler = odata.createHandler(serviceMetadata);
if (odataProcessors!=null) {
    for (Processor odataProcessor : odataProcessors) {

We can notice that the previous code uses static methods to create instances. Whereas its possible to use the factory feature support of Spring, well rather use its powerful concept of FactoryBean. The latter provides an indirection level to get instances of beans that cant be created simply using a new. We will deal with this aspect in section .

This first thing to do before dive into the design and the implementation of the namespace is to try to configure what we want to obtain using the default XML configuration of Spring. This is very useful since implementing a Spring custom namespace actually consists in configuring programmatically the container (bean definition, properties and so on) based on the hints we get from the custom XML elements.

Configuring an HTTP handler for Olingo within a Spring context is a bit verbose with the default XML configuration. It would look like something like that:

<bean id="httpHandler"
    <property name="odata" ref="odata" />
    <property name="serviceMetadata">
        <bean class="org.apache.olingo.spring.factory.ServiceMetadataFactoryBean">
            <property name="odata" ref="odata" />
            <property name="edmProvider" ref="edmProvider" />
            <property name="references">
                    <bean class="org.apache.olingo.spring.factory.EdmxReferenceFactoryBean">
                        <property name="uri"
                             value="../v4.0/cs02/vocabularies/Org.OData.Core.V1.xml" />
                        <property name="includes">
                                <entry key="Org.OData.Core.V1" value="Core" />
    <property name="processors">
            <ref bean="testProcessor" />

Our custom namespace could look like something like to take into account all the necessary hints present in the previous XML configuration:

<olingo:http-handler id="httpHandler" edm-provider="edmProvider">
    <olingo:reference uri="../v4.0/cs02/vocabularies/Org.OData.Core.V1.xml">
        <olingo:include key="Org.OData.Core.V1" value="Core"/>
    <olingo:processor ref="testProcessor"/>

We can notice that we can also provide something to make easier the configuration of an EDM provider declaratively within a Spring configuration.

Implementing Spring FactoryBeans

Our factory beans implement both interfaces:

  • FactoryBean. This interface defines the type of object to create (method getObject), if its a singleton (method isSingleton) and how to create it (method getObject).
  • InitializingBean. This interface allows to check if everythting is injected in the factory to make possible the creation of the object.

The following code describes how implement a factory bean to create an HTTP handler:

public class ODataHttpHandlerFactoryBean implements
                FactoryBean<ODataHttpHandler>, InitializingBean {
    private OData odata;
    private ServiceMetadata serviceMetadata;
    private List<Processor> processors;

    public ODataHttpHandler getObject() throws Exception {
        ODataHttpHandler handler = odata.createHandler(serviceMetadata);
        if (processors != null) {
            for (Processor processor : processors) {
        return handler;

    public Class<?> getObject () {
        return ODataHttpHandler.class;

    public boolean isSingleton() {
        return true;

    public void afterPropertiesSet() throws Exception {
        if (odata == null) {
            throw new IllegalArgumentException(
                               "The property odata is required.");

        if (serviceMetadata == null) {
            throw new IllegalArgumentException(
                       "The property serviceMetadata is required.");

    // Getters and setters

We have everything now to begin to implement our custom namespace for Olingo.

Implementing the namespace handler

The first step consists in defining an XML schema for our grammar. This file will be used by Spring to validate that the specified configuration is correct with a Spring XML configuration. We wont dive here into more details. We provide below the XML schema for the definition of the configuration of an HTTP handler.

            elementFormDefault="qualified" attributeFormDefault="unqualified">

    <xsd:import namespace=""
                " />

    <xsd:element name="http-handler" type="httpHandlerBeanType">

    <xsd:complexType name="httpHandlerBeanType">
            <xsd:element name="reference"
            <xsd:element name="processor"
        <xsd:attribute name="id" type="xsd:string" use="required"/>
        <xsd:attribute name="edm-provider" type="xsd:string" use="required"/>

    <xsd:complexType name="referenceBeanType">
            <xsd:element name="include"
        <xsd:attribute name="uri" type="xsd:string" use="required"/>

    <xsd:complexType name="referenceIncludeBeanType">
        <xsd:attribute name="key" type="xsd:string" use="required"/>
        <xsd:attribute name="value" type="xsd:string" use="required"/>

    <xsd:complexType name="processorBeanType">
        <xsd:attribute name="ref" type="xsd:string" use="required"/>

Spring requires two files to put within the folder META-INF/spring. They allow to map namespace URL used in the XML with entities to handle it. This actually corresponds to the two following things:

  • the XML schema file to validate the XML configuration
  • the namespace handler class

First, we need to configure namespace handler class for the namespace in the file spring.handlers:


Then we do a similar thing for the XML Schema file in the file spring.schemas:


Now we have the configure done. Lets implement the class OlingoNamespaceHandler. The latter allows to define which element are handled at the root level. We associate a dedicated parser for each of them in order to parse the custom grammar and use its hints to configure corresponding beans in Spring. Following code describes the content of this class:

public class OlingoNamespaceHandler
                extends NamespaceHandlerSupport {
    public static final String HTTP_HANDLER_ELEMENT = "http-handler";

    public void init() {
                                    new OlingoHttpHandlerBeanDefinitionParser());

The parser delegates the parse processing to a dedicated helper class called OlingoHandlerBeanDefinitionHelper. The latter is responsible to parse the XML elements and create corresponding bean definition(s).

public class OlingoHttpHandlerBeanDefinitionParser
                             extends AbstractBeanDefinitionParser {
    protected AbstractBeanDefinition parseInternal(Element element,
                                             ParserContext parserContext) {
        BeanDefinition configuration
               = OlingoHandlerBeanDefinitionHelper.parseHttpHandler(
                                             element, parserContext);
        return (AbstractBeanDefinition) configuration;

Note: automatic registration / return null and use the registry

Spring provides an API for all concepts supported when configuring beans within XML files.

  • BeanDefinitionBuilder. This provides a builder to make easier
  • BeanDefinition. This corresponds to a bean definition.
  • RuntimeBeanReference. This allows to define a property that references a bean.
  • ManagedList. This allows to define list properties. They can contain both bean definitions, bean references and values.
  • ManagedMap. This allows to define map properties. They can contain both bean definitions, bean references and values.

The following methods of the class BeanDefinitionBuilder allow to link bean definitions between us and actually define dependency injection:

  • addPropertyValue. This method allows to define the value of a property. The second parameter of this method can be a primitive value, a bean definition, a bean reference, a list or a map.
  • addConstructorArg. This method allows to define a constructor parameter. It can contain the same things than the previous method.

We define some utility methods to get element attribute value (method elementAttribute) and create a bean definition builder for a specific class (method createBeanDefinitionBuilder).

private static String elementAttribute(
                       Element element, String name) {
    String value = element.getAttribute(name);
    return value.length() == 0 ? null : value;

private static BeanDefinitionBuilder
               createBeanDefinitionBuilder(Class<?> beanClass) {
    return BeanDefinitionBuilder.rootBeanDefinition(beanClass);

The code below corresponds to the complete processing to parse the XML element and generate corresponding beans. Its a bit long but it provides a concrete and from real-life example of use.

public static BeanDefinition parseHttpHandler(
                         Element element, ParserContext parserContext) {
    BeanDefinitionBuilder httpHandler = createBeanDefinitionBuilder(

    // OData
    BeanDefinitionBuilder odataBuilder = createBeanDefinitionBuilder(
    BeanDefinition odata = odataBuilder.getBeanDefinition();

    httpHandler.addPropertyValue(ODATA_PROPERTY, odata);

    // ServiceMetadata
    BeanDefinitionBuilder serviceMetadata = createBeanDefinitionBuilder(
    serviceMetadata.addPropertyValue(ODATA_PROPERTY, odata);

    String edmProviderRef = elementAttribute(
                                       element, EDM_PROVIDER_ATTR);
                                    new RuntimeBeanReference(edmProviderRef));

    // References
    List<Element> referenceElements
                                 = DomUtils.getChildElementsByTagName(
                                               element, REFERENCE_ELEMENT);
    if (referenceElements.size() > 0) {
        ManagedList<BeanDefinition> referenceList
                          = new ManagedList<BeanDefinition>(
        for (Element referenceElement : referenceElements) {
            BeanDefinition reference = parseReference(
                                        referenceElement, parserContext);
                 REFERENCES_LIST_PROPERTY, referenceList);


    // Processors
    List<Element> processorElements
                     = DomUtils.getChildElementsByTagName(
                                          element, PROCESSOR_ELEMENT);
    if (processorElements.size() > 0) {
        ManagedList<RuntimeBeanReference> processorList
                        = new ManagedList<RuntimeBeanReference>(
        for (Element processorElement : processorElements) {
            RuntimeBeanReference processorRef = parseProcessor(
                                                  processorElement, parserContext);

    AbstractBeanDefinition configurationDef = httpHandler.getBeanDefinition();
    return configurationDef;

The method parseReference parses the reference definition:

private static BeanDefinition parseReference(
           Element referenceElement, ParserContext parserContext) {
    BeanDefinitionBuilder reference = createBeanDefinitionBuilder(

    String uri = elementAttribute(referenceElement, URI_ATTR);
    reference.addPropertyValue(URI_PROPERTY, uri);

    // Processors
    List<Element> includeElements = DomUtils.getChildElementsByTagName(
                                           referenceElement, INCLUDE_ELEMENT);
    if (includeElements.size() > 0) {
        ManagedMap<String, String> includeMap
                     = new ManagedMap<String, String>(
        for (Element includeElement : includeElements) {
            String key = elementAttribute(includeElement, KEY_ATTR);
            String value = elementAttribute(includeElement, VALUE_ATTR);
            includeMap.put(key, value);
        reference.addPropertyValue(INCLUDES_PROPERTY, includeMap);

    return reference.getBeanDefinition();

The method parseProcessor parses the processor definition:

private static RuntimeBeanReference parseProcessor(
        Element processorElement, ParserContext parserContext) {
    String ref = elementAttribute(processorElement, REF_ATTR);
    return new RuntimeBeanReference(ref);

Implementing a Spring

Now we have implemented a way to configure an Olingo HTTP handler, we need to implement a servlet that can be an instance of it from the Spring Web application context and use it. This servlet needs to the following:

  • Reference the Spring Web application context
  • Get an instance of ODataHttpHandler from this context
  • Use this instance to serve OData requests

Following code describes the implementation of such servlet:

public class OlingoSpringServlet extends HttpServlet {
    private WebApplicationContext context;
    private ODataHttpHandler httpHandler;

    private ODataHttpHandler getHttpHandler() throws ServletException {
        Map<String, ODataHttpHandler> odatas = context
        if (odatas.size() == 1) {
            return odatas.values().iterator().next();

        throw new ServletException(
            "No OData HTTP handler can be found in the Spring container.");

    private void initializeApplicationContext(ServletConfig config)
                                               throws ServletException {
        context = WebApplicationContextUtils.getWebApplicationContext(

        if (context==null) {
            throw new ServletException(
                "No Spring container is configured within the Web application.");

    public void init(ServletConfig config) throws ServletException {
        httpHandler = getHttpHandler();

    protected void service(HttpServletRequest req,
           HttpServletResponse resp) throws ServletException,
                       IOException {
        try {
            httpHandler.process(req, resp);
        } catch (RuntimeException e) {
            throw new ServletException(e);

At this point, we have all the Spring support for Olingo implemented. Before finishing this post, we will describe how to use it within a Web application.

Using the namespace

To use the namespace, we need first to configure the Spring XML context with the file web.xml. The listener can be used for this. Our Spring-based servlet for Olingo can be then configured.

Following code describes the complete configuration within this file:

<web-app (...) id="OlingoWebApp" version="2.5">
    <display-name>Apache Olingo Spring</display-name>

As you can see the Spring configuration will be contained in the file applicationContext-namespace.xml located in the folder WEB-INF. The first thing to do in this file is to define our namespace within the root XML element beans, as described below:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""

Now this done, we can use the XML namespace olingo to configure the Olingo HTTP handle.

<beans (...)>
    <olingo:http-handler id="httpHandler" edm-provider="edmProvider">
        <olingo:reference uri="../v4.0/cs02/vocabularies/Org.OData.Core.V1.xml">
            <olingo:include key="Org.OData.Core.V1" value="Core"/>
        <olingo:processor ref="testProcessor"/>

    <bean id="edmProvider" class="org.apache.olingo.spring.edm.GenericEdmProvider" />

    <bean id="testProcessor" class="org.apache.olingo.spring.config.TestProcessor" />

We dont but the Spring Olingo support also provides a convenient way to configure an EDM provider using the Spring XML configuration:

<beans (...)>
    <olingo:edm-provider id="edmProvider">
        <olingo:schema namespace="mynamespace" alias="myalias">
                <olingo:entitySet name="books" type="books"/>
            <olingo:entityType name="sources1">
                <olingo:key property-name="id"/>
                <olingo:property name="id" type="Edm.Int32"/>
                <olingo:property name="name" type="Edm.String"/>
                <olingo:property name="genre" type="Edm.String"/>
                <olingo:property name="publisher" type="Edm.String"/>

This entry was posted in Olingo, Spring and tagged , , , , . Bookmark the permalink.

2 Responses to Implementing a Spring custom namespace for Olingo

  1. Babra says:

    There is no “org.apache.olingo.spring” package in official olingo distribution at Where can we get all these classes mentioned in the article?

    • templth says:

      Yes, this is part of a contribution (see issue OLINGO-562 in the Olingo JIRA). The corresponding code is in attachment in the issue. Note that I’ll provide soon a new version with more unit tests

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s