<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Ashish's Tech Blog &#187; Apache MINA</title>
	<atom:link href="http://www.ashishpaliwal.com/blog/tag/apache-mina/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.ashishpaliwal.com/blog</link>
	<description>From Programmer, For Programmers</description>
	<lastBuildDate>Tue, 17 Aug 2010 12:04:43 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Using Auto expanding and shrinking IoBuffer in Apache MINA</title>
		<link>http://www.ashishpaliwal.com/blog/2008/12/using-auto-expanding-and-shrinking-iobuffer-in-apache-mina/</link>
		<comments>http://www.ashishpaliwal.com/blog/2008/12/using-auto-expanding-and-shrinking-iobuffer-in-apache-mina/#comments</comments>
		<pubDate>Tue, 09 Dec 2008 13:37:32 +0000</pubDate>
		<dc:creator>ashish</dc:creator>
				<category><![CDATA[Apache MINA]]></category>
		<category><![CDATA[IoBuffer]]></category>

		<guid isPermaLink="false">http://www.ashishpaliwal.com/blog/?p=224</guid>
		<description><![CDATA[Networking applications always need ByteBuffer that can expand on the need basis. Java ByteBuffer doesn’t provide this feature. Fortunately, MINA’s IoBuffer class has implemented this much needed feature. Creating Auto Expanding Buffer IoBuffer class in MINA has a property autoExpand, which when set makes the IoBuffer expand on the need basis, very much similar to [...]]]></description>
			<content:encoded><![CDATA[<p>Networking applications always need ByteBuffer that can expand on the need basis. Java ByteBuffer doesn’t provide this feature. Fortunately, MINA’s IoBuffer class has implemented this much needed feature.</p>
<p><strong>Creating Auto Expanding Buffer</strong></p>
<p>IoBuffer class in MINA has a property autoExpand, which when set makes the IoBuffer expand on the need basis, very much similar to StringBuffer class.<br />
Let’s see, how we can achieve this</p>
<pre class="java5">&nbsp;
IoBuffer buffer = IoBuffer.<span style="color: #006600;">allocate</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">8</span><span style="color: #66cc66;">&#41;</span>;
buffer.<span style="color: #006600;">setAutoExpand</span><span style="color: #66cc66;">&#40;</span><span style="color: #b13366;">true</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
buffer.<span style="color: #006600;">putString</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;12345678&quot;</span>, encoder<span style="color: #66cc66;">&#41;</span>;
<span style="color: #808080; font-style: italic;">// Add more to this buffer</span>
buffer.<span style="color: #006600;">put</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#40;</span><span style="color: #993333;">byte</span><span style="color: #66cc66;">&#41;</span><span style="color: #cc66cc;">10</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>When we set this property, the buffer will expand as and when needed. Under the hood, it essentially allocated a new IoBuffer and returns the new instance with the copied data.</p>
<p>So, can we shrink the buffer as well. Yes, if we set the autoshrink property to true.</p>
<pre class="java5">&nbsp;
IoBuffer buffer = IoBuffer.<span style="color: #006600;">allocate</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">8</span><span style="color: #66cc66;">&#41;</span>;
buffer.<span style="color: #006600;">setAutoShrink</span><span style="color: #66cc66;">&#40;</span><span style="color: #b13366;">true</span><span style="color: #66cc66;">&#41;</span>;
buffer.<span style="color: #006600;">put</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#40;</span><span style="color: #993333;">byte</span><span style="color: #66cc66;">&#41;</span><span style="color: #cc66cc;">7</span><span style="color: #66cc66;">&#41;</span>;
<a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/System.html"><span style="color: #aaaadd; font-weight: bold;">System</span></a>.<span style="color: #006600;">out</span>.<span style="color: #006600;">println</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Buffer size = &quot;</span>+buffer.<span style="color: #006600;">capacity</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
buffer.<span style="color: #006600;">shrink</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
buffer.<span style="color: #006600;">capacity</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">16</span><span style="color: #66cc66;">&#41;</span>;
<a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/System.html"><span style="color: #aaaadd; font-weight: bold;">System</span></a>.<span style="color: #006600;">out</span>.<span style="color: #006600;">println</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Buffer size = &quot;</span>+buffer.<span style="color: #006600;">capacity</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
buffer.<span style="color: #006600;">shrink</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
<a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/System.html"><span style="color: #aaaadd; font-weight: bold;">System</span></a>.<span style="color: #006600;">out</span>.<span style="color: #006600;">println</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Buffer size = &quot;</span>+buffer.<span style="color: #006600;">capacity</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>Here we set autoShrink property to true. To manually shrink the capacity, we use shrink() method. Caution, shrink(), won’t reduce capacity below the minimum capacity (the capacity with which the buffer was created). The second call to shrink(), will reduce the capacity to 8.</p>
<p>Has updated the MINA’s documentation page on IoBuffer today. So please feel free to find more details <a href="http://mina.apache.org/iobuffer.html">here</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.ashishpaliwal.com/blog/2008/12/using-auto-expanding-and-shrinking-iobuffer-in-apache-mina/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How I learned Apache MINA internal?</title>
		<link>http://www.ashishpaliwal.com/blog/2008/12/how-i-learned-apache-mina-internal/</link>
		<comments>http://www.ashishpaliwal.com/blog/2008/12/how-i-learned-apache-mina-internal/#comments</comments>
		<pubDate>Thu, 04 Dec 2008 02:58:08 +0000</pubDate>
		<dc:creator>ashish</dc:creator>
				<category><![CDATA[Apache MINA]]></category>

		<guid isPermaLink="false">http://www.ashishpaliwal.com/blog/?p=220</guid>
		<description><![CDATA[This is a very short post. The idea was to share how I learned some basic things about Apache MINA. LoggingFilter provides a very good way of how MINA process a incoming requests. Add the LoggingFilter in the chain and enable logging. As soon as it receives a packet, watch out the logs, it provides [...]]]></description>
			<content:encoded><![CDATA[<p>This is a very short post. The idea was to share how I learned some basic things about Apache MINA. LoggingFilter provides a very good way of how MINA process a incoming requests. Add the LoggingFilter in the chain and enable logging. As soon as it receives a packet, watch out the logs, it provides enough details on what is going around inside the framework. Believe it or not, I learned a lot of internals using this filter.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.ashishpaliwal.com/blog/2008/12/how-i-learned-apache-mina-internal/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Apache MINA – Blacklist Filter Explained</title>
		<link>http://www.ashishpaliwal.com/blog/2008/11/apache-mina-%e2%80%93-blacklist-filter-explained/</link>
		<comments>http://www.ashishpaliwal.com/blog/2008/11/apache-mina-%e2%80%93-blacklist-filter-explained/#comments</comments>
		<pubDate>Fri, 21 Nov 2008 11:26:28 +0000</pubDate>
		<dc:creator>ashish</dc:creator>
				<category><![CDATA[Apache MINA]]></category>
		<category><![CDATA[Blacklist Filter]]></category>

		<guid isPermaLink="false">http://www.ashishpaliwal.com/blog/?p=214</guid>
		<description><![CDATA[Blacklist filter blocks connections from the blacklisted remote Addresses. The filter is very useful, for dropping the connection originating from addresses, not of interest. Useful API’s setBlacklist(InetAddress[] addresses) – Sets a list of IP Addresses that needs to be blocked. This API call clears all the previously added Addresses setSubnetBlacklist(Subnet[] subnets) – Sets a List [...]]]></description>
			<content:encoded><![CDATA[<p>Blacklist filter blocks connections from the blacklisted remote Addresses. The filter is very useful, for dropping the connection originating from addresses, not of interest.</p>
<p class="MsoNormal"><strong><span style="text-decoration: underline;">Useful API’</span></strong><strong><span style="text-decoration: underline;">s</span></strong></p>
<p class="MsoNormal"><em><strong>setBlacklist(InetAddress[] addresses)</strong></em> – Sets a list of IP Addresses that needs to be blocked. This API call clears all the previously added Addresses</p>
<p class="MsoNormal"><strong><em>setSubnetBlacklist(Subnet[] subnets)</em></strong> – Sets a List of Subnets to be blocked. This API call clears all the previously added Addresses</p>
<p class="MsoNormal"><em><strong>setBlacklist(Iterable&lt;InetAddress&gt; addresses)</strong></em> – Sets a list of IP Addresses that needs to be blocked. This API call clears all the previously added Addresses</p>
<p class="MsoNormal"><strong><em>setSubnetBlacklist(Iterable&lt;Subnet&gt; subnets)</em></strong> - Sets a List of Subnets to be blocked. This API call clears all the previously added Addresses</p>
<p class="MsoNormal"><em><strong>block(InetAddress address)</strong></em><span> </span>- Adds a remote address to the blacklist</p>
<p class="MsoNormal"><em><strong>block(Subnet subnet)</strong></em> – Adds a Subnet to be blocked</p>
<p class="MsoNormal"><strong><em>unblock(InetAddress address)</em></strong> – Removes remote address from the blacklist</p>
<p class="MsoNormal"><em><strong>unblock(Subnet subnet)</strong></em> – Removes a Subnet from the blacklist</p>
<p class="MsoNormal"><strong><span style="text-decoration: underline;">Under the Hood</span></strong></p>
<p class="MsoNormal">For each of the events, the Filter checks for the remote address, in the blacklisted Address. If found, the session is closed. The isBlocked() API, checks for the remote address in the configured list and returns true if found.</p>
<p class="MsoNormal"> </p>
<div id="attachment_215" class="wp-caption aligncenter" style="width: 509px"><a href="http://www.ashishpaliwal.com/blog/wp-content/uploads/2008/11/blacklistfilter.png"><img class="size-full wp-image-215" title="blacklistfilter" src="http://www.ashishpaliwal.com/blog/wp-content/uploads/2008/11/blacklistfilter.png" alt="Blacklist Filter" width="499" height="357" /></a><p class="wp-caption-text">Blacklist Filter</p></div>
<p class="MsoNormal"><strong><span style="text-decoration: underline;">How to Use Blacklist Filter</span></strong></p>
<p class="MsoNormal">To use a blacklist filter, we need to follow some simple steps listed below</p>
<ul>
<li>Create an instance of Blacklist filter</li>
<li>Add IP Addresses/Subnets to be blacklisted</li>
<li>Add the Backlist filter to the Filter chain</li>
</ul>
<p><strong><span style="text-decoration: underline;">Code Snippet</span></strong></p>
<pre class="java5"><span style="color: #000000; font-weight: bold;">public</span> BlacklistFilter createBlacklistFilter<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <a href="http://www.google.com/search?sitesearch=java.sun.com&amp;q=allinurl%3Aj2se%2F1+5+0%2Fdocs%2Fapi+UnknownHostException"><span style="color: #aaaadd; font-weight: bold;">UnknownHostException</span></a> <span style="color: #66cc66;">&#123;</span>
        BlacklistFilter filter = <span style="color: #000000; font-weight: bold;">new</span> BlacklistFilter<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
        <span style="color: #808080; font-style: italic;">// Get the IP Addresses to be blocked</span>
        <span style="color: #808080; font-style: italic;">// from a config file or from DB, whatever</span>
        <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/net/InetAddress.html"><span style="color: #aaaadd; font-weight: bold;">InetAddress</span></a><span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span> blockedAddresses = <span style="color: #b13366;">null</span>;
&nbsp;
        <span style="color: #808080; font-style: italic;">// populate the list</span>
        <span style="color: #808080; font-style: italic;">// Ensure that the list if populated correctly as per requirement</span>
        blockedAddresses = <span style="color: #000000; font-weight: bold;">new</span> <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/net/InetAddress.html"><span style="color: #aaaadd; font-weight: bold;">InetAddress</span></a><span style="color: #66cc66;">&#91;</span><span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#93;</span>;
&nbsp;
        <span style="color: #808080; font-style: italic;">// block all connection from Localhost</span>
        blockedAddresses<span style="color: #66cc66;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#93;</span> = <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/net/InetAddress.html"><span style="color: #aaaadd; font-weight: bold;">InetAddress</span></a>.<span style="color: #006600;">getByName</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;127.0.0.1&quot;</span><span style="color: #66cc66;">&#41;</span>;
        filter.<span style="color: #006600;">setBlacklist</span><span style="color: #66cc66;">&#40;</span>blockedAddresses<span style="color: #66cc66;">&#41;</span>;
&nbsp;
        <span style="color: #000000; font-weight: bold;">return</span> filter;
    <span style="color: #66cc66;">&#125;</span></pre>
<p>The code is fairly straight forward. We create an instance of Blacklist Filter and add the list of Addresses to be blocked. Then we need to add the Filter instance in the Filter chain of our implementation.</p>
<p><strong><span style="text-decoration: underline;">Usage Scenario’s</span></strong></p>
<ul>
<li>Conditionally allow traffic from only selected sources</li>
</ul>
<p class="MsoNormal"><em>Think Differently</em> <img src='http://www.ashishpaliwal.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<ul>
<li>The default MINA implementation stores the blacklisted Addresses in a List, Custom data structure can be used to speed up search</li>
<li>Can extend the Filter’s functionality to allow traffic only from selected sources.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.ashishpaliwal.com/blog/2008/11/apache-mina-%e2%80%93-blacklist-filter-explained/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Apache MINA &#8211; CumulativeProtocolDecoder Explained</title>
		<link>http://www.ashishpaliwal.com/blog/2008/11/apache-mina-cumulativeprotocoldecoder-explained/</link>
		<comments>http://www.ashishpaliwal.com/blog/2008/11/apache-mina-cumulativeprotocoldecoder-explained/#comments</comments>
		<pubDate>Sat, 08 Nov 2008 15:37:32 +0000</pubDate>
		<dc:creator>ashish</dc:creator>
				<category><![CDATA[Apache MINA]]></category>
		<category><![CDATA[CumulativeProtocolDecoder]]></category>

		<guid isPermaLink="false">http://www.ashishpaliwal.com/blog/?p=211</guid>
		<description><![CDATA[Apache MINA uses the concept of Protocol Decoder to decoder read bytes into High Level Message objects. There are conditions in which a single packet may not contain the complete bytes to convert raw message into High Level Objects. For such situations, CumulativeProtocolDecoder can be used. Basically, encoder makes the framework buffer the data, till [...]]]></description>
			<content:encoded><![CDATA[<p>Apache MINA uses the concept of Protocol Decoder to decoder read bytes into High Level Message objects. There are conditions in which a single packet may not contain the complete bytes to convert raw message into High Level Objects. For such situations, <em>CumulativeProtocolDecoder</em> can be used. Basically, encoder makes the framework buffer the data, till the complete data is received, to convert the byte[] into a high level object.</p>
<p>So, how do we use this Decoder</p>
<p>Extend from the class <em>CumulativeProtocolDecoder</em> and implement the <em>doDecode()</em>.</p>
<p>Conditions to take care of</p>
<ol>
<li>read the IoBuffer and decode as per yur logic</li>
<li>If the data is sufficient to create your message, return true, else return false</li>
</ol>
<div><strong><span style="text-decoration: underline;">Under the Hood</span></strong></div>
<div>The magic lies in the asbtract class CumulativeProtocolDecoder, which internally buffer the data and keep on calling our doDecoder(). Based on the return type from doDecode(), it either keeps buffering or allows the framework to call next filter in the chain.</div>
<div>Implementation of CumulativeProtocolDecoder can be seen in detail in the following post</div>
<div><a title="Permanent Link: Implementing XML Decoder for Apache MINA" rel="bookmark" href="http://www.ashishpaliwal.com/blog/2008/10/implementing-xml-decoder-for-apache-mina/">Implementing XML Decoder for Apache MINA</a></div>
]]></content:encoded>
			<wfw:commentRss>http://www.ashishpaliwal.com/blog/2008/11/apache-mina-cumulativeprotocoldecoder-explained/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Integrating Apache MINA with Spring</title>
		<link>http://www.ashishpaliwal.com/blog/2008/11/integrating-apache-mina-with-spring/</link>
		<comments>http://www.ashishpaliwal.com/blog/2008/11/integrating-apache-mina-with-spring/#comments</comments>
		<pubDate>Sat, 01 Nov 2008 12:10:15 +0000</pubDate>
		<dc:creator>ashish</dc:creator>
				<category><![CDATA[Apache MINA]]></category>
		<category><![CDATA[Spring]]></category>

		<guid isPermaLink="false">http://www.ashishpaliwal.com/blog/?p=198</guid>
		<description><![CDATA[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 [...]]]></description>
			<content:encoded><![CDATA[<p class="MsoNormal">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</p>
<p class="MsoNormal">This is how our application is structure. To see details of this application, please refer to the post <a href="http://www.ashishpaliwal.com/blog/2008/10/implementing-trap-receiver-in-30-minutes-using-apache-mina/">Implementing Trap Receiver in 30 minutes using Apache MINA</a></p>
<p>To integrate with Spring, we need to do following</p>
<ul>
<li>One Handler</li>
<li>Two Filter – Logging Filter and a ProtocolCodec Filter</li>
<li>NioDatagram Socket</li>
</ul>
<p class="MsoNormal">This is how our code looks like for the standalone application</p>
<pre class="java5"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> initialize<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/io/IOException.html"><span style="color: #aaaadd; font-weight: bold;">IOException</span></a> <span style="color: #66cc66;">&#123;</span>
&nbsp;
	<span style="color: #808080; font-style: italic;">// Create an Acceptor</span>
	NioDatagramAcceptor acceptor = <span style="color: #000000; font-weight: bold;">new</span> NioDatagramAcceptor<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
	<span style="color: #808080; font-style: italic;">// Add Handler</span>
	acceptor.<span style="color: #006600;">setHandler</span><span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> ServerHandler<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
	acceptor.<span style="color: #006600;">getFilterChain</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">addLast</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;logging&quot;</span>,
				<span style="color: #000000; font-weight: bold;">new</span> LoggingFilter<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
	acceptor.<span style="color: #006600;">getFilterChain</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">addLast</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;codec&quot;</span>,
				<span style="color: #000000; font-weight: bold;">new</span> ProtocolCodecFilter<span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> SNMPCodecFactory<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
	<span style="color: #808080; font-style: italic;">// Create Session Configuration</span>
	DatagramSessionConfig dcfg = acceptor.<span style="color: #006600;">getSessionConfig</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
        dcfg.<span style="color: #006600;">setReuseAddress</span><span style="color: #66cc66;">&#40;</span><span style="color: #b13366;">true</span><span style="color: #66cc66;">&#41;</span>;
        logger.<span style="color: #006600;">debug</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Starting Server......&quot;</span><span style="color: #66cc66;">&#41;</span>;
        <span style="color: #808080; font-style: italic;">// Bind and be ready to listen</span>
        acceptor.<span style="color: #006600;">bind</span><span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/net/InetSocketAddress.html"><span style="color: #aaaadd; font-weight: bold;">InetSocketAddress</span></a><span style="color: #66cc66;">&#40;</span>DEFAULT_PORT<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
        logger.<span style="color: #006600;">debug</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Server listening on &quot;</span>+DEFAULT_PORT<span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span></pre>
<p>To integrate with Spring, we need to do following</p>
<ol>
<li>Set the IO handler</li>
<li>Create the Filters and add to the chain</li>
<li>Create the Socket and set Socket Parameters</li>
</ol>
<div>
<p class="MsoNormal">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.</p>
<p class="MsoNormal">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.</p>
<p class="MsoNormal">Now lets pull things together</p>
<ol type="1">
<li class="MsoNormal">Lets set the IO Handler</li>
<div><span style="text-decoration: underline;"><a href="http://www.ashishpaliwal.com/blog/wp-content/uploads/2008/11/filter.png"></a><a href="http://www.ashishpaliwal.com/blog/wp-content/uploads/2008/11/handler.png"><img class="size-full wp-image-201 aligncenter" title="handler" src="http://www.ashishpaliwal.com/blog/wp-content/uploads/2008/11/handler.png" alt="" width="500" height="25" /></a><br />
</span></div>
<li class="MsoNormal">Lets  create the Filter chain</li>
<p style="text-align: center;"><a href="http://www.ashishpaliwal.com/blog/wp-content/uploads/2008/11/filter1.png"><img class="size-full wp-image-202 aligncenter" title="filter1" src="http://www.ashishpaliwal.com/blog/wp-content/uploads/2008/11/filter1.png" alt="" width="500" height="155" /></a></p>
<p>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</p>
<li class="MsoNormal"><span>Lets complete the last part of creating the Socket and completing the chain</span><a href="http://www.ashishpaliwal.com/blog/wp-content/uploads/2008/11/acceptor.png"><img class="size-full wp-image-203 aligncenter" title="acceptor" src="http://www.ashishpaliwal.com/blog/wp-content/uploads/2008/11/acceptor.png" alt="" width="500" height="182" /></a></li>
</ol>
<p>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</p>
<pre class="java5"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> initializeViaSpring<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Exception.html"><span style="color: #aaaadd; font-weight: bold;">Exception</span></a> <span style="color: #66cc66;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">new</span> ClassPathXmlApplicationContext<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;trapReceiverContext.xml&quot;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span></pre>
<p>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.</p>
<p><strong><em>Reference:</em></strong></p>
<ul>
<li><a href="http://svn.apache.org/viewvc/mina/branches/1.0/example/src/main/java/org/apache/mina/example/chat/">Chat Server</a></li>
</ul>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.ashishpaliwal.com/blog/2008/11/integrating-apache-mina-with-spring/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Implementing XML Decoder for Apache MINA</title>
		<link>http://www.ashishpaliwal.com/blog/2008/10/implementing-xml-decoder-for-apache-mina/</link>
		<comments>http://www.ashishpaliwal.com/blog/2008/10/implementing-xml-decoder-for-apache-mina/#comments</comments>
		<pubDate>Fri, 31 Oct 2008 14:50:05 +0000</pubDate>
		<dc:creator>ashish</dc:creator>
				<category><![CDATA[Apache MINA]]></category>
		<category><![CDATA[XML Decoder]]></category>

		<guid isPermaLink="false">http://www.ashishpaliwal.com/blog/?p=187</guid>
		<description><![CDATA[Will continues to post articles about MINA, to be updated, Subscribe in a reader Apache MINA has wonderful concept of ProtocolDecoder to process Decoding protocol specific messages. XML is one of the most widely used format for EDA. Lets see how can we implement a Protocol Decoder for Apache MINA. Algorithm The picture below describes [...]]]></description>
			<content:encoded><![CDATA[<p>Will continues to post articles about MINA, to be updated, <a rel="alternate" type="application/rss+xml" href="http://feedproxy.google.com/AshishsTechBlog"><img style="vertical-align:middle;border:0" src="http://www.feedburner.com/fb/images/pub/feed-icon16x16.png" alt="" /></a> <a rel="alternate" type="application/rss+xml" href="http://feedproxy.google.com/AshishsTechBlog">Subscribe in a reader</a></p>
<p>Apache MINA has wonderful concept of ProtocolDecoder to process Decoding protocol specific messages. XML is one of the most widely used format for EDA. Lets see how can we implement a Protocol Decoder for Apache MINA.</p>
<p><strong>Algorithm</strong></p>
<p>The picture below describes the basic algorithm that we need to use to construct an XML message from bytes.</p>
<p> </p>
<p><a href="http://www.ashishpaliwal.com/blog/wp-content/uploads/2008/10/decoderalgo.png"><img class="aligncenter size-full wp-image-188" title="decoderalgo" src="http://www.ashishpaliwal.com/blog/wp-content/uploads/2008/10/decoderalgo.png" alt="" width="340" height="399" /></a></p>
<p>The logic is simple, keep reading the bytes till the XML message is balanced. Balanced here means, that end of the root element has been achieved. For eg. If the xml document has root element as , we have to read the bytes till we received .</p>
<p>Its very particular to note that large XML packets when sent over TCP, may get fragmented and we shall received the same amount of read events while using Apache MINA low level API’s.</p>
<p>This type of situations where, we need to wait to data to completely arrive, calls for the use of CumulativeProtocolDecoder. As the name signifies, the decoder waits till, we get the balanced xml. Once the balanced XML is found, we write the parsed object to the output, to be processed further.</p>
<p>Lets see the code. My apologies for the unformatted code <img src='http://www.ashishpaliwal.com/blog/wp-includes/images/smilies/icon_sad.gif' alt=':-(' class='wp-smiley' /> </p>
<pre class="java5"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">abstract</span> <span style="color: #000000; font-weight: bold;">class</span> <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/beans/XMLDecoder.html"><span style="color: #aaaadd; font-weight: bold;">XMLDecoder</span></a> <span style="color: #000000; font-weight: bold;">extends</span> CumulativeProtocolDecoder  <span style="color: #66cc66;">&#123;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">/*
* As per XML specification 1.0, http://www.w3.org/TR/REC-xml
*/</span>
<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #993333;">char</span> XML_START_TAG = <span style="color: #ff0000;">'&amp;lt;'</span>;
<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #993333;">char</span> XML_END_TAG = <span style="color: #ff0000;">'&amp;gt;'</span>;
<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #993333;">char</span> XML_PI_TAG = <span style="color: #ff0000;">'?'</span>;
<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #993333;">char</span> XML_COMMENT_TAG = <span style="color: #ff0000;">'!'</span>;
&nbsp;
<span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">enum</span> ParseState <span style="color: #66cc66;">&#123;</span>ELEMENT_START, ELEMENT_END, COMMENTS, ENDELEMENT, PI, UNDEFINED<span style="color: #66cc66;">&#125;</span>;
&nbsp;
<span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #993333;">int</span> ELEMENT_START = <span style="color: #cc66cc;">1</span>;
<span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #993333;">int</span> ELEMENT_END = <span style="color: #cc66cc;">2</span>;
&nbsp;
<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">static</span> <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/logging/Logger.html"><span style="color: #aaaadd; font-weight: bold;">Logger</span></a> logger = LoggerFactory.<span style="color: #006600;">getLogger</span><span style="color: #66cc66;">&#40;</span><a href="http://java.sun.com/j2se/1.5.0/docs/api/java/beans/XMLDecoder.html"><span style="color: #aaaadd; font-weight: bold;">XMLDecoder</span></a>.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
@<a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Override.html"><span style="color: #aaaadd; font-weight: bold;">Override</span></a>
<span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #993333;">boolean</span> doDecode<span style="color: #66cc66;">&#40;</span>IoSession session, IoBuffer ioBuffer,
ProtocolDecoderOutput decoderOutput<span style="color: #66cc66;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Exception.html"><span style="color: #aaaadd; font-weight: bold;">Exception</span></a> <span style="color: #66cc66;">&#123;</span>
&nbsp;
<span style="color: #993333;">int</span> startPosition = ioBuffer.<span style="color: #006600;">position</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
<span style="color: #b1b100;">if</span><span style="color: #66cc66;">&#40;</span>!ioBuffer.<span style="color: #006600;">hasRemaining</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
logger.<span style="color: #006600;">debug</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;NO bytes to read keep waiting...&quot;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #000000; font-weight: bold;">return</span> <span style="color: #b13366;">false</span>;
<span style="color: #66cc66;">&#125;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">// Continue to read the bytes and keep parsing</span>
<span style="color: #993333;">char</span> currentChar = <span style="color: #ff0000;">'0'</span>, previousChar = <span style="color: #ff0000;">'0'</span>;
&nbsp;
<span style="color: #993333;">boolean</span> rootElementStarted = <span style="color: #b13366;">false</span>;
<span style="color: #993333;">boolean</span> rootElementPresent = <span style="color: #b13366;">false</span>;
<span style="color: #993333;">boolean</span> isBalanced = <span style="color: #b13366;">false</span>;
&nbsp;
<span style="color: #993333;">int</span> rootStartPosition, rootEndPosition;
&nbsp;
ParseState parsingState = ParseState.<span style="color: #006600;">UNDEFINED</span>;
logger.<span style="color: #006600;">debug</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Lets start decoding the XML&quot;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
<a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html"><span style="color: #aaaadd; font-weight: bold;">String</span></a> root = <span style="color: #b13366;">null</span>;
&nbsp;
<span style="color: #993333;">boolean</span> markedForEndElement = <span style="color: #b13366;">false</span>;
&nbsp;
<span style="color: #b1b100;">while</span><span style="color: #66cc66;">&#40;</span>ioBuffer.<span style="color: #006600;">hasRemaining</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
previousChar = currentChar;
currentChar = <span style="color: #66cc66;">&#40;</span><span style="color: #993333;">char</span><span style="color: #66cc66;">&#41;</span>ioBuffer.<span style="color: #006600;">get</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
<span style="color: #b1b100;">switch</span> <span style="color: #66cc66;">&#40;</span>parsingState<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
<span style="color: #b1b100;">case</span> ELEMENT_START:
<span style="color: #b1b100;">if</span><span style="color: #66cc66;">&#40;</span>currentChar == XML_PI_TAG<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
logger.<span style="color: #006600;">debug</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Got PI Element&quot;</span><span style="color: #66cc66;">&#41;</span>;
parsingState = ParseState.<span style="color: #006600;">PI</span>;
<span style="color: #66cc66;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #b1b100;">if</span><span style="color: #66cc66;">&#40;</span>currentChar == XML_COMMENT_TAG<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
logger.<span style="color: #006600;">debug</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Got Comment Element&quot;</span><span style="color: #66cc66;">&#41;</span>;
parsingState = ParseState.<span style="color: #006600;">COMMENTS</span>;
<span style="color: #66cc66;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #b1b100;">if</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#40;</span>currentChar == <span style="color: #ff0000;">' '</span> || currentChar == XML_END_TAG<span style="color: #66cc66;">&#41;</span>
&amp;amp;&amp;amp; rootElementStarted &amp;amp;&amp;amp; !rootElementPresent<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
rootEndPosition = ioBuffer.<span style="color: #006600;">position</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
rootElementPresent = <span style="color: #b13366;">true</span>;
&nbsp;
<span style="color: #808080; font-style: italic;">// Copy the Root Element</span>
<span style="color: #993333;">int</span> cPos = ioBuffer.<span style="color: #006600;">position</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #993333;">int</span> mPos = ioBuffer.<span style="color: #006600;">markValue</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
<span style="color: #993333;">char</span><span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span> rootChar = <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #993333;">char</span><span style="color: #66cc66;">&#91;</span>cPos - mPos<span style="color: #66cc66;">&#93;</span>;
<span style="color: #b1b100;">for</span><span style="color: #66cc66;">&#40;</span><span style="color: #993333;">int</span> i = mPos - <span style="color: #cc66cc;">1</span>, j =<span style="color: #cc66cc;">0</span>; i &amp;lt; cPos - <span style="color: #cc66cc;">1</span>; i++<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
rootChar<span style="color: #66cc66;">&#91;</span>j++<span style="color: #66cc66;">&#93;</span> = <span style="color: #66cc66;">&#40;</span><span style="color: #993333;">char</span><span style="color: #66cc66;">&#41;</span>ioBuffer.<span style="color: #006600;">get</span><span style="color: #66cc66;">&#40;</span>i<span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span>
&nbsp;
root = <span style="color: #000000; font-weight: bold;">new</span> <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html"><span style="color: #aaaadd; font-weight: bold;">String</span></a><span style="color: #66cc66;">&#40;</span>rootChar<span style="color: #66cc66;">&#41;</span>;
logger.<span style="color: #006600;">debug</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Root Element = &quot;</span>+ root<span style="color: #66cc66;">&#41;</span>;
parsingState = ParseState.<span style="color: #006600;">ELEMENT_END</span>;
logger.<span style="color: #006600;">debug</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Root Element detection completed &quot;</span>+rootEndPosition<span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #b1b100;">if</span><span style="color: #66cc66;">&#40;</span>currentChar == XML_END_TAG<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
parsingState = ParseState.<span style="color: #006600;">ELEMENT_END</span>;
<span style="color: #66cc66;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #b1b100;">if</span><span style="color: #66cc66;">&#40;</span>!rootElementStarted &amp;amp;&amp;amp; !rootElementPresent<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
rootStartPosition = ioBuffer.<span style="color: #006600;">position</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
ioBuffer.<span style="color: #006600;">mark</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
rootElementStarted = <span style="color: #b13366;">true</span>;
logger.<span style="color: #006600;">debug</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Got the root element at &quot;</span>+rootStartPosition<span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>currentChar == <span style="color: #ff0000;">'/'</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
<span style="color: #808080; font-style: italic;">// Change state</span>
<span style="color: #b1b100;">if</span><span style="color: #66cc66;">&#40;</span>previousChar == XML_START_TAG<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
parsingState = ParseState.<span style="color: #006600;">ENDELEMENT</span>;
<span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>
<span style="color: #000000; font-weight: bold;">break</span>;
&nbsp;
<span style="color: #b1b100;">case</span> ENDELEMENT:
<span style="color: #b1b100;">if</span><span style="color: #66cc66;">&#40;</span>currentChar == XML_END_TAG<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
parsingState = ParseState.<span style="color: #006600;">ELEMENT_END</span>;
&nbsp;
<span style="color: #993333;">int</span> cPos = ioBuffer.<span style="color: #006600;">position</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #993333;">int</span> mPos = ioBuffer.<span style="color: #006600;">markValue</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
<span style="color: #993333;">char</span><span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span> el = <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #993333;">char</span><span style="color: #66cc66;">&#91;</span>cPos - mPos<span style="color: #66cc66;">&#93;</span>;
<span style="color: #b1b100;">for</span><span style="color: #66cc66;">&#40;</span><span style="color: #993333;">int</span> i = mPos - <span style="color: #cc66cc;">1</span>, j =<span style="color: #cc66cc;">0</span>; i &amp;lt; cPos - <span style="color: #cc66cc;">1</span>; i++<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
el<span style="color: #66cc66;">&#91;</span>j++<span style="color: #66cc66;">&#93;</span> = <span style="color: #66cc66;">&#40;</span><span style="color: #993333;">char</span><span style="color: #66cc66;">&#41;</span>ioBuffer.<span style="color: #006600;">get</span><span style="color: #66cc66;">&#40;</span>i<span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span>
markedForEndElement = <span style="color: #b13366;">false</span>;
<span style="color: #b1b100;">if</span><span style="color: #66cc66;">&#40;</span>root.<span style="color: #006600;">equalsIgnoreCase</span><span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html"><span style="color: #aaaadd; font-weight: bold;">String</span></a><span style="color: #66cc66;">&#40;</span>el<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
logger.<span style="color: #006600;">debug</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;XML is balanced.&quot;</span>+root<span style="color: #66cc66;">&#41;</span>;
isBalanced = <span style="color: #b13366;">true</span>;
<span style="color: #66cc66;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">break</span>;
<span style="color: #66cc66;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>currentChar == <span style="color: #ff0000;">' '</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
<span style="color: #000000; font-weight: bold;">continue</span>;
<span style="color: #66cc66;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #66cc66;">&#123;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">// mark the position, we need to compare the it to see that if its the end element</span>
<span style="color: #b1b100;">if</span><span style="color: #66cc66;">&#40;</span>!markedForEndElement<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
ioBuffer.<span style="color: #006600;">mark</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
markedForEndElement = <span style="color: #b13366;">true</span>;
<span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>
<span style="color: #000000; font-weight: bold;">break</span>;
&nbsp;
<span style="color: #b1b100;">case</span> ELEMENT_END:
<span style="color: #b1b100;">if</span><span style="color: #66cc66;">&#40;</span>currentChar == XML_START_TAG<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
parsingState = ParseState.<span style="color: #006600;">ELEMENT_START</span>;
<span style="color: #66cc66;">&#125;</span>
<span style="color: #000000; font-weight: bold;">break</span>;
&nbsp;
<span style="color: #b1b100;">case</span> UNDEFINED:
<span style="color: #b1b100;">if</span><span style="color: #66cc66;">&#40;</span>currentChar == XML_START_TAG<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
parsingState = ParseState.<span style="color: #006600;">ELEMENT_START</span>;
<span style="color: #66cc66;">&#125;</span>
<span style="color: #000000; font-weight: bold;">break</span>;
&nbsp;
<span style="color: #b1b100;">case</span> COMMENTS:
<span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>currentChar == <span style="color: #ff0000;">'-'</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
previousChar = currentChar;
<span style="color: #66cc66;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>previousChar == <span style="color: #ff0000;">'-'</span> &amp;amp;&amp;amp; currentChar == <span style="color: #ff0000;">'&amp;gt;'</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
parsingState = ParseState.<span style="color: #006600;">ELEMENT_END</span>;
<span style="color: #66cc66;">&#125;</span>
<span style="color: #000000; font-weight: bold;">break</span>;
&nbsp;
<span style="color: #b1b100;">case</span> PI:
<span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>currentChar == <span style="color: #ff0000;">'?'</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
previousChar = currentChar;
<span style="color: #66cc66;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>previousChar == <span style="color: #ff0000;">'?'</span> &amp;amp;&amp;amp; currentChar == XML_END_TAG<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
parsingState = ParseState.<span style="color: #006600;">ELEMENT_END</span>;
<span style="color: #66cc66;">&#125;</span>
<span style="color: #000000; font-weight: bold;">break</span>;
&nbsp;
<span style="color: #b1b100;">default</span>:
<span style="color: #000000; font-weight: bold;">break</span>;
<span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;
<span style="color: #b1b100;">if</span><span style="color: #66cc66;">&#40;</span>isBalanced<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
decoderOutput.<span style="color: #006600;">write</span><span style="color: #66cc66;">&#40;</span>parserXML<span style="color: #66cc66;">&#40;</span>ioBuffer<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span>
&nbsp;
<span style="color: #b1b100;">if</span><span style="color: #66cc66;">&#40;</span>isBalanced &amp;amp;&amp;amp; !ioBuffer.<span style="color: #006600;">hasRemaining</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
logger.<span style="color: #006600;">debug</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;No more bytes to process&quot;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #000000; font-weight: bold;">return</span> <span style="color: #b13366;">true</span>;
<span style="color: #66cc66;">&#125;</span>
&nbsp;
ioBuffer.<span style="color: #006600;">position</span><span style="color: #66cc66;">&#40;</span>startPosition<span style="color: #66cc66;">&#41;</span>;
<span style="color: #000000; font-weight: bold;">return</span> <span style="color: #b13366;">false</span>;
<span style="color: #66cc66;">&#125;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">/**
* Extending classes can implement their custom XML parsing to create Objects
* from XML and use them appropriately in Handler
*
* @param xmlBuffer
* @return
*/</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">abstract</span> <a href="http://www.google.com/search?sitesearch=java.sun.com&amp;q=allinurl%3Aj2se%2F1+5+0%2Fdocs%2Fapi+Object"><span style="color: #aaaadd; font-weight: bold;">Object</span></a> parserXML<span style="color: #66cc66;">&#40;</span>IoBuffer xmlBuffer<span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span></pre>
<p>The implementation is pretty straight forward. We take each character and try to match the characters as specified in XML specification.</p>
<p><strong>Some keys things in the implementation:</strong><br />
1.	The Decode function just collects the bytes till we get the balanced XML document<br />
2.	Once we get the balanced XML document, we shall call the abstract function parseXML(). The function has been kept abstract, so that its easy to implement custom parsing using desired XML library like JAXB, JIBX etc<br />
3.	We have to return true from doDecode(), the moment we have balanced XML. Return type true indicates to the framework that we are not waiting for any more data. A false, forces the framework to keep accumulating the data, till we write it to the output. Now it must be clear why, its called Cumulative decoder.</p>
<p>Still have Queries, please leave a comment and I shall revert back to you.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.ashishpaliwal.com/blog/2008/10/implementing-xml-decoder-for-apache-mina/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Implementing Trap Sender using SNMP4J</title>
		<link>http://www.ashishpaliwal.com/blog/2008/10/implementing-trap-sender-using-snmp4j/</link>
		<comments>http://www.ashishpaliwal.com/blog/2008/10/implementing-trap-sender-using-snmp4j/#comments</comments>
		<pubDate>Tue, 28 Oct 2008 06:56:06 +0000</pubDate>
		<dc:creator>ashish</dc:creator>
				<category><![CDATA[Application Programming]]></category>
		<category><![CDATA[Network Programming]]></category>
		<category><![CDATA[Apache MINA]]></category>
		<category><![CDATA[SMP]]></category>
		<category><![CDATA[SNMP4J]]></category>
		<category><![CDATA[Trap Sender]]></category>

		<guid isPermaLink="false">http://www.ashishpaliwal.com/blog/?p=176</guid>
		<description><![CDATA[In this post, we shall implement a Trap Sender using SNMP4J. We may choose to use Apache MINA for sending Traps or can resort to using DatagramSocket class directly. This shall be the logical flow of the implementation Get the encoded Trap Data Send the Trap  Lets look at the first component, on getting the [...]]]></description>
			<content:encoded><![CDATA[<p>In this post, we shall implement a Trap Sender using SNMP4J. We may choose to use Apache MINA for sending Traps or can resort to using DatagramSocket class directly.</p>
<p>This shall be the logical flow of the implementation</p>
<ul>
<li>Get the encoded Trap Data</li>
<li>Send the Trap </li>
</ul>
<div>Lets look at the first component, on getting the encoded Trap data</div>
<p> </p>
<div><a href="http://www.ashishpaliwal.com/blog/wp-content/uploads/2008/10/trapdata.png"><img class="aligncenter size-full wp-image-178" title="trapdata" src="http://www.ashishpaliwal.com/blog/wp-content/uploads/2008/10/trapdata.png" alt="" width="500" height="224" /></a></div>
<p>The code snippet above shows a simple way of creating and encoding a Trap PDU. Essentially, we create an instance of PDU class and sets the type as Trap. This is important, else SNMP4J shall throw an exception. Thereafter, we can set the trap parameters. Here, we have hardcoded the parameters, there can be custom implementations that can take these from config files or from UI. After setting the parameters, we just call the encode function passing the Output stream and collect the byte array to be sent.</p>
<div>Sending part is even simpler     </p>
<div><a href="http://www.ashishpaliwal.com/blog/wp-content/uploads/2008/10/sendtrap.png"><img class="aligncenter size-full wp-image-179" title="sendtrap" src="http://www.ashishpaliwal.com/blog/wp-content/uploads/2008/10/sendtrap.png" alt="" width="500" height="83" /></a></div>
<p><script type="text/javascript"><!--
google_ad_client = "pub-6961884887741817";
/* 468x15LinkUnit */
google_ad_slot = "4400881690";
google_ad_width = 468;
google_ad_height = 15;
// --></script><br />
<script src="http://pagead2.googlesyndication.com/pagead/show_ads.js" type="text/javascript"></script></p>
<p>The send code is preety straight forward. Here we have used Datagram Socket, we can use Apache MINA UDP Client implementation to send the trap as well.</p>
<div>References</div>
<div>
<ul>
<li><a href="http://www.snmp4j.org/">http://www.snmp4j.org/</a></li>
<li><a href="http://www.ashishpaliwal.com/blog/2008/10/implementing-udp-client-using-apache-mina/">Implementing UDP Client using Apache MINA</a> </li>
</ul>
</div>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.ashishpaliwal.com/blog/2008/10/implementing-trap-sender-using-snmp4j/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Implementing Trap Receiver in 30 minutes using Apache MINA</title>
		<link>http://www.ashishpaliwal.com/blog/2008/10/implementing-trap-receiver-in-30-minutes-using-apache-mina/</link>
		<comments>http://www.ashishpaliwal.com/blog/2008/10/implementing-trap-receiver-in-30-minutes-using-apache-mina/#comments</comments>
		<pubDate>Wed, 22 Oct 2008 10:24:26 +0000</pubDate>
		<dc:creator>ashish</dc:creator>
				<category><![CDATA[Apache MINA]]></category>
		<category><![CDATA[Network Programming]]></category>
		<category><![CDATA[How-to]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Trap Receiver]]></category>

		<guid isPermaLink="false">http://www.ashishpaliwal.com/blog/?p=157</guid>
		<description><![CDATA[Will continues to post articles about MINA, to be updated,  Subscribe in a reader Yes, we are going to implement a SNMP trap receiver in less than 30 minutes. If you have been following my post on Apache MINA, this would be a natural extension to it. In this article, we shall bring together all [...]]]></description>
			<content:encoded><![CDATA[<p><script type="text/javascript"><!--
google_ad_client = "pub-6961884887741817";
/* 468x15LinkUnit */
google_ad_slot = "4400881690";
google_ad_width = 468;
google_ad_height = 15;
// --></script><br />
<script src="http://pagead2.googlesyndication.com/pagead/show_ads.js" type="text/javascript"></script></p>
<p>Will continues to post articles about MINA, to be updated, <a rel="alternate" type="application/rss+xml" href="http://feedproxy.google.com/AshishsTechBlog"><img style="vertical-align:middle;border:0" src="http://www.feedburner.com/fb/images/pub/feed-icon16x16.png" alt="" /></a> <a rel="alternate" type="application/rss+xml" href="http://feedproxy.google.com/AshishsTechBlog">Subscribe in a reader</a></p>
<p>Yes, we are going to implement a SNMP trap receiver in less than 30 minutes. If you have been following my post on Apache MINA, this would be a natural extension to it. In this article, we shall bring together all our components to build the system.</p>
<p> <strong>Pre-requisites:</strong></p>
<p><strong> <span style="font-weight: normal;">Please read through these articles. You can find all these posts on <a href="http://www.ashishpaliwal.com/blog/apache-mina/">Apache MINA</a></span></strong></p>
<ul type="disc">
<li>What is Apache MINA</li>
<li>Apache MINA based Server Application Architecture</li>
<li>Implementing UDP Server using Apache MINA</li>
<li>Implementing SNMP4J Decoder for Apache MINA</li>
</ul>
<p> To execute the code, you need following jars</p>
<ul type="disc">
<li>mina-core-2.0.0-M1.jar</li>
<li>slf4j-api-1.5.0.jar</li>
<li>slf4j-log4j12-1.5.0.jar</li>
<li>log4j-1.2.15.jar</li>
<li>SNMP4J.jar</li>
</ul>
<p> I am assuming that you have read my previous posts and jumping straight to the implementations. The high level architecture is explained in the post Apache MINA based Server Application Architecture</p>
<p><strong>Architecture</strong> </p>
<p><a href="http://www.ashishpaliwal.com/blog/wp-content/uploads/2008/10/traprcvrarchitecture1.png"><img class="aligncenter size-full wp-image-164" title="traprcvrarchitecture1" src="http://www.ashishpaliwal.com/blog/wp-content/uploads/2008/10/traprcvrarchitecture1.png" alt="" width="500" height="238" /></a></p>
<p>Let’s understand the flow here and see what all we need to do to process a trap</p>
<ul type="disc">
<li class="MsoNormal">Receive      the trap over UDP</li>
<li class="MsoNormal">Decode      the Trap</li>
<li class="MsoNormal">Dump      the Trap</li>
</ul>
<p>Lets see how each of the these maps to the code we have already written</p>
<p><a style="text-decoration: none;" href="http://www.ashishpaliwal.com/blog/wp-content/uploads/2008/10/traprcvrcomponents1.png"><span style="color: #000000;"><br />
 </span><img class="aligncenter size-full wp-image-160" style="text-decoration: underline;" title="traprcvrcomponents1" src="http://www.ashishpaliwal.com/blog/wp-content/uploads/2008/10/traprcvrcomponents1.png" alt="" width="500" height="248" /></a></p>
<p>It's a now simple to understand that we have reused all the components to create the Server. Let me not write too much, and jump straight to the code <span><span>J</span></span></p>
<p><strong> The Server Code</strong></p>
<p><a href="http://www.ashishpaliwal.com/blog/wp-content/uploads/2008/10/trapserver.png"><img class="aligncenter size-full wp-image-161" title="trapserver" src="http://www.ashishpaliwal.com/blog/wp-content/uploads/2008/10/trapserver.png" alt="" width="500" height="339" /></a></p>
<p>The only change that we did to the UDP Server code was to add a Protocol Codec. At line 36, we added our custom ProtocolCodecFiler. The SNMPCodecFactory return the instance of our SNMP4J codec. There is not much code and this construct is fairly simple, and explained very well in MINA’s documentation. From the main method, we just need to call the method initialize() and our trap receiver starts.</p>
<p> </p>
<p><script type="text/javascript"><!--
google_ad_client = "pub-6961884887741817";
/* 468x15LinkUnit */
google_ad_slot = "4400881690";
google_ad_width = 468;
google_ad_height = 15;
// --></script><br />
<script src="http://pagead2.googlesyndication.com/pagead/show_ads.js" type="text/javascript"></script><br />
 <strong>References</strong></p>
<ul type="disc">
<li><a href="http://mina.apache.org/">http://mina.apache.org/</a></li>
<li><a href="http://www.snmp4j.org/">http://www.snmp4j.org/</a></li>
</ul>
<p><script type="text/javascript"><!--
google_ad_client = "pub-6961884887741817";
/* 468x60ImageOnly */
google_ad_slot = "0221726572";
google_ad_width = 468;
google_ad_height = 60;
// --></script><br />
<script src="http://pagead2.googlesyndication.com/pagead/show_ads.js" type="text/javascript"></script></p>
]]></content:encoded>
			<wfw:commentRss>http://www.ashishpaliwal.com/blog/2008/10/implementing-trap-receiver-in-30-minutes-using-apache-mina/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Implementing UDP Server using Apache MINA</title>
		<link>http://www.ashishpaliwal.com/blog/2008/10/implementing-udp-server-using-apache-mina/</link>
		<comments>http://www.ashishpaliwal.com/blog/2008/10/implementing-udp-server-using-apache-mina/#comments</comments>
		<pubDate>Tue, 21 Oct 2008 07:07:28 +0000</pubDate>
		<dc:creator>ashish</dc:creator>
				<category><![CDATA[Network Programming]]></category>
		<category><![CDATA[Apache MINA]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[UDP]]></category>

		<guid isPermaLink="false">http://www.ashishpaliwal.com/blog/?p=151</guid>
		<description><![CDATA[In my last post we created a UDP client using Apache MINA. Lets turn the table and implement the Server side. Let's see how using Apache MINA reduces the effort to create a UDP Server. Steps to create a UDP Server using java.net API's Create a Socket and listen for incoming connection Process each packet [...]]]></description>
			<content:encoded><![CDATA[<p>In my last post we created a UDP client using Apache MINA. Lets turn the table and implement the Server side. Let's see how using Apache MINA reduces the effort to create a UDP Server.</p>
<p>Steps to create a UDP Server using java.net API's</p>
<ol>
<li>Create a Socket and listen for incoming connection</li>
<li>Process each packet in a separate thread <img src='http://www.ashishpaliwal.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' />  (I hate this, unfortunately need this to have high processing rate)</li>
<li>Parse and process the request and optionally send response (Lets omit this to keep things simple)</li>
</ol>
<div>Lets see how to achieve the same using Apache MINA</div>
<div>
<ol>
<li>Create a NioDatagramAcceptor</li>
<li>Add an IoHandler</li>
<li>Bind and make application ready to receive</li>
</ol>
</div>
<div>That's it <img src='http://www.ashishpaliwal.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </div>
<div>Before we dive into the code, lets see some assumption made to run this</div>
<div>
<ul>
<li>Our protocol is carrying Strings in UDP packet</li>
<li>We shall not do any transformation on the packets received. We shall just dump the content</li>
</ul>
<div><strong>The Handler</strong></div>
<p> </p>
<div><a href="http://www.ashishpaliwal.com/blog/wp-content/uploads/2008/10/udpsrvhandler.png"><img class="aligncenter size-full wp-image-142" title="udpsrvhandler" src="http://www.ashishpaliwal.com/blog/wp-content/uploads/2008/10/udpsrvhandler.png" alt="" width="500" height="192" /></a></div>
<p><script type="text/javascript"><!--
google_ad_client = "pub-6961884887741817";
/* 468x15LinkUnit */
google_ad_slot = "4400881690";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script><br />
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p>
<p>The Handler is in its basic form. Our only method of interest is messageReceived. Since we know that we are getting "String" message without any transformation, we could easily create a new string from the bytes received. A wonderful thing to note about this API is the parameter "<em>message</em>". This makes the API generic enough to cater to any kind of objects. If we had used a ProtocolCodec in the chain and had transformed the byte[] into a custom Object, we would have type-casted <em>message </em>to that object.</p>
<div>That's all in the handler.</div>
<p> </p>
<div><strong>The Server</strong></div>
<div>Lets see the main Server code</div>
<p> </p>
<div><a href="http://www.ashishpaliwal.com/blog/wp-content/uploads/2008/10/minaudpsrv.png"><img class="aligncenter size-full wp-image-143" title="minaudpsrv" src="http://www.ashishpaliwal.com/blog/wp-content/uploads/2008/10/minaudpsrv.png" alt="" width="500" height="379" /></a></div>
<p> <script type="text/javascript"><!--
google_ad_client = "pub-6961884887741817";
/* 468x15LinkUnit */
google_ad_slot = "4400881690";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script><br />
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p>
<div>The Server is even simpler than client <img src='http://www.ashishpaliwal.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </div>
<div>We create an instance of NioDatagramAcceptor and add our custom handler to it. We then bind to the port desired. Here I have made it bind to the default port, code can be customized to bind to any port desired.</div>
<p>So what does 31 does. There is wonderful description of this option at <a href="http://www.unixguide.net/network/socketfaq/4.5.shtml">http://www.unixguide.net/network/socketfaq/4.5.shtml</a><br />
The main function is pretty simple. The Server is ready. You can run it, using the Client from the post <a href="http://www.ashishpaliwal.com/blog/2008/10/implementing-udp-client-using-apache-mina/">Implementing UDP Client using Apache MINA</a></p>
<p><strong>References</strong></p>
<div>
<ul>
<li><a href="http://mina.apache.org/udp-tutorial.html">http://mina.apache.org/udp-tutorial.html</a></li>
</ul>
</div>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.ashishpaliwal.com/blog/2008/10/implementing-udp-server-using-apache-mina/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Implementing UDP Client using Apache MINA</title>
		<link>http://www.ashishpaliwal.com/blog/2008/10/implementing-udp-client-using-apache-mina/</link>
		<comments>http://www.ashishpaliwal.com/blog/2008/10/implementing-udp-client-using-apache-mina/#comments</comments>
		<pubDate>Mon, 20 Oct 2008 10:47:45 +0000</pubDate>
		<dc:creator>ashish</dc:creator>
				<category><![CDATA[Network Programming]]></category>
		<category><![CDATA[Apache MINA]]></category>
		<category><![CDATA[UDP Client]]></category>

		<guid isPermaLink="false">http://www.ashishpaliwal.com/blog/?p=110</guid>
		<description><![CDATA[Its been a while that I wrote on Apache MINA. Please refer to my post collection on Apache MINA. In this post, I have tried to capture briefly on how to implement a UDP Client using Apache MINA. We shall concentrate on keeping our scope limited to sending data over UDP. In Subsequent posts, we [...]]]></description>
			<content:encoded><![CDATA[<p>Its been a while that I wrote on Apache MINA. Please refer to my post collection on <a href="http://www.ashishpaliwal.com/blog/apache-mina/">Apache MINA</a>.</p>
<p>In this post, I have tried to capture briefly on how to implement a UDP Client using Apache MINA. We shall concentrate on keeping our scope limited to sending data over UDP. In Subsequent posts, we shall see how we can enhance this UDP Client to send SNMP Traps.</p>
<p>In brief, these are the steps we need to perform to send a UDP packet</p>
<ol>
<li>Create a Datagram Socket</li>
<li>Create a Datagram Packet</li>
<li>Send the packet</li>
</ol>
<div>This is how we used to do when using java.net API's. The logical flow remains same, but lets see how it maps to Apache MINA</div>
<div>
<ol>
<li>Create a NioDatagramConnector instance</li>
<li>Add an IoHandler (we can use an IoHandlerAdapter, as for this example we don't need to use all the API's)</li>
<li>Connect the NioDatagramConnector</li>
<li>Get the session</li>
<li>Write the data onto the session</li>
</ol>
<div>There is a slight difference in which the MINA API's work. The API's work asynchronously. A call to connect() on NioDatagramConnector, return a reference to ConnectFuture and the operation is kicked off in a new thread. Lets see how the Code looks like and see it in details.</div>
<p> </p>
<div><a href="http://www.ashishpaliwal.com/blog/wp-content/uploads/2008/10/minaudpclient.png"><img class="alignleft size-full wp-image-113" title="minaudpclient" src="http://www.ashishpaliwal.com/blog/wp-content/uploads/2008/10/minaudpclient.png" alt="" width="500" height="270" /></a></div>
<div> </div>
<p>Lets see the Code in detail now. We have maintained the Session at the class level, assuming that we may reuse the session for sending packets, if session is still active. At line 25, we check if the session is active or not. If inactive we initiate the connection. </p>
<p>Line 28, creates an instance of NioDatagramConnector</p>
<p>Line 31, add an IoHandler to the NioDatagramConnector on Line 28. In MINA terminology, IoHandler contains the code where Business logic of an Application resides. In our case its a pure Adapter, with only log statements inside the functions.</p>
<p>Line 32, a call to connect(), returns an reference to ConnectFuture. The call, starts the connection operation, in a separate thread and returns to the caller. To cater to this asynchronous behaviour, we add an IoFutureListener, to returned ConnectFuture reference. Out there (Line 38-43), we just check if the connection is OK, we get the session from it. Line 39, signals that connection is connected and its safe to get the session for writing data.</p>
<p>The connect code is complete. Lets see how to send the data.</p>
<p><a href="http://www.ashishpaliwal.com/blog/wp-content/uploads/2008/10/minaudpclient_send.png"><img class="aligncenter size-full wp-image-116" title="minaudpclient_send" src="http://www.ashishpaliwal.com/blog/wp-content/uploads/2008/10/minaudpclient_send.png" alt="" width="500" height="286" /></a></p>
<p>The send function is pretty simple. We just create an IoBuffer and call write on the session. We have called connect() on Line 59, just to ensure that the connection is alive. If it isn't, it shall create a connection and return a session back.</p>
<p>NOTE: This code is in its very simple form. There can be various mechanism to handle Session (based on destination etc). Also, please be aware of the asynchronous behaviour of the NioDatagramConnector connect() API. If the connection is not complete in time, you might see a null pointer at Line 67 <img src='http://www.ashishpaliwal.com/blog/wp-includes/images/smilies/icon_sad.gif' alt=':-(' class='wp-smiley' /> . But this is usually the case. For production code, it is advisable to ensure that session is never null.</p>
<p>That's it, out UDP client is ready. To create an SNMP Trap sender, we just need to pass Trap byte array to send() and we are done. Will try to post that article soon.</p>
<p>References</p>
<ul>
<li><a href="http://mina.apache.org/udp-tutorial.html">http://mina.apache.org/udp-tutorial.html</a></li>
</ul>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.ashishpaliwal.com/blog/2008/10/implementing-udp-client-using-apache-mina/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
	</channel>
</rss>
