<?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/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Technology and fun</title>
	<atom:link href="http://technfun.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://technfun.wordpress.com</link>
	<description>software development and computer gaming</description>
	<lastBuildDate>Wed, 28 Dec 2011 06:49:02 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='technfun.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Technology and fun</title>
		<link>http://technfun.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://technfun.wordpress.com/osd.xml" title="Technology and fun" />
	<atom:link rel='hub' href='http://technfun.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Remote debugging C programs with Eclipse and GDB</title>
		<link>http://technfun.wordpress.com/2011/12/27/remote-debugging-with-eclipse/</link>
		<comments>http://technfun.wordpress.com/2011/12/27/remote-debugging-with-eclipse/#comments</comments>
		<pubDate>Tue, 27 Dec 2011 14:32:19 +0000</pubDate>
		<dc:creator>kmatveev</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Technology]]></category>

		<guid isPermaLink="false">http://technfun.wordpress.com/?p=218</guid>
		<description><![CDATA[On my daily job I write in Java. My last assignment, however, was to patch existing networking program written in C. Last time I&#8217;ve used C was 10 years ago. I took this assignment since I was pretty confident about myself, because I frequently refresh my knowledge of C by reading a book &#8220;Unix network [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=technfun.wordpress.com&amp;blog=1182547&amp;post=218&amp;subd=technfun&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>On my daily job I write in Java. My last assignment, however, was to patch existing networking program written in C. Last time I&#8217;ve used C was 10 years ago. I took this assignment since I was pretty confident about myself, because I frequently refresh my knowledge of C by reading a book &#8220;Unix network programming&#8221;, for example. By the way, I strongly believe that this book is the only must-read book for any Java programmer who writes networking software regardless if he uses either IO or NIO.</p>
<p>My IDE of choice is Intellij IDEA, but I&#8217;ve evaluated Eclipse several times, so I know how it works. I also knew that Eclipse CDT is a one of the best free IDEs for C development available, so I chose it as my C IDE. On my desktop PC I use Windows, but software I was modifying is Unix-only. When I&#8217;ve finished writing code I&#8217;ve uploaded it using FTP on Linux host (more on that later), and launched <span style="color:#ff6600;">make</span>. Of course I had compilation errors, but after some editing and uploading I finally got binary executable. The program is a network proxy. I&#8217;ve started it, sent some messages through it, and, as I expected, it was not working in a right way. I had to debug it to know why.</p>
<p>With Java it is very easy to debug programs remotelly. You just ask IDE to do a remote debug, IDE will display to you what command-line options you should add to <span style="color:#ff6600;">java</span> executable, then you just type host and port, and that&#8217;s it. All debugging takes place in JVM, and your IDE is a debugging front-end. Easy and straightforward.</p>
<p>Not like this with Eclipse CDT. I&#8217;ve opened &#8220;Debug configurations&#8221; window, and saw &#8220;C/C++ Remote Application&#8221; option. I chose this option, but I found myself confused with fields I had to specify: location of executable and location of debugger. Even after I&#8217;ve downloaded executable from Linux to Windows, I couldn&#8217;t start remote debugging. So I decided to abandon this attempt for a while and try manual debugging with <span>GDB</span>.</p>
<p>This debugger was surprisingly easy for me to learn. It is much less cryptic than other Unix tools. Just a dozen of simple and memorable commands which you can print on one small sheet of paper for reference. Using GDB I quickly found my errors. The only inconvenience is that you have to switch between terminal window where GDB is running and Eclipse CDT window where code is. Also I still had an impression that remote debugging is actually possible from Eclpse CDT, so I decided to get it working, or at least to have an explanation why it is not possible.</p>
<p>And that&#8217;s that I&#8217;ve discovered after some long investigation. When C guys say &#8220;remote debug&#8221; they mean something very-very different from what Java guys mean. To remotelly debug C program you should link it with small chunk of code, which is able to do basic control of program execution (setting breakpoints, pausing-resuming, &#8230;) and basic program state examination (memory, stack frames, registers). This chunk of code is called &#8220;<span style="color:#008000;">target side</span>&#8220;. It will communicate with main part of a debugger which will be located on another machine. Debugger should be able to access an image of a program with all it&#8217;s symbols. This symbolic info allows debugger to perform all high-level debugging job, like showing contents of local variables, execution of code in line-by-line mode, setting breakpoint on function. This part of a debugger is called &#8220;<span style="color:#008000;">symbol side+UI</span>&#8220;. When you perform a local debug both sides are in a same <span style="color:#0000ff;">gdb</span> process. You can also avoid linking with target size code by launching <span style="color:#ff6600;">gdbserver</span> which will attach to any process on a host. There is no official name for a protocol between target side and symbol side, so I&#8217;ll call it Remote Serial Protocol. It can work over serial cable or over TCP/IP.</p>
<p>So, difference between remote debugging in Java and remote debugging in C is that in case of Java target side and symbol side work on the same machine as program being debugged, and UI is on remote machine. In case of C only target side is located with program being debugged, and symbol side together with UI is on remote machine. Such approach allows debugging programs in cases where normal gdb will not work in local mode. For example, if you have a program for embedded device, which doesn&#8217;t have enough memory for full GDB.</p>
<p>But I want to remotelly debug programs with GDB in Java style. C guys will call it &#8220;remote UI for GDB&#8221;. And I believe that this is possible. Then you debug a program locally with Eclipse CDT, it creates a process for gdb, and intercepts it&#8217;s input and output. Then it says to GDB that instead of human-oriented command language it will use for communication a special machine-oriented language called MI (&#8220;machine interface&#8221;), which is easier to parse. So in order to use Eclipse CDT as a remote UI for GDB I should just launch GDB remotelly and remotelly attach to it&#8217;s input and output. I&#8217;ll try to make a plugin for Eclipse using my knowledge of Java, because a bunch of questions on StackOverflow shows that such capability is demanded.</p>
<p>Some links:</p>
<p>http://sourceware.org/gdb/current/onlinedocs/gdb/Remote-Protocol.html#Remote-Protocol</p>
<p>http://sourceware.org/gdb/current/onlinedocs/gdb/GDB_002fMI.html#GDB_002fMI</p>
<p>http://sourceware.org/gdb/current/onlinedocs/gdbint/Overall-Structure.html#Overall-Structure</p>
<p>http://dev.eclipse.org/mhonarc/lists/dsdp-tm-dev/msg01369.html</p>
<p>http://wiki.eclipse.org/TM_and_RSE_FAQ#How_can_I_do_Remote_Debugging_with_CDT.3F</p>
<p>http://www.ibm.com/developerworks/library/os-eclipse-cdt-debug2/index.html</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/technfun.wordpress.com/218/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/technfun.wordpress.com/218/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/technfun.wordpress.com/218/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/technfun.wordpress.com/218/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/technfun.wordpress.com/218/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/technfun.wordpress.com/218/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/technfun.wordpress.com/218/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/technfun.wordpress.com/218/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/technfun.wordpress.com/218/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/technfun.wordpress.com/218/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/technfun.wordpress.com/218/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/technfun.wordpress.com/218/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/technfun.wordpress.com/218/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/technfun.wordpress.com/218/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=technfun.wordpress.com&amp;blog=1182547&amp;post=218&amp;subd=technfun&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://technfun.wordpress.com/2011/12/27/remote-debugging-with-eclipse/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">kmatveev</media:title>
		</media:content>
	</item>
		<item>
		<title>Haskell platform pitfalls #1</title>
		<link>http://technfun.wordpress.com/2011/10/25/haskell-platform-pitfalls-1/</link>
		<comments>http://technfun.wordpress.com/2011/10/25/haskell-platform-pitfalls-1/#comments</comments>
		<pubDate>Tue, 25 Oct 2011 05:48:06 +0000</pubDate>
		<dc:creator>kmatveev</dc:creator>
				<category><![CDATA[Haskell]]></category>

		<guid isPermaLink="false">http://technfun.wordpress.com/?p=205</guid>
		<description><![CDATA[I&#8217;ve started playing with Haskell platform, and immediatelly had some issues. Here are some of them, recorded so if I&#8217;ll forget I don&#8217;t need to solve them again. After installation of a platform I knew I need cabal. Haskell wiki says it is there, but I didn&#8217;t knew where to look. Finally I&#8217;ve found it: [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=technfun.wordpress.com&amp;blog=1182547&amp;post=205&amp;subd=technfun&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve started playing with Haskell platform, and immediatelly had some issues. Here are some of them, recorded so if I&#8217;ll forget I don&#8217;t need to solve them again.</p>
<ol>
<li>After installation of a platform I knew I need cabal. Haskell wiki says it is there, but I didn&#8217;t knew where to look. Finally I&#8217;ve found it: in Haskell Platform directory there is a place with path lib/extralibs/bin. It seems that I need to read full platform documentation before starting using it</li>
<li>OK, with cabal I&#8217;ve tried to install snap framework. It stumbled on ghc-paths component, complaing that it &#8220;cannot configure&#8221;. I&#8217;ve checked and found that this component is used to find path where Haskell Platform is installed. I&#8217;ve checked my path and there were an entry for Haskell bin directory. A mystery. I&#8217;ve tried to run ghc from that command line (Far Manager, actually) which I&#8217;ve used to start cabal, and no, ghc was not found. I&#8217;ve typed &#8216;path&#8217;, and an entry for Haskell Platform was missing. I&#8217;ve remembered that command line was started before I&#8217;ve installed Haskell Platform, so changes in system path were not seen. Restarting command line solved that problem</li>
<li>Next package I&#8217;ve tried to install was hxt. It complained that it cannot determine version of ghc. It took me a while to figure out that command line should be started with admin rights.</li>
<li>I&#8217;ve tried to create a blank project with snap. Just create a folder and type &#8216;snap init&#8217;. Then I&#8217;ve tried to build that project with cabal. Oops, &#8220;can&#8217;t parse name&#8221;. It took me some time to guess that it doesn&#8217;t like symbol &#8216;-&#8217; in the name of that folder</li>
</ol>
<p>So far so good.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/technfun.wordpress.com/205/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/technfun.wordpress.com/205/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/technfun.wordpress.com/205/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/technfun.wordpress.com/205/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/technfun.wordpress.com/205/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/technfun.wordpress.com/205/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/technfun.wordpress.com/205/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/technfun.wordpress.com/205/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/technfun.wordpress.com/205/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/technfun.wordpress.com/205/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/technfun.wordpress.com/205/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/technfun.wordpress.com/205/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/technfun.wordpress.com/205/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/technfun.wordpress.com/205/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=technfun.wordpress.com&amp;blog=1182547&amp;post=205&amp;subd=technfun&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://technfun.wordpress.com/2011/10/25/haskell-platform-pitfalls-1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">kmatveev</media:title>
		</media:content>
	</item>
		<item>
		<title>Is network stack a framework ?</title>
		<link>http://technfun.wordpress.com/2009/07/13/is-network-stack-a-framework/</link>
		<comments>http://technfun.wordpress.com/2009/07/13/is-network-stack-a-framework/#comments</comments>
		<pubDate>Mon, 13 Jul 2009 11:15:12 +0000</pubDate>
		<dc:creator>kmatveev</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[SIP]]></category>
		<category><![CDATA[telecom]]></category>

		<guid isPermaLink="false">http://technfun.wordpress.com/?p=183</guid>
		<description><![CDATA[My recent articles about JAIN SIP API and SIP Servlets API often mention a term &#8220;framework&#8221;. I&#8217;ve planned to discuss this term in regard to SIP stack in depth, but forgot. Of course, this caused some questions, thus I&#8217;m doing it now. I&#8217;m calling software module a &#8220;framework&#8221; if it is built with &#8220;Inversion of [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=technfun.wordpress.com&amp;blog=1182547&amp;post=183&amp;subd=technfun&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>My recent articles about JAIN SIP API and SIP Servlets API often mention a term &#8220;framework&#8221;. I&#8217;ve planned to discuss this term in regard to SIP stack in depth, but forgot. Of course, this caused some questions, thus I&#8217;m doing it now.</p>
<p>I&#8217;m calling software module a &#8220;framework&#8221; if it is built with &#8220;Inversion of control&#8221; pattern. You provide callbacks, and framework invokes them according to it&#8217;s specification. Sometimes you can manage frameworks, but you cannot customize it beyond certain degree. Your code is not active, it is either passive or reactive.</p>
<p>Event-driven programming model is a one example of framework architecture. Software containers is another example.</p>
<p>Now you can see why I call SIP stacks which implement JAIN SIP API or SIP Servlets API as frameworks. They read data from network, handle them and then invoke a supplied listener (either SipServlet or SipListener). This invocation takes place in a thread of a SIP stack, so if you should not block it. JAIN SIP API has dispatch of incoming traffic based on local endpoint, and SIP Servlets API has method-based dispatch, but this is not a very significant difference.</p>
<p>Why SIP stacks are implemented as frameworks? To answer this, let&#8217;s imagine a stack which is implemented as a library. So, you create a socket, read from it, and then pass a byte array to stack for handling. SIP stack will return a result to you in functional style:</p>
<p style="padding-left:30px;"><span style="color:#0000ff;">ByteBuffer data = ByteBuffer.allocate(MAX_MESSAGE);</span></p>
<p style="padding-left:30px;"><span style="color:#0000ff;">SocketAddress remote = channel.receive(data);</span></p>
<p style="padding-left:30px;"><span style="color:#0000ff;">SipResult result = stack.handle(data, remote);</span></p>
<p>Since there are many possible results of handling SIP messages, now you should analyze the result and dispatch according to it: was the message parsed correctly or not, was it request or response, was it a retransmission or not, and many other choices. If request was parsed correctly but has some mandatory headers missing, then result should contain error response which you can send through stack object. Such dispatch code is large, and should be written once because it&#8217;s behaviour is well specified in RFC 3261. This is a first reason why stacks are implemented as frameworks: they include common dispach code.</p>
<p>A second reason is that application programmers often afraid of working with threads and sockets directly. They consider that to be &#8220;system-level&#8221; code, which should be hidden from them. Developers of SIP stacks should bother about performance, race conditions and other complex stuff.</p>
<p>Thus, SIP stacks are frameworks, and I think that this is a right way. By the way, most HTTP stacks are also frameworks.</p>
<p>Now I will explain why I think that JAIN SIP API and SIP Servlets API are not perfect frameworks.</p>
<p>JAIN SIP API has a single callback called <em>SipListener</em>. It has only two methods for processing incoming messages: <em><span style="color:#000000;">processRequest()</span></em> and <em>processResponse()</em>. Thus, SIP stack does very little dispatch for you. If you are doing a stateless proxy, you&#8217;ll have very simple logic there. But for UA and statefull proxy there will be one large &#8220;if&#8221; statement. It could be implemented in different ways. One way is to map transactions and dialog on your application contexts. In this case you&#8217;ll have to look up into maps. Another way is to bind application contexts to transactions and dialogs using setApplicationData() method. In this case you&#8217;ll need to invoke getApplicationData() then cast it to your application context. When you have your application context you have additional dispatch. JAIN SIP API is flexible here, but this dispatching code is reusable, thus it should be written once. This dispatch code makes a better protocol framework on top of framework provided by SipListener.</p>
<p>A better protocol framework should have the following capabilities:</p>
<ul>
<li>ServerTransactionListener, which can be provided to specific server transaction. This listener will be notified when transaction terminates, when final response retransmission timeout happens, and when CANCEL is received</li>
<li>ClientTransactionListener, which can be provided to specific client transaction. This listener will be notified when response is received</li>
<li>DialogListener, which can be provided to specific dialog. This listener will be notified when dialog has been forked and when dialog has been terminated</li>
<li>ServerListener, which is invoked for incoming requests. There should be one &#8220;global&#8221;  listener, and there could be specific listener for each dialog.</li>
</ul>
<p>Such protocol framework will allow you to write applications with much less dispatch code.</p>
<p>Most of that is also true for SIP Servlets API. You have to extract attributes from SipSession and dispatch your execution based on them. However, they have some things better:</p>
<ul>
<li>You can specify which servlet will handle which SipSession. Unfortunatelly, servlets are stateless.</li>
<li>Method-based dispatch is provided by SipServlet class</li>
</ul>
<p>Thus, SIP Servlets API doesn&#8217;t provide a powerful protocol framework. Instead, they provide application framework: you can compose servlets, you have listener for various things such as binding attributes to sessions.</p>
<p>I hope I have explained why I consider SIP stacks to implement &#8220;framework&#8221; architecture. I also hope I have explaided why I think that it could be a better frameworks.</p>
<p>And, finally, what I&#8217;m calling an &#8220;application server&#8221; ? An application server:</p>
<ul>
<li>Is a server for some protocol</li>
<li>Is implemented as a framework for this protocol</li>
<li>Is implemented as component container</li>
</ul>
<p>Thus, SIP Servlets API and JAIN SLEE are describing application server, but JAIN SIP API is not.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/technfun.wordpress.com/183/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/technfun.wordpress.com/183/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/technfun.wordpress.com/183/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/technfun.wordpress.com/183/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/technfun.wordpress.com/183/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/technfun.wordpress.com/183/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/technfun.wordpress.com/183/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/technfun.wordpress.com/183/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/technfun.wordpress.com/183/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/technfun.wordpress.com/183/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/technfun.wordpress.com/183/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/technfun.wordpress.com/183/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/technfun.wordpress.com/183/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/technfun.wordpress.com/183/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=technfun.wordpress.com&amp;blog=1182547&amp;post=183&amp;subd=technfun&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://technfun.wordpress.com/2009/07/13/is-network-stack-a-framework/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">kmatveev</media:title>
		</media:content>
	</item>
		<item>
		<title>Tracing facilities and tools for Unix</title>
		<link>http://technfun.wordpress.com/2009/05/28/tracing-facilities-and-tools-for-unix/</link>
		<comments>http://technfun.wordpress.com/2009/05/28/tracing-facilities-and-tools-for-unix/#comments</comments>
		<pubDate>Thu, 28 May 2009 09:29:25 +0000</pubDate>
		<dc:creator>kmatveev</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://technfun.wordpress.com/?p=172</guid>
		<description><![CDATA[I&#8217;ve become confused with amount of tools and facilities ending with &#8220;trace&#8221; which exist on different Unix-like OSes. This small article lists them together will small description ptrace A system call of System V and BSD (also exists in Linux) which may be used by one process &#8220;to observe and control the execution of another [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=technfun.wordpress.com&amp;blog=1182547&amp;post=172&amp;subd=technfun&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve become confused with amount of tools and facilities ending with &#8220;trace&#8221; which exist on different Unix-like OSes. This small article lists them together will small description</p>
<h3>ptrace</h3>
<p>A system call of System V and BSD (also exists in Linux) which may be used by one process &#8220;to observe and control the execution of another process&#8221;. Available commands include reading and writing a memory of the process (used for setting breakpoints), reading CPU registers, intercepting signals sent to the process, intercepting system calls made by the process. Intercepting is done by stopping a traced process and sending a signal SIGCHILD to process which requested the tracing. Observer then may request information about stopped process and may continue its execution.</p>
<h3>strace</h3>
<p>A Linux utility which is used to trace system calls and signals. Uses ptrace() system call</p>
<h3>ktrace/ktruss/kdump</h3>
<p>A system call of BSD unixes which traces system calls and signals of specified process and writes the data in specified file. Since there is no context switch between processes, a tracing is faster. Trace data are not human-readable. A ktrace is also a name of command-line utility for unixes of BSD family which does a process tracing by invoking ktrace(). kdump is an utility which reads tracing info written into file by ktrace() and prints this info in human-readable form. ktruss is another command-line utility for BSD-derived unixes which traces system calls and signals for some process by using ktrace() system call. It prints tracing info in human-readable form on console.</p>
<h3>systrace</h3>
<p>A facility of some BSD unixes which is intended to restrict certain system calls done by some process. In simplest case can be used just to trace those calls. Implemented as pseudo-device &#8220;/dev/systrace&#8221;. System call ioctl() is used to perform actions such as attaching to process or permit to do a system call. System call read() on systrace device will block until some traced process will perform a system call. Systrace is also a name of command-line utility which uses systrace facility.</p>
<h3>ltrace</h3>
<p>A command-line utility which traces system calls and calls to functions of dynamically linked libraries. System calls are traced using ptrace(). Library calls are traced by analyzing symbol table of ELF file, calculating addresses and placing breakpoints for every library call using ptrace(). When breakpoint hits a stack trace of the process is obtained (using ptrace()) and compared with breakpoint table to get function name.</p>
<h3>dtrace</h3>
<p>Tracing facility originally developed for Solaris and later moved to other Unixes. It consists of core, &#8220;probe providers&#8221; which register with core, and &#8220;probe consumers&#8221; which are user-level processes like &#8216;dtrace&#8217; command-line tool. Consumers can express an interest in some probe by asking a core to enable it. Core, in turn, uses provider to obtain and address.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/technfun.wordpress.com/172/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/technfun.wordpress.com/172/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/technfun.wordpress.com/172/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/technfun.wordpress.com/172/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/technfun.wordpress.com/172/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/technfun.wordpress.com/172/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/technfun.wordpress.com/172/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/technfun.wordpress.com/172/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/technfun.wordpress.com/172/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/technfun.wordpress.com/172/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/technfun.wordpress.com/172/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/technfun.wordpress.com/172/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/technfun.wordpress.com/172/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/technfun.wordpress.com/172/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=technfun.wordpress.com&amp;blog=1182547&amp;post=172&amp;subd=technfun&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://technfun.wordpress.com/2009/05/28/tracing-facilities-and-tools-for-unix/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">kmatveev</media:title>
		</media:content>
	</item>
		<item>
		<title>A study on Java APIs for SIP. Part 3: future</title>
		<link>http://technfun.wordpress.com/2009/05/28/java-sip-4/</link>
		<comments>http://technfun.wordpress.com/2009/05/28/java-sip-4/#comments</comments>
		<pubDate>Thu, 28 May 2009 09:00:47 +0000</pubDate>
		<dc:creator>kmatveev</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[SIP]]></category>
		<category><![CDATA[telecom]]></category>

		<guid isPermaLink="false">http://technfun.wordpress.com/?p=146</guid>
		<description><![CDATA[Comparing JAIN SIP API and SIP Servlets API makes it clear that these APIs play on different fields. JAIN SIP API focuses on implementation simplicity. It is not a stack, but a Stack SDK. If you need to quickly implement some well-known call-flow, JAIN SIP API is a bad choice. But if you want to [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=technfun.wordpress.com&amp;blog=1182547&amp;post=146&amp;subd=technfun&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Comparing JAIN SIP API and SIP Servlets API makes it clear that these APIs play on different fields.</p>
<p>JAIN SIP API focuses on implementation simplicity. It is not a stack, but a Stack SDK. If you need to quickly implement some well-known call-flow, JAIN SIP API is a bad choice. But if you want to implement some new SIP feature, then JAIN SIP API may come handy.</p>
<p>SIP Servlets API focuses on developer&#8217;s productivity and enforces implementation to be very powerful, because it is not an API for SIP stack, but API provided by application server. It is especially suited for well-known areas of SIP. However, it doesn&#8217;t allow you to do something unusual. Other minor drawbacks are bloat and manual contextualization.</p>
<p>By the way, there is an interesting move by company called OpenCloud. They support two APIs: one is <a href="https://developer.opencloud.com/devportal/display/OCDEV/OC+SIP+API+2.0">JAIN SIP API</a>, just a little bit extended, and another is called &#8220;<a href="https://developer.opencloud.com/devportal/display/OCDEV/EasySIP+API+1.0">EasySIP</a>&#8220;, which is a complete rip-off of SIP Servlets API. They have introduced separate classes for incoming and outgoing requests and responses.</p>
<p>While both APIs could be used with some effort, I&#8217;m not satisfied with them. I want an API which:</p>
<ul>
<li>Has stack management methods much more powerful then in JAIN SIP API. It should be possible to add/remove local endpoints while stack is running. A listener should receive a reference local endpoint with incoming requests.</li>
<li>Has much better built-in support for &#8220;protocol context&#8221;. For incoming ACK and PRACK it should be possible to get a response it acknowledges. For incoming CANCEL it should be possible to get a request it cancels</li>
<li>Has syntax separated from behaviour.</li>
<li>Will produce compilation errors if trying to respond on incoming ACK or CANCEL, to respond on outgoing request, to acknowledge outgoing response, to cancel incoming response.</li>
<li>Is a protocol framework. It should be possible to specify listener for any particular client transaction, server transaction and dialog.</li>
</ul>
<p>Such API will be powerfull enough so it will provide the same level of developer&#8217;s productivity as SIP Servlets API. But it will also be extensible, and could be used in any type of applications, not only on server side.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/technfun.wordpress.com/146/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/technfun.wordpress.com/146/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/technfun.wordpress.com/146/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/technfun.wordpress.com/146/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/technfun.wordpress.com/146/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/technfun.wordpress.com/146/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/technfun.wordpress.com/146/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/technfun.wordpress.com/146/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/technfun.wordpress.com/146/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/technfun.wordpress.com/146/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/technfun.wordpress.com/146/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/technfun.wordpress.com/146/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/technfun.wordpress.com/146/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/technfun.wordpress.com/146/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=technfun.wordpress.com&amp;blog=1182547&amp;post=146&amp;subd=technfun&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://technfun.wordpress.com/2009/05/28/java-sip-4/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">kmatveev</media:title>
		</media:content>
	</item>
		<item>
		<title>A study on Java APIs for SIP. Part 2: SIP Servlets API</title>
		<link>http://technfun.wordpress.com/2009/05/19/java-sip-3/</link>
		<comments>http://technfun.wordpress.com/2009/05/19/java-sip-3/#comments</comments>
		<pubDate>Tue, 19 May 2009 17:09:13 +0000</pubDate>
		<dc:creator>kmatveev</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[SIP]]></category>
		<category><![CDATA[telecom]]></category>
		<category><![CDATA[SIP Servlets]]></category>

		<guid isPermaLink="false">http://technfun.wordpress.com/?p=140</guid>
		<description><![CDATA[Now let&#8217;s take a look on JAIN SIP API&#8216;s younger brother called SIP Servlets API. This guy was ambitious from the birth, so he joined a mob called &#8220;JEE&#8221; to receive money from big business. But big business never gives money for free, so SIP Servlets API had to cover all behaviour specified for SIP [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=technfun.wordpress.com&amp;blog=1182547&amp;post=140&amp;subd=technfun&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Now let&#8217;s take a look on <a href="http://technfun.wordpress.com/2009/05/15/java-sip-2/">JAIN SIP API</a>&#8216;s younger brother called SIP Servlets API. This guy was ambitious from the birth, so he joined a mob called &#8220;JEE&#8221; to receive money from big business. But big business never gives money for free, so SIP Servlets API had to cover all behaviour specified for SIP and to provide as large framework as possible, so programmers who work for big business will not bother thinking about protocol details and about execution model. An attempt has failed miserably, because SIP, unlike HTTP, is not about content.</p>
<h3>SipServlet interface</h3>
<p>First obvious problem of SIP Servlets API is that it is an extension of Generic Servlets API. The cornerstone class of Generic Servlets API is called <em>Servlet</em>, and has only three methods: <em>init()</em>, <em>service()</em> and <em>destroy()</em>. In my opinion, the main problem here is that this class is essentially a too generic framework. Behaviour of container is always protocol-dependent, so servlets are also protocol-dependant. Still, everybody are forced to use this narrow interface for interaction. Are there any convergent servlets which handle several protocols through their <em>service()</em> method ? No, there are convergent applications instead. I think that<em> service()</em> method should be removed from <em>Servlet</em> class. Instead, all concrete servlets would have their own <em>service()</em> method, accepting protocol-specific requests and responses.</p>
<p>I understand that most people don&#8217;t bother with problem of downcasting request and response in <em>service()</em> method, so it is not a big deal. I just don&#8217;t like it working in this way.</p>
<p>Applications always do some dispatch for incoming messages, so APIs provide some dispatch out-of-box to help application developers. Unlike JAIN SIP API, which has dispatch based on local endpoint and on message type (request/response), SIP Servlets API have built-in dispatch based on request method and response status code. I think that this approach is more useful for applications.</p>
<h3>Syntax</h3>
<p>Next bad thing in SIP Servlets API is an existence of <em>SipServletMessage</em> interface. It&#8217;s exactly the same case as with JAIN SIP API: this abstraction is not used by anyone. Yes, it is good that signatures of methods in <em>SipServletRequest</em> and <em>SipServletResponse</em> are the same, but nothing will break if these signatures would differ. Authors of SIP Servlet API have ignored the lesson of HTTP Servlets API, which doesn&#8217;t have common interface. I understand that HTTP is much more assymmetric then SIP, so in HTTP servlets people are reading headers of requests and writing headers and body to responses, so syntaxic similarity is not related to behaviour. But I still don&#8217;t see how syntaxic symmetry of SIP requests and responses could be used in practice.</p>
<p>Syntax part of SIP Servlets API is much smaller and simpler then of JAIN SIP API. Obtaining header will return you a string, adding or changing a header will also accept value as string. Additional parsing is supported only for address headers.</p>
<h3>Behaviour</h3>
<p><em>SipServletMessage</em> interface includes not only syntax-related methods but also method <em>send()</em>. Message is a nice context for method <em>send()</em>, because it is the message which should be sent. The fact that method <em>send()</em> belongs to <em>SipServletMessage</em> interface shows that SIP Servlets API doesn&#8217;t strive for separation of syntax and behaviour. <em>SipServletMessage</em> is not just a header, start line and body, but it is a gateway to SIP stack, hiding transactions, dialogs and all other protocol layers. This means that you can&#8217;t just &#8220;forward&#8221; incoming message, because it can&#8217;t be separated from all internal state. Instead you should either create a new message and manually copy all necessary data from original message into new message, or use hacks provided by API (like <em>proxyTo()</em> or <em>createRequest()</em> method which accepts original request). Thus the amount of interfaces in API is low, but the amount of behavioural methods is large, and their semantics is more complex. However, as long as &#8220;message=syntax+state&#8221; approach was selected, all methods which implement SIP behaviour are also belong to <em>SipServletRequest</em> or <em>SipServletResponse</em> classes, so message is a context for an action. Such approach is easy to understand by beginners.</p>
<p>Another problem of method <em>send()</em> is that compiler will not complain if you&#8217;ll try to invoke it for incoming message. Of course SIP stack will not send such message, you&#8217;ll get <em>IllegalStateException</em> in runtime. Thus, SIP Servlets API is not designed to use type system for preventing errors.  A correct solution would be to have separate classes like IncomingRequest, OutgoingRequest, IncomingResponse, OutgoingResponse. There are other behaviour-related methods which could be moved to specific classes instead of throwing an <em>IllegalStateException</em>: <em>createCancel()</em>, <em>createResponse()</em>, <em>createAck()</em>. Some special requests (like ACK and CANCEL) could also be represented by specific classes which would not have methods <em>createResponse()</em>.</p>
<p>SIP Servlets API provide large application framework, with different listeners. However, it doesn&#8217;t provide a powerfull protocol framework. Instead, you have a <em>SipSession</em> which represents either dialog or proxying session. This <em>SipSession</em> is used for two purposes. First, as a factory for in-dialog requests. Second, as a storage for application context. This means that for every incoming subsequent message an application should restore its context from <em>SipSession</em> object. Such manual contextualization is not a very convenient thing to program, but it allows application server to be distributed and fault-tolerant. Ability to set a servlet which will handle the session can&#8217;t be considered as a protocol framework, since that servlet also can&#8217;t have its own context and should contextualize itself from <em>SipSession</em>. A little bit more information is given in <a href="http://technfun.wordpress.com/2009/07/13/is-network-stack-a-framework/">subsequent post</a>.</p>
<h3>Conclusion</h3>
<p>SIP Servlets API is not an API for SIP stack. Instead it is an API for application server which means that it tries to be as complete as possible and it is not designed to be extensible. Container should provide all nesessary functionality, and servlets should just contain business logic needed to handle incoming messages. This makes it attactive to beginners who enjoy it&#8217;s protocol power. This API will not allow you to violate SIP rules, however it is usually done by throwing exceptions in runtime. Protocol framework is absent, all you have is a SipSession to store and restore your context.</p>
<p>Next article will compare both APIs, will discuss lots of general API-related stuff and will propose better solutions.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/technfun.wordpress.com/140/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/technfun.wordpress.com/140/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/technfun.wordpress.com/140/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/technfun.wordpress.com/140/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/technfun.wordpress.com/140/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/technfun.wordpress.com/140/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/technfun.wordpress.com/140/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/technfun.wordpress.com/140/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/technfun.wordpress.com/140/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/technfun.wordpress.com/140/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/technfun.wordpress.com/140/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/technfun.wordpress.com/140/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/technfun.wordpress.com/140/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/technfun.wordpress.com/140/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=technfun.wordpress.com&amp;blog=1182547&amp;post=140&amp;subd=technfun&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://technfun.wordpress.com/2009/05/19/java-sip-3/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">kmatveev</media:title>
		</media:content>
	</item>
		<item>
		<title>A study on Java APIs for SIP. Part 1: JAIN SIP API</title>
		<link>http://technfun.wordpress.com/2009/05/15/java-sip-2/</link>
		<comments>http://technfun.wordpress.com/2009/05/15/java-sip-2/#comments</comments>
		<pubDate>Fri, 15 May 2009 21:54:43 +0000</pubDate>
		<dc:creator>kmatveev</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[SIP]]></category>
		<category><![CDATA[telecom]]></category>
		<category><![CDATA[JAIN SIP API]]></category>

		<guid isPermaLink="false">http://technfun.wordpress.com/?p=138</guid>
		<description><![CDATA[Introduction This is a first article of the series which will study popular Java APIs for SIP: JAIN SIP API and SIP Servlets API. My intention is to analyze what is good and what is bad, and why it is so. These articles represent my personal opinion, however I&#8217;m not just going to tag things [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=technfun.wordpress.com&amp;blog=1182547&amp;post=138&amp;subd=technfun&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h3>Introduction</h3>
<p>This is a first article of the series which will study popular Java APIs for SIP: JAIN SIP API and SIP Servlets API. My intention is to analyze what is good and what is bad, and why it is so. These articles represent my personal opinion, however I&#8217;m not just going to tag things as &#8220;good&#8221; or &#8220;bad&#8221;. Instead, I&#8217;ll try to explain why I like or dislike something. The study will focus on technical aspects of APIs. Since I&#8217;m not satisfied with current state of affairs, I also want to propose a better API. Yes, the purpose of this study is to justify the need for another SIP API, because I believe that API is very important.</p>
<p>I don&#8217;t think that a long intoduction is needed, so let&#8217;s start with JAIN SIP API.</p>
<h3>JAIN SIP API</h3>
<p>This API is quite curious because it is very maximalistic in implementation of SIP syntax and quite minimalistic in implementation of SIP behaviour. I have a very strong impression that the author (exactly as I did) at the beginning has focused his attention on syntax believing that parser is the only re-usable part of SIP, and all messaging  scenarios are so volatile that they should be implemented in applications. A version of 1.0 of this API covers only a parser together with a stateless sender/receiver. However, in version 1.2 this API also covers some re-usable behavioural layers, such as transaction layer and dialog layer.</p>
<h3>Syntax representation</h3>
<p>A noticeable feature of JAIN SIP API is that you can work with protocol syntax without a running stack. You just need to obtain a specific factory and then create syntax objects through it.</p>
<p>There are two interfaces which represent two kinds of SIP messages: <em>Request</em> and <em>Response</em>. These interfaces have a common parent interface <em>Message</em>, which contains common syntax-related functionality. I think that existence of <em>Message</em> interface is a bad thing. Occam&#8217;s razor should be applied here: RFC 3261 doesn&#8217;t say anything about messages in general, so this abstraction is totally unnecessary. Let&#8217;s do a simple check: are there any methods of JAIN SIP API which accept <em>Message</em> as parameter or return it as a result? No. This is an example of OOP people to apply abstraction everywhere, and also an implementation detail showing though an API.</p>
<p>Interfaces<em> </em><em>Request</em>/<em>Message</em>/<em>Response</em> provide methods for obtaining/adding/removing header fields, modify start line and obtaining/setting body. These methods are defined quite well, except of methods for obtaining headers. Instead of single method which accepts header name and returns abstract Header which should be downcasted, I propose having specific methods for each known header, for examle <em>getViaHeader()</em>. This will make code more clear and will involve compiler into error checking.</p>
<p>JAIN SIP API strives to have an interface for every documented SIP header. Interfaces for all headers are descendants of <em>Header</em> interface. This interface has <em>getName()</em> method, which is correct in my opinion, meaning that header name defines a format for header value. Unfortunatelly, there is no <em>getValue()</em> method, such method is available only for <em>ExtensionHeader</em>. This is bad, because for some headers (like &#8216;Content-Type&#8217;, for example) it is often needed to obtain whole value instead of accessing it&#8217;s parts.</p>
<p>I don&#8217;t have very much to say about <em>Address</em>, <em>URI</em> and <em>SipURI</em>. They are OK.</p>
<p>As you can see, I&#8217;m quite satisfied with syntax part of JAIN SIP API. These objects are just data structures reflecting syntax structure of SIP messages.</p>
<h3>Stack management: SipStack, SipProvider and ListeningPoint</h3>
<p>SIP stack is managed through interface <em>SipStack</em>. Besides lifecycle methods <em>start()</em> and <em>stop()</em>, this interface also has factory methods for <em>ListeningPoints</em> and for <em>SipProviders</em>.These two classes are then supplied to methods add()/remove() to define which network endpoints will be served by which provider.</p>
<p><em>ListeningPoint</em> is a combo-class for an <em>InetSocketAddress</em> and a <em>String</em> which specifies a name of a transport protocol. This class could be avoided at all. In all methods where <em>ListeningPoint</em> is passed as a parameter it could be replaced with combo of  <em>InetSocketAddress</em> and <em>String</em>. There is a method that returns ListeningPoints, but it can be very well replaced with two methods: one that returns InetSocketAddresses, and another that returns transports for provided InetSocketAddress. So the only point behind this class is to make argument list shorter. I think that it is better to add one or two methods to an existing class then having another useless class.</p>
<p>Interface <em>SipProvider</em> is used to bind a specific <em>SipListener</em> to a specific network endpoint. Thus, JAIN SIP API can only dispatch incoming traffic based on address where it was received. If you can handle all the traffic by single listener &#8211; fine, but you still need to create and maintain separate <em>SipProvider</em> for each local endpoint. SipProviders can be added to SipStack or removed from it only while it is stopped. This means that in order to listen on one more port you need to stop listening on all other ports. Such restriction is a very bad idea.</p>
<p>Another responsibility of <em>SipProvider</em> is to be a factory for transactions and dialogs. This implicitly means that all events for these transactions and dialogs will be handled by the listener associated with <em>SipProvider</em>, and all outgoing messages will be sent from the local endpoint associated with this provider. A third responsibility is to serve as a facility for stateless sending of requests and responses.</p>
<p>I suggest that Occam&#8217;s razor should be applied to this interface, because it&#8217;s responsibilities are vague. It&#8217;s essentially a context for a very few things, which could be provided explicitly. All methods of this class could be moved to <em>SipStack</em>, so <em>setListener()</em> method would accept an <em>InetSocketAddress</em>, factory methods for transactions and dialogs whould accept <em>SipListener</em>, and local endpoint for sending whould be choosen automatically.</p>
<h3>Transactions</h3>
<p>Client and server transactions are represented by interfaces <em>ClientTransaction</em> and <em>ServerTransaction</em>. These interfaces have common parent interface <em>Transaction</em>, which (very similar to <em>Message</em>) has no apparent use and could also be removed without anybody noticing. <em>ClientTransaction</em> has method for sending request and creating a cancel, <em>ServerTransaction</em> has method for sending responses.</p>
<p>Let&#8217;s try to apply Occam&#8217;s razor to these classes and see if it is possible to replace them with methods. For <em>ServerTransaction</em>, an answer seems to be no, because sometimes server transactions are created automatically by stack.</p>
<p>Maybe a client transaction can be replaced with method <em>sendStatefully()</em> on <em>SipStack</em>? In case of incoming response or timeout, an application needs a context to handle these events. JAIN SIP API is built in a way that transactions are used as contexts, thus transactions are needed. But, maybe it is possible to replace separate factory method and sending method with just one method, which whould send message statefully and return a transaction object? This whould also eliminate vague problems like: what should stack do if &#8216;Via&#8217; branch of the request has changed after the creation of transaction? The problem with such apporach is caused by threading issue: an event can happen before a thread which invokes sendStatefully() will retrieve transaction, and this event will be handled by another thread which will not find context for the event. However, this problem can be solved by application providing something as a context instead of re-using transactions for that purpose. Thus, <em>sendStatefully()</em> whould accept a context from application, and use that context in <em>ResponseEvent</em>. Thus, client transactions can be avoided.</p>
<p>In fact, transactions do have some support for  application-provided contexts through methods <em>setApplicationData()</em> and <em>getApplicationData()</em>. They have been introduced as a convenient way to avoid having lookup facilities for context in applications. A good idea, but it is implemented in API in a way that makes application to be written like in BASIC:</p>
<p><span style="color:#0000ff;">10 let transaction=provider.createTransaction(request);</span></p>
<p><span style="color:#0000ff;">20 transaction.setApplicationData(context);</span></p>
<p><span style="color:#0000ff;">30 transaction.sendRequest();</span></p>
<p>instead of single invocation:</p>
<p><span style="color:#0000ff;">stack.sendRequest(request, context);</span></p>
<p><span style="color:#0000ff;"><span style="color:#000000;">Since send() is invoked only once, </span><span style="color:#000000;">there is no need to have separate setApplicationData() method.</span></span></p>
<p>Transactions have getState() method which returns transaction state as defined in RFC. This method is more an implementation detail rather then useful thing. Applications are not really interested in difference between COMPLETED and TERMINATED states. Instead, they are interested in things like <em>canRespond(), canCancel()</em> or <em>requestSent()</em>.</p>
<p>So, what exactly are the responsibilities of transaction classes? Implementation details which they expose are not really useful. The answer is that they are more than transactions as they are defined in RFC.</p>
<p>For client transactions method send() includes some functionality which is common for proxies an user agents, such as arranging &#8220;Route&#8221; headers and determining of remote address. This funcionality in fact belongs to another layer (as described <a href="http://technfun.wordpress.com/2008/07/10/lost-layer-of-sip/">here</a>).</p>
<p>Another purpose of transaction classes is to serve as protocol-level context. For example, it is possible to obtain original request. <span style="color:#0000ff;"><span style="color:#000000;"><em>ClientTransaction</em>s has method <em>createCancel()</em>, which should be in <em>MessageFactory</em>. </span></span></p>
<p><span style="color:#0000ff;"><span style="color:#000000;">In my opinion, cancellation in JAIN SIP API is done very badly, in the same BASIC style:</span></span></p>
<p style="text-align:left;"><span style="color:#0000ff;">10 Request cancel = clientTran.createCancel();</span></p>
<p style="text-align:left;"><span style="color:#0000ff;">20 ClientTransaction cancelTran = provider.createTransaction(cancel);</span></p>
<p style="text-align:left;"><span style="color:#0000ff;">30 cancelTran.sendRequest();</span></p>
<p><span style="color:#0000ff;"><span style="color:#000000;">instead of simple:</span></span></p>
<p><span style="color:#0000ff;">stack.cancel(request);</span></p>
<p><span style="color:#0000ff;"><span style="color:#000000;">which is not a subject to errors which can occur because of thread races. I mean: what will happen if a final response will be received between lines 20 and 30 ? JAIN SIP API doesn&#8217;t give you an answer. Since stack is a multithreaded module, sending should be done through &#8220;atomic&#8221; actions, doing several things at once by implementing internal locking.</span></span></p>
<p><span style="color:#0000ff;"><span style="color:#000000;">Another example of not taking threading issues into account is an existence of factory method for server transactions. I strongly believe that server transactions should be always implicitly created for incoming requests (except ACK, of course). Usefulness of stateless proxy is minimal, so attempt to support it in a way that JAIN SIP API does doesn&#8217;t justify the problems it brings. For example, what will happen if a retransmission is received while </span></span><span style="color:#0000ff;"><span style="color:#000000;">application has delayed a processing of incoming request ? Yes, a retransmission will be processed, and application will get an exception when it will try to create a server transaction for retransmitted request.</span></span></p>
<p><span style="color:#0000ff;"><span style="color:#000000;">Processing of incoming CANCEL is another weak point of JAIN SIP API. I think that it is a responsibility of stack to discover which server transaction should be cancelled, but JAIN SIP API makes it a work for application. But even if there would be a special CancelServerTransaction with method getCancelledTransaction(), this behaviour whould be plagued with threading issues. Thus, such improvement will be useful only if server transactions are created automatically.</span></span></p>
<p><span style="color:#0000ff;"><span style="color:#000000;">At least two implementations (NIST SIP and SIP from OpenCloud) do recognize that server transactions should be created automatically. NIST SIP creates a hidden &#8220;prototype&#8221; for a transaction. Stack of OpenCloud introduces a method on transaction which removes it. These are bad hacks, because problem should be fixed on API level.<br />
</span></span></p>
<p><span style="color:#0000ff;"><span style="color:#000000;">Transactions have method getDialog() which should return a dialog corresponding to that transaction. First, I don&#8217;t see any practical reason for this method. And second, what should this method do in case of dialog forking?<br />
</span></span></p>
<h3><span style="color:#0000ff;"><span style="color:#000000;">Dialogs</span></span></h3>
<p><span style="color:#0000ff;"><span style="color:#000000;">I&#8217;m more or less satisfied with implementation of dialogs in JAIN SIP API. There are several problems with them, but these problems are not as bad as in other areas.</span></span></p>
<p><span style="color:#0000ff;"><span style="color:#000000;">Existence of separate factory methods for normal requests and ACK is a bad idea. Method for incrementing local sequence number is a bad idea.</span></span></p>
<p><span style="color:#0000ff;"><span style="color:#000000;">Ability to set application context for dialog through setApplicationData() is a good thing. To have this method here is not as bad as for transactions, since dialogs live longer, so application context may change. Of course, changing application context can lead to complex errors because of threading, but it is still a useful thing.</span></span></p>
<p><span style="color:#0000ff;"><span style="color:#000000;">JAIN SIP API doesn&#8217;t describe how stack should behave in case of dialog forking. An instance of Dialog which was created by application will be returned with response from first destination. Responses from other destinations will return other dialogs, but how application will recognize them ? There are no event like &#8220;DialogForked&#8221; so application will know that new dialog is related to existing one.</span></span></p>
<h3><span style="color:#0000ff;"><span style="color:#000000;">Layering</span></span></h3>
<p><span style="color:#0000ff;"><span style="color:#000000;">JAIN SIP API is not a truly layered API. By looking at it you may think that <em>Dialog.sendRequest()</em> invokes <em>ClientTransaction.sendRequest()</em> which, in turn, invokes <em>SipProvider.sendRequest()</em>. While first may be true, the second can&#8217;t be, because both <em>ClientTransaction.sendRequest()</em> and <em>SipProvider.sendRequest()</em> perform the same actions which may modify the request (by exchanging &#8220;Route&#8221; header and request-URI if &#8220;Route&#8221; value doesn&#8217;t have &#8220;;lr&#8221;). Thus it is not possible to built your own transaction layer on top of SipProvider. It is also not possible to build your own dialog layer, because server dialogs should move to CONFIRMED state when succesfull response is sent through server transaction, or to TERMINATED state when unsuccesfull response is sent, but there are no means for your dialog to be notified about that.<br />
</span></span></p>
<h3><span style="color:#0000ff;"><span style="color:#000000;">SipListener and events</span></span></h3>
<p><span style="color:#0000ff;"><span style="color:#000000;">Application is notified about incoming messages and changes in state of objects through <em>SipListener</em> callback interface. There are just two methods for processing incoming messages: <em>processRequest()</em> and <em>processResponse()</em> so its an application job to dispatch a processing based on content of events. An implementation of these methods are usually trees of &#8220;if/else&#8221; operators which analyze transactions, dialogs and application data. A much better way would be to allow setting specific listeners for particular transactions and dialogs. These specific listeners would easily replace all application-provided contexts and will eliminate any dispatch code in application. Thus by applying IoC principle to full extent it is possible to turn stack into good protocol-based framework. (Update: I&#8217;ve explained this in more detail in <a href="http://technfun.wordpress.com/2009/07/13/is-network-stack-a-framework/">subsequent post</a>)<br />
</span></span></p>
<h3><span style="color:#0000ff;"><span style="color:#000000;">Conclusion</span></span></h3>
<p><span style="color:#0000ff;"><span style="color:#000000;">Let&#8217;s summarize all what I&#8217;ve said about JAIN SIP API.</span></span></p>
<p><span style="color:#0000ff;"><span style="color:#000000;">Advantages:</span></span></p>
<ul>
<li><span style="color:#0000ff;"><span style="color:#000000;">Syntax objects are separated from the behavioural part<br />
</span></span></li>
<li>Fairly complete</li>
<li><span style="color:#0000ff;"><span style="color:#000000;">Easy to understand and use for simple tasks by developers who like BASIC-style imperative programming</span></span></li>
<li><span style="color:#0000ff;"><span style="color:#000000;">Has semantics which is close to RFC</span></span></li>
<li><span style="color:#0000ff;"><span style="color:#000000;">Rather easy to implement</span></span></li>
<li><span style="color:#0000ff;"><span style="color:#000000;">Since it is not restrictive, it is flexible and extensible<br />
</span></span></li>
</ul>
<p><span style="color:#0000ff;"><span style="color:#000000;">Disadvantages:</span></span></p>
<ul>
<li>Parser for messages is not available</li>
<li>Stack management is unnesessary complex and restrictive</li>
<li>Transactions show implementation details rather and badly implement a protocol context</li>
<li><span style="color:#0000ff;"><span style="color:#000000;">Doesn&#8217;t help with productivity</span></span></li>
<li><span style="color:#0000ff;"><span style="color:#000000;">Thee ways to send a request. Two ways to send a response.<br />
</span></span></li>
<li>Is not fully complete. For example, doesn&#8217;t cover proxying.</li>
<li><span style="color:#0000ff;"><span style="color:#000000;">Doesn&#8217;t prevent you from doing mistakes</span></span></li>
<li><span style="color:#0000ff;"><span style="color:#000000;">Doesn&#8217;t allow you to override some layers<br />
</span></span></li>
<li><span style="color:#0000ff;"><span style="color:#000000;">It is not a real framework (expanded <a href="http://technfun.wordpress.com/2009/07/13/is-network-stack-a-framework/">here</a>)<br />
</span></span></li>
<li><span style="color:#0000ff;"><span style="color:#000000;">Has holes in specification<br />
</span></span></li>
</ul>
<p><span style="color:#0000ff;"><span style="color:#000000;">Be careful, you have been warned!</span></span></p>
<p>In <a href="http://technfun.wordpress.com/2009/05/19/java-sip-3/">next article</a> I&#8217;ll discuss SIP Servlets API.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/technfun.wordpress.com/138/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/technfun.wordpress.com/138/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/technfun.wordpress.com/138/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/technfun.wordpress.com/138/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/technfun.wordpress.com/138/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/technfun.wordpress.com/138/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/technfun.wordpress.com/138/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/technfun.wordpress.com/138/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/technfun.wordpress.com/138/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/technfun.wordpress.com/138/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/technfun.wordpress.com/138/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/technfun.wordpress.com/138/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/technfun.wordpress.com/138/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/technfun.wordpress.com/138/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=technfun.wordpress.com&amp;blog=1182547&amp;post=138&amp;subd=technfun&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://technfun.wordpress.com/2009/05/15/java-sip-2/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">kmatveev</media:title>
		</media:content>
	</item>
		<item>
		<title>Changing request URI for in-dialog requests</title>
		<link>http://technfun.wordpress.com/2009/05/14/changing-request-uri-for-in-dialog-requests/</link>
		<comments>http://technfun.wordpress.com/2009/05/14/changing-request-uri-for-in-dialog-requests/#comments</comments>
		<pubDate>Thu, 14 May 2009 16:07:26 +0000</pubDate>
		<dc:creator>kmatveev</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[SIP]]></category>
		<category><![CDATA[Sailfin]]></category>

		<guid isPermaLink="false">http://technfun.wordpress.com/?p=157</guid>
		<description><![CDATA[In SIP Servlets API there is a concept of &#8220;system headers&#8221; which cannot be changed, because it can violate SIP rules. An attempt to change these headers will result in throwing IllegalArgumentException from container. These headers can never be changed. But SIP rules are more complex. For in-dialog requests it is mandatory that request URI [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=technfun.wordpress.com&amp;blog=1182547&amp;post=157&amp;subd=technfun&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In SIP Servlets API there is a concept of &#8220;system headers&#8221; which cannot be changed, because it can violate SIP rules. An attempt to change these headers will result in throwing IllegalArgumentException from container. These headers can never be changed. But SIP rules are more complex. For in-dialog requests it is mandatory that request URI and &#8220;Route&#8221; headers will contain values obtained from dialog state. Thus, methods addHeader(&#8220;Route&#8221;), setHeader(&#8220;Route&#8221;), removeHeader(&#8220;Route&#8221;), pushRoute() and setRequestURI() should throw IllegalStateException for in-dialog requests. Unfortunatelly, it is not specified in SIP Servlets spec. Implementations also don&#8217;t fully follow those rules. For example, Sailfin will throw IllegalStateException upon pushRoute(), but will allow changing this header through addHeader(), setHeader() and removeHeader(). It will also allow you to change request URI for in-dialog request. Since SIP Servlet API strives for enforcing SIP rules, these things should be taken into account.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/technfun.wordpress.com/157/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/technfun.wordpress.com/157/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/technfun.wordpress.com/157/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/technfun.wordpress.com/157/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/technfun.wordpress.com/157/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/technfun.wordpress.com/157/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/technfun.wordpress.com/157/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/technfun.wordpress.com/157/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/technfun.wordpress.com/157/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/technfun.wordpress.com/157/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/technfun.wordpress.com/157/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/technfun.wordpress.com/157/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/technfun.wordpress.com/157/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/technfun.wordpress.com/157/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=technfun.wordpress.com&amp;blog=1182547&amp;post=157&amp;subd=technfun&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://technfun.wordpress.com/2009/05/14/changing-request-uri-for-in-dialog-requests/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">kmatveev</media:title>
		</media:content>
	</item>
		<item>
		<title>Adding headers through iterator</title>
		<link>http://technfun.wordpress.com/2009/03/02/adding-headers-through-iterator/</link>
		<comments>http://technfun.wordpress.com/2009/03/02/adding-headers-through-iterator/#comments</comments>
		<pubDate>Mon, 02 Mar 2009 11:48:31 +0000</pubDate>
		<dc:creator>kmatveev</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[SIP]]></category>
		<category><![CDATA[telecom]]></category>
		<category><![CDATA[JAIN SIP API]]></category>
		<category><![CDATA[Sailfin]]></category>

		<guid isPermaLink="false">http://technfun.wordpress.com/?p=129</guid>
		<description><![CDATA[Both JAIN SIP API and SIP Servlets API have method getHeaders(String headerName) on object representing a message (javax.sip.message.Message and javax.servlet.sip.SipServletMessage, respectively). This method returns ListIterator over all headers which have provided name. This iterator is a convenient way to go step-by-step through multi-value headers. Both APIs provide only very basic means of header manipulations. Method [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=technfun.wordpress.com&amp;blog=1182547&amp;post=129&amp;subd=technfun&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Both JAIN SIP API and SIP Servlets API have method <em>getHeaders(String headerName)</em> on object representing a message (<em>javax.sip.message.Message</em> and <em>javax.servlet.sip.SipServletMessage</em>, respectively). This method returns ListIterator over all headers which have provided name. This iterator is a convenient way to go step-by-step through multi-value headers.</p>
<p>Both APIs provide only very basic means of header manipulations. Method <em>addHeader()</em> adds a value always to the end of the list, and <em>removeHeader()</em> deletes all the headers with same name. Thus, an iterator provides a very convenient way to do more sophisticated actions, like insterting a header value into the middle of the list or removing a header value from the midde of the list. Without iterators, these actions whould require a combination of several <em>get()</em>/<em>add()</em>/<em>remove()</em> operations, complicating a code.</p>
<p>Unfortunatelly, APIs don&#8217;t explicitly specify if <em>add()</em>/<em>remove()</em>/<em>set()</em> operations of iterators should be supported. However, it seems that Sailfin and NIST implementation of JAIN SIP API do support it to some extent. Since both implementations have separate classes handling single-value headers (<em>SIPHeader</em> and <em>SingleLineHeader</em>, respectively) and multiple-value headers (<em>SIPHeaderList</em> and <em>MultiLineHeader</em>, respectively) there are also different classes for the iterators. Implemetation of <em>ListIterator</em> for multi-value headers is easy and straightforward, because both implementations use lists as storage of values and just re-use or wrap <em>ListIterator</em> of Java collection framework. Implementations of <em>ListIterator</em> for single-value header are written manually, and they are not full. In case of Sailfin, methods <em>add()</em>, <em>remove()</em> and <em>set()</em> are not implemented. In case of NIST SIP, methods <em>add()</em> and <em>set()</em> are not implemented.</p>
<p>Another interesting question is what should SIP stacks return if there are no headers with provided name ? To be consistent with other cases, a non-null iterator should be returned, having method <em>next()</em> throwing a <em>NoSuchElementException</em>, and having method <em>add()</em> adding new header to the message. After some header was added, iterator should support both navigation with <em>next()</em> and <em>previous()</em> and modification with <em>remove()</em>, <em>add()</em> and <em>set()</em>.</p>
<p>NIST SIP returns iterator over empty <em>LinkedList</em>. This iterator supports all modifier methods, but these modifications will be fake: message will not be modified. Sailfin returns iterator of EMPTY_LIST singleton of <em>java.util.Collections</em>. This iterator doesn&#8217;t implement modifiers.</p>
<p>Hey you guys other there! You don&#8217;t support corner cases properly. Fix up your code, and don&#8217;t forget to give me a credit for finding these bugs (just kidding).</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/technfun.wordpress.com/129/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/technfun.wordpress.com/129/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/technfun.wordpress.com/129/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/technfun.wordpress.com/129/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/technfun.wordpress.com/129/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/technfun.wordpress.com/129/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/technfun.wordpress.com/129/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/technfun.wordpress.com/129/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/technfun.wordpress.com/129/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/technfun.wordpress.com/129/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/technfun.wordpress.com/129/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/technfun.wordpress.com/129/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/technfun.wordpress.com/129/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/technfun.wordpress.com/129/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=technfun.wordpress.com&amp;blog=1182547&amp;post=129&amp;subd=technfun&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://technfun.wordpress.com/2009/03/02/adding-headers-through-iterator/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">kmatveev</media:title>
		</media:content>
	</item>
		<item>
		<title>Networking in Java: non-blocking NIO, blocking NIO and IO</title>
		<link>http://technfun.wordpress.com/2009/01/29/networking-in-java-non-blocking-nio-blocking-nio-and-io/</link>
		<comments>http://technfun.wordpress.com/2009/01/29/networking-in-java-non-blocking-nio-blocking-nio-and-io/#comments</comments>
		<pubDate>Thu, 29 Jan 2009 16:09:25 +0000</pubDate>
		<dc:creator>kmatveev</dc:creator>
				<category><![CDATA[Concurrent programming]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[networking]]></category>
		<category><![CDATA[NIO]]></category>

		<guid isPermaLink="false">http://technfun.wordpress.com/?p=120</guid>
		<description><![CDATA[Standard run-time library in Java provides two interfaces for networking. One, which exists in Java since the beginning, is called &#8220;basic IO&#8221;, because it is based on generic framework of  &#8220;input streams&#8221; and &#8220;output streams&#8221; defined in package &#8220;java.io&#8221;. Sun did a good thing by providing uniform way for accessing files and sockets, following a [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=technfun.wordpress.com&amp;blog=1182547&amp;post=120&amp;subd=technfun&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Standard run-time library in Java provides two interfaces for networking. One, which exists in Java since the beginning, is called &#8220;basic IO&#8221;, because it is based on generic framework of  &#8220;input streams&#8221; and &#8220;output streams&#8221; defined in package &#8220;java.io&#8221;. Sun did a good thing by providing uniform way for accessing files and sockets, following a Unix philosophy. However, there are some drawbacks in stream-based access, so Sun created another set of interfaces located in &#8220;java.nio&#8221; package. This package also provides uniform access to files and sockets, and is much more flexible than basic IO.</p>
<p>Main problem with basic IO was scalability to number of connections. Operation <em>read()</em> will block until some data will become available. It is not a problem if your program accesses files, because file operations never block for a long time. You are just reading the data until you&#8217;ll reach the end of file. Reading after the end of file will immediatelly return with &#8220;-1&#8243; bytes read. Another good thing is most programs usually access quite small amount of files. In other words, when working with files it is data who is waiting for program to process it, while program can decide what size of internal buffer to use for processing.</p>
<p>But with networking a model of basic IO is not so convenient. First, <em>read()</em> operation may block an execution thread for a long time. This means that to handle several connections simultaneously you&#8217;ll need as many threads as the amount of incoming connections you have. There is a small thing which can help you not to block forewer: you can specify a timeout for socket operations. But it will not solve a scalability problem.</p>
<p>Another problem is related to &#8220;message&#8221;-based structure of most protocols. Often you don&#8217;t know how much data you&#8217;ll receive. So, you have to organize your code in a special way:</p>
<ul>
<li>Always read data by one byte, then assemble data array from those bytes. Code is simple, but slow.</li>
<li>Read one byte first, then use <em>available()</em> method to determine if there are more data to read. If there are, then read remaining data using bulk operation. Code is more complex, but faster then previous way.</li>
</ul>
<p>NIO helps you to deal with both these problems. I&#8217;ll explain them in a way which seems to me most logical.</p>
<p>First, NIO introduces &#8220;Buffers&#8221; which are used to combine data and information used to process it. There are also &#8220;Channels&#8221; which can read into buffers and write from buffers.</p>
<p>To simplify your &#8220;basic IO&#8221; code you can just call <em>Channels.newChannel()</em> method for your input stream. The resulting channel will implement <em>read()</em> operation which will either block fill provided <em>ByteBuffer</em> with data and moving position to a place right after last byte. This makes code much more simple.</p>
<p>You can avoid wrapping by creating <em>SocketChannel</em> directly. This will get you almost the same result. It is called &#8220;blocking NIO&#8221;, and I strongly advise using it in simple cases, when thread blocking is not a problem for you.</p>
<p>The only difference between &#8220;blocking NIO&#8221; and &#8220;NIO wrapped around IO&#8221; is that you can&#8217;t use socket timeout with <em>SocketChannels</em>. Why ? Read a javadoc for <em>setSocketTimeout()</em>. It says that this timeout is used only by streams. However, you can use a trick to make it working:</p>
<p style="text-align:left;"><span style="color:#0000ff;">SocketChannel socketChannel;</span></p>
<p style="text-align:left;"><span style="color:#0000ff;">socketChannel.socket().setSocketTimeout(500);</span></p>
<p style="text-align:left;"><span style="color:#0000ff;">InputStream inStream = </span><span style="color:#0000ff;">socketChannel.socket().getInputStream();</span></p>
<p style="text-align:left;"><span style="color:#0000ff;">ReadableByteChannel wrappedChannel = Channels.newChannel(inStream);</span></p>
<p style="text-align:left;">In this example, reading from <em>socketChannel</em> directly will not be interrupted by timeout, but reading from <em>wrappedChannel</em> will be. To find out why it is so, you can take a look inside Java RT library. Socket timeout is used by OS-specific implementation of SocketInputStream, but is is not used by OS-specific implementation of SocketChannel.</p>
<p>However, NIO has much better things to solve a scalability problem. First, you can put a channel into non-blocking mode. This means that read() operation will return immediatelly if there are no data to read. Thus, you can create a single thread which will check all SocketChannels in cycle and read a data if it is available.</p>
<p>Having a single thread is nice, but if it will spin around read() operation it will waste lots of CPU cycles. To help with the performance NIO has a class called &#8220;Selector&#8221; which WILL block on non-blocking channels. The difference is that it can monitor any amount of channels, resuming execution when at least one of those channels has some readable data. This idea was copied from Unix, but with one big flaw: Selector can use only non-blocking channels.</p>
<p>I don&#8217;t know why Sun has introduced this limitation. This article focuses on reading, but both basic IO and NIO also support writing. Since a blocing/non-blocking mode applies both to read and write directions simultaneously, then usage of Selector makes <em>connect()</em> and <em>write()</em> operations more complex. Anyway, it is the only way to have only one thread reading from several network connections.</p>
<p>Let&#8217;s finish for today. It&#8217;s quite easy to understand what to use. If scalability is an issue, then use &#8220;non-blocking NIO&#8221;. Otherwise, use &#8220;blocking NIO&#8221; with thread per connection. You can make those threads as daemons so they will not prevent application from termination when all other threads will stop. Another way to stop those threads is to close channels they are reading from. This will cause a read operation to interrupt with exception.</p>
<p>I hope I&#8217;ve shown that NIO is simple. So, don&#8217;t use <a href="http://technfun.wordpress.com/2008/04/21/critique-of-java-nio-frameworks/">NIO frameworks</a>. They are bad.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/technfun.wordpress.com/120/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/technfun.wordpress.com/120/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/technfun.wordpress.com/120/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/technfun.wordpress.com/120/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/technfun.wordpress.com/120/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/technfun.wordpress.com/120/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/technfun.wordpress.com/120/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/technfun.wordpress.com/120/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/technfun.wordpress.com/120/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/technfun.wordpress.com/120/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/technfun.wordpress.com/120/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/technfun.wordpress.com/120/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/technfun.wordpress.com/120/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/technfun.wordpress.com/120/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=technfun.wordpress.com&amp;blog=1182547&amp;post=120&amp;subd=technfun&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://technfun.wordpress.com/2009/01/29/networking-in-java-non-blocking-nio-blocking-nio-and-io/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">kmatveev</media:title>
		</media:content>
	</item>
	</channel>
</rss>
