01 November 2008 ~ 16 Comments

Integrating Apache MINA with Spring



So far we have seen Apache MINA code samples in standalone form. Apache MINA can be nicely integrated into DI frameworks like Spring. Lets see how to integrate a simple MINA application with Spring

This is how our application is structure. To see details of this application, please refer to the post Implementing Trap Receiver in 30 minutes using Apache MINA

To integrate with Spring, we need to do following

  • One Handler
  • Two Filter – Logging Filter and a ProtocolCodec Filter
  • NioDatagram Socket

This is how our code looks like for the standalone application

  1. public void initialize() throws IOException {
  2.  
  3. // Create an Acceptor
  4. NioDatagramAcceptor acceptor = new NioDatagramAcceptor();
  5.  
  6. // Add Handler
  7. acceptor.setHandler(new ServerHandler());
  8.  
  9. acceptor.getFilterChain().addLast("logging",
  10. new LoggingFilter());
  11. acceptor.getFilterChain().addLast("codec",
  12. new ProtocolCodecFilter(new SNMPCodecFactory()));
  13.  
  14. // Create Session Configuration
  15. DatagramSessionConfig dcfg = acceptor.getSessionConfig();
  16. dcfg.setReuseAddress(true);
  17. logger.debug("Starting Server......");
  18. // Bind and be ready to listen
  19. acceptor.bind(new InetSocketAddress(DEFAULT_PORT));
  20. logger.debug("Server listening on "+DEFAULT_PORT);
  21. }

To integrate with Spring, we need to do following

  1. Set the IO handler
  2. Create the Filters and add to the chain
  3. Create the Socket and set Socket Parameters

NOTE: The latest MINA releases doesn’t have the package specific to Spring, like its earlier versions. The package is now named Integration Beans, to make the implementation work for all DI frameworks.

Lets see the Spring xml file. Please see that I have removed generic part from xml and have put only the specific things needed to pull up the implementation. This example has been derived from Chat example shipped with MINA release.

Now lets pull things together

  1. Lets set the IO Handler

  2. Lets create the Filter chain
  3. Here, we create instance of our IoFilter. See that for the ProtocolCodec factory, we have used Constructor injection. Logging Filter creation is straight forward. Once we have defined the beans for the filters to be used, we now create the Filter Chain to be used for the implementation. We define a bean with id “FilterChainBuidler” and add the defined filters to it. We are almost ready, and we just need to create the Socket and call bind

  4. Lets complete the last part of creating the Socket and completing the chain

Now we create our ioAcceptor, set IO handler and Filter Chain. Now we have to write a function to read this file using Spring and start our application. Here’s the code

  1. public void initializeViaSpring() throws Exception {
  2. new ClassPathXmlApplicationContext("trapReceiverContext.xml");
  3. }

We just call this method from main, and this shall initialize our MINA application. Will try to write a post using some other DI framework like Google Guice.

Reference:


16 Responses to “Integrating Apache MINA with Spring”

  1. Mike 4 November 2008 at 8:18 pm Permalink

    Thanks for this example. It was invaluable in porting my mina-1.1.7 spring configuration over to 2.0.

  2. Declan 10 December 2008 at 11:43 pm Permalink

    Hi Ashish,
    Thanks for the example. One question that has been vexing me for the past while that you may know the answer to. Do you know why the reuseAddress session config parameter no longer exposed when configuring an NioDatagramConnector/Acceptor ? Of course it is possible to set it programmatically by getting a hold of the DatagramSessionConfig from the acceptor/connector once created, however it makes it awkward from a spring config point of view.

    Thanks,
    Declan.

  3. ashish 13 December 2008 at 8:00 am Permalink

    To be true, I don’t have an answer right now. Let me check and get back to you.

  4. serge 26 February 2009 at 11:31 pm Permalink

    Hi Ashish

    We need the chain filters in a certain order, so a Map is not appropriate !

    By.

  5. Les Hazlewood 21 October 2009 at 2:28 am Permalink

    @serge

    You don’t need to worry about this – Spring uses a LinkedHashMap implementation for map definitions by default which does retain definition order.

    – Les

  6. Les Hazlewood 22 October 2009 at 4:15 am Permalink

    @Declan and Ashish,

    Spring supports nested property configuration by using OGNL path expressions. For example, if you wanted to change the ‘tcpNoDelay’ property of the NioSocketAcceptor’s nested SessionConfig instance:

    Naturally the default,no-arg constructor of whatever bean you’re instantiating must ensure that any beans referenced via a OGNL expression are non-null (the NioSocketAcceptor does indeed ensure this for its internal SessionConfig instance). No coding necessary :)

    Using the nested property technique above, I think you can easily satisfy almost all of your Mina Spring-configuration needs.

    Here is the Spring doco reference:

    http://static.springsource.org/spring/docs/2.5.x/reference/beans.html#beans-compound-property-names

    Regards,

    Les

  7. Les Hazlewood 22 October 2009 at 4:18 am Permalink

    Oops – my XML example didn’t show correctly. Let’s try again with brackets instead:

    [bean class=”org.apache.mina.transport.socket.nio.NioSocketAcceptor”
    init-method=”bind” destroy-method=”unbind”/]

    [property name=”sessionConfig.tcpNoDelay” value=”true”/]

    [/bean]

    Ashish, please feel free to edit/consolidate my comments so this shows proper XML if you have the ability to do so.

    Regards,

    Les

  8. Marek Šabo 28 October 2010 at 5:55 am Permalink

    I see this is an old post but nevertheless, would it be possible to provide a simple example how to integrate mina app with webbap using guice so it would run on tomcat? Webapp already uses guice and as author suggested he could write a howto – I would very much appreciate just the vital example of it.

    Regards,

    • ashish 28 October 2010 at 9:30 am Permalink

      A good suggestion. Its been on my to-do list for long, let me see how soon can I make it to MINA User Guide

  9. ilango 23 November 2010 at 8:01 pm Permalink

    I was wondering if it might be possible to integrate the above code into a Spring based MVC webapp running on Tomcat or websphere
    Great article. Thanks.

  10. Sajjad 11 July 2011 at 4:36 pm Permalink

    Is it possible to use spring security while TCP/IP commnuication using MINA, if yes then how ? please help me.

    • ashish 11 July 2011 at 4:41 pm Permalink

      I have no clue how this can be done. Probably you need to implement a IoFilter that does the job for you, by integrating with Spring security API’s. Or look at existing integrations and tweak them to use your IoFilter.

      Please do share your findings.

      Good Luck !

  11. Vid 17 April 2012 at 10:44 am Permalink

    Hi,

    I am unable to find example with SocketConnector with Spring. What would it look like?

    Kind regards,
    -Vid-

  12. LuoPei 27 September 2013 at 11:20 am Permalink

    If I want add ExecutorFilter to FilterChainBuidler, how to write it in spring.xml file?

  13. Ker 6 August 2014 at 8:47 am Permalink

    what version of slf4j and logback are you using?

  14. Ker 6 August 2014 at 9:07 am Permalink

    do you have the client side configuration using mina and spring?


Leave a Reply