<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Chanaka Balasooriya on Medium]]></title>
        <description><![CDATA[Stories by Chanaka Balasooriya on Medium]]></description>
        <link>https://medium.com/@chanakadkb?source=rss-667e7af8d35e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*zY77C2JboRLITtxXS6ZFRw@2x.jpeg</url>
            <title>Stories by Chanaka Balasooriya on Medium</title>
            <link>https://medium.com/@chanakadkb?source=rss-667e7af8d35e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 12:34:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@chanakadkb/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[What, Why and How Fiscalisation]]></title>
            <link>https://medium.com/@chanakadkb/what-why-and-how-fiscalisation-5f79f4d6fabc?source=rss-667e7af8d35e------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f79f4d6fabc</guid>
            <category><![CDATA[fiscal-policy]]></category>
            <category><![CDATA[pos]]></category>
            <category><![CDATA[taxes]]></category>
            <dc:creator><![CDATA[Chanaka Balasooriya]]></dc:creator>
            <pubDate>Mon, 09 Sep 2019 01:42:44 GMT</pubDate>
            <atom:updated>2019-09-09T01:42:44.231Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*E3DpqgQkWhwY1lzpo4ZMuA.jpeg" /></figure><p>Value-added tax is one of the major income paths for any state except very few countries in the world. Calculation, recording and presenting of taxes of good and services was never an easy task for any retailer. Moreover, frauding financial reports, losing transaction records and complexity of time and resources to calculate taxes led the government intervention to regulate this process.</p><blockquote>Fiscalisation is the process of calculating, persisting and presenting tax amounts of retailers based on the state’s financial acts.</blockquote><p>Even though the countries follow their own methods for fiscalisation, they can be clearly classified into few categories as printer-based solutions, signature-based solutions, service-based solutions and hybrid solutions</p><p>In printer based solutions, the government has enforced to use a particular set of printers to print receipts at the point of sales. Those printers are known as fiscal printers and it is amusing to know that these printers have some special features that we can’t see in normal receipt printers. Recoding the transaction details, generating receipts based on its own templates, producing financial reports whenever requested and calculating tax amounts are some of such distinctive attributes. <strong>The memory or the fiscal module of the printer can be accessed only by tax authorities and hence, transactions details are kept safe in the printer.</strong></p><p>Another interesting category is signature-based fiscalisation which requires each transaction to be signed digitally before persisting them. Here, the retailer has to have a private-public key pair and sometimes the law defines how it should be generated including the length and the algorithm. It can be seen that there are few organizations who provide smart cards or REST APIs to generate signatures for the given transaction details. However, the basic concept of this module is, encrypting transaction details along with the signature of the previous transaction, generating a signature for those encrypted details and save that as an attribute of the current transaction as well as printing it on the receipt. <strong>As each transaction is bound with the previous transaction, it is hard to alter or delete transactions after they are recorded.</strong></p><p>With the development of IT infrastructure, there’s a trend that states are moving into service-based solutions which <strong>each transaction is required to be sent to a central server managed by the government tax authorities</strong>. In the point of retailers view, this seems a good solution as they don’t have to worry about operating separate devices as well as protection of transaction details. But 24x7 availability of the server cannot be assured and hence almost all countries using this kind of mechanisms have introduced an offline transaction processing mechanism as well.</p><p>To overcome the drawbacks of each of the above categories some countries have introduced hybrid solutions combining at least two of the above solutions.</p><p>Fiscalisation is not a process that can be adapted in one day and it requires lots of negotiations as well as practices. Sometimes it consumes a lot more resources than the conventional tax calculation methods and I don’t think we still have the optimal solution. Overhead of certification processes, regulating PoS software and inspection of shops and stores needs to be carefully handled and the overall concept requires to be evolved lot more.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f79f4d6fabc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bitmap Indexing vs Bit-slice Indexing]]></title>
            <link>https://medium.com/@chanakadkb/bitmap-indexing-vs-bit-slice-indexing-ee34086e23b7?source=rss-667e7af8d35e------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee34086e23b7</guid>
            <category><![CDATA[data-warehouse]]></category>
            <category><![CDATA[bitslice]]></category>
            <category><![CDATA[bitmap]]></category>
            <dc:creator><![CDATA[Chanaka Balasooriya]]></dc:creator>
            <pubDate>Sun, 24 Sep 2017 09:26:22 GMT</pubDate>
            <atom:updated>2017-09-24T09:26:22.659Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Indexing is a technique that is used to speed up data retrieving and query processing in databases and OLAP data warehouses. There are lots of indexing schemes such as Value-List Indexing, B-Tree and Projection Indexing. Bitmap and Bit-slices are two cutting edge indexing techniques and we are going to compare them under several criteria.</blockquote><p><strong>General Usage</strong></p><p>Bitmap indexing is basically used for indexing dimension(or String) columns of a database table such as Name and Country. But Bit-slice indexing is generally used for Metric (or Numeric) columns.</p><p><strong>Initialization</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/194/1*D6m_i7-LUKiAqpU9A4UZGA.jpeg" /><figcaption>Table 1: Sample data table</figcaption></figure><p>Consider the Table 1. The column country is a dimension column and we can create a bitmap index for that column. In Bitmap indexing we create a bitmap for each distinct row value of the column.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/194/1*RiYKeVg5EjdV63Kt0Ib57g.jpeg" /><figcaption>Table 2: Bitmaps of column Country</figcaption></figure><p>As you can see in Table 2, if we consider the country value Australia, since it is the value of first row we put 1 in first column of bitmap for Sri Lanka and we put 0 in second row since 2nd row of Country column is not Sri Lanka. Likewise we fill 1s and 0s in each bitmap. So, number of bitmaps depends on number of distinct values of the column (column cardinality).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/144/1*ZWxsGr09sapAq2sCJnfmiA.jpeg" /><figcaption>Table 3: Bit-slices of column Visits</figcaption></figure><p>Let’s consider number of visits column for creating a bit-slice index. here we convert each number into bit-string and create a bitmap for each bit-position as you can see in Table 3. So, the number of bitmaps for bit-slice indexing depends on the largest value of the column.</p><p><strong>Operations</strong></p><p>Bitmap outperforms in select operations with where clause. For an example if we need to select rows of country value is USA or Australia we can just get OR operation between bitmaps for USA and Australia.</p><p>Bitslice outperforms in aggregation operations such as sum, count. for an example if we need to get the sum of all visits, we just need to take a count on number of ‘1’s in each bit-slice. Then sum can be calculated as follows,</p><p>sum = (2^0*count_1s_in_B0)+(2^1*count_1s_in_B1)+(2^2*count_1s_in_B2)+(2^3*count_1s_in_B3)</p><p>Therefor we do not need to iterate through each row to perform those queries.</p><p><strong>Implementations</strong></p><p>Even though both bitmap and bitslice can be used to improve query performance, the main drawback of them is large space requirement. to overcome that problem it is necessary to use appropriate compression schemes to compress bitmaps. Roaring bitmap, Fastbit and Concise bitmap are such widely used compression schemes.</p><p>It is possible to find some databases/data warehouses that uses bitmap indexing such as Druid and Spark. But it hard to find a database/data-warehouse that uses bitslice indexing instead of Sybase IQ.</p><p><strong>References</strong></p><p>Rinfret, Denis, Patrick O’Neil, and Elizabeth O’Neil. “Bit-sliced index arithmetic.” <em>ACM Sigmod Record</em>. Vol. 30. №2. ACM, 2001.</p><p>O’Neil, Patrick, and Dallan Quass. “Improved query performance with variant indexes.” <em>ACM Sigmod Record</em>. Vol. 26. №2. ACM, 1997.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee34086e23b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Do you know HTTP/2 Server-Push]]></title>
            <link>https://medium.com/@chanakadkb/do-you-know-http-2-server-push-8f374d05bfa6?source=rss-667e7af8d35e------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f374d05bfa6</guid>
            <category><![CDATA[http2]]></category>
            <category><![CDATA[server-push]]></category>
            <dc:creator><![CDATA[Chanaka Balasooriya]]></dc:creator>
            <pubDate>Sun, 24 Sep 2017 07:45:57 GMT</pubDate>
            <atom:updated>2017-09-24T07:52:05.403Z</atom:updated>
            <content:encoded><![CDATA[<p>Server-push is not a new concept for those who have worked with protocols like SMTP, Websocket and SPDY. Basically it means that the server is capable of sending resources to the client without a request from the client. But the implementation of server-push varies from protocol to protocol.</p><p>In Websocket API, the server can push data to any connected client whenever it needs. But in HTTP/2 it is slightly different. HTTP/2 server cannot push data whenever it wants without a client’s request.</p><p>Wait… It means in HTTP/2, server-push is triggered only according to the client’s request.Yes, as an example we can configure a server to send server-push binding .css files that is necessary for a requested html page (see Figure 1).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*JBI1bFVuGmkK7sdpPGuUQg.png" /><figcaption>Figure 1</figcaption></figure><p>Then how do we know a server push is coming from a server? Well, HTTP/2 handles it using its frames. Whenever a server needs to send a server push, it sends a PUSH_PROMISE frame including method, stream id and other necessary header fields to the client with the response to the client’s request. Thereafter the push-data is sent using a server initiated stream including HEADER and DATA frames.</p><p>According the implementation of HTTP/2, those server push responses are sent to client before the response of the client’s original request to prevent client from sending requests for those pushed data again.</p><p>If the server is not authorized or the responses are not cacheable client can send a stream error frame rejecting server push. Moreover server-push stream must not exceed the client’s maximum concurrent streams limit.</p><p>A sample implementation of HTTP/2 server push can be found at <a href="https://medium.com/@chanakadkb/lets-make-server-push-enabled-http-2-server-with-netty-1e54134dc90b">Let’s make server-push enabled server with Netty</a>.</p><p>Thank you for reading this article.</p><p>see you again…!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f374d05bfa6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let’s design the game “Place the eye on elephant” using cryptography]]></title>
            <link>https://medium.com/@chanakadkb/lets-place-the-eye-on-elephant-using-cryptography-bea8770f4233?source=rss-667e7af8d35e------2</link>
            <guid isPermaLink="false">https://medium.com/p/bea8770f4233</guid>
            <category><![CDATA[information-security]]></category>
            <category><![CDATA[cryptography]]></category>
            <dc:creator><![CDATA[Chanaka Balasooriya]]></dc:creator>
            <pubDate>Mon, 03 Jul 2017 13:20:57 GMT</pubDate>
            <atom:updated>2017-07-03T13:23:16.994Z</atom:updated>
            <content:encoded><![CDATA[<p>“Place the eye on elephant” is a traditional New Year game in Sri Lanka. Each competitor is blindfolded and given a chalk to spot the position of eye on a blackboard on which has been drawn a picture of the side view of an elephant without an eye. Moreover, the blindfolded player is moved around to disorient the player.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/0*L0s3OYvz70ET1wF0.jpg" /><figcaption>Placing eye on elephant — Traditional New Year game</figcaption></figure><p>Recently when I was studying in Information Security and Cryptography lecture, I found an interesting question on designing an online version of “Place the eye on elephant” game.</p><p>So, “Online place the eye on elephant” has following properties,</p><ol><li>The game has two parties who are game-master and players.</li><li>Players can see where the other players put the eye.</li><li>Winner is the player who places the eye closest to the actual eye.</li></ol><p>Moreover we need to achieve following security requirements.</p><ol><li>It should not be possible for any subgroup of players to collude and cheat.</li><li>It should not be possible for game master and other players to help the current player.</li><li>It should not be possible for game-master to declare someone else as the winner.</li><li>Each placing request should be integrity protected.</li></ol><p>So how are we going to design the game achieving those security requirements?</p><p>Since this is an online game, we have to hide the game-board instead of blindfolding the player and disorient the elephant instead of the player as well. To prevent players from colluding and helping each other we need to show different game-board orientations to each player or hide the orientation of the elephant till the end of the game. We need to make sure that game-master does not know the position of actual eye as well. Showing each players played spot to everyone we can prevent from declaring someone else as the winner.</p><p>One possible solution is providing an interactive game-board to mark players’ spots. So every other player can see the other players’ guess spots. Since any player does not know the orientation of the elephant, collusion is prevented. Then we need to think of how the elephant is oriented as we do not trust the game master. Even though the system can generate a random orientation for the elephant and broadcast it, players cannot assure whether it is not something that game-manager generated. So the orientation should be generated from some values which were collected from players. We can design the system, asking each player at the beginning to submit a guessing point for the orientation of the elephant. So the system can calculate and get the average of the points as the orientation of the elephant.</p><p>Now again we face two problems. One is the orientation positions should be blind till the end of the game to make sure that game-manager cannot calculate and know the actual elephant orientation till the end of the game. To avoid that each player can submit a blind/encrypted orientation position and provide the decryption key at the end of the game. We can use a temporary generated public key pair for the encryption.</p><p>The next problem is if the majority of players colluded to submit a same orientation position, it will become the average position. To avoid that we can get a hash value from each submission combined with a time-stamp of each submission arrived time.</p><p>To protect integrity and authenticity of messages, a public key signature can be passed along with each message.</p><p>So the final design will look like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*bFFTeWWvyQCQcYXvlM_oOg.png" /></figure><p>One problem of this solution is each player needs to submit their temporary private key in order to calculate the orientation of the elephant. So if a player could not submit it within a given time period at the end of the game, he will be dismissed from the game.</p><p>If you have any doubts or suggestions, feel free to share with me.</p><p>Thank you …!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bea8770f4233" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why You Should Not Keep A Diary]]></title>
            <link>https://medium.com/@chanakadkb/why-you-should-not-keep-a-diary-61bda6a6bf1a?source=rss-667e7af8d35e------2</link>
            <guid isPermaLink="false">https://medium.com/p/61bda6a6bf1a</guid>
            <category><![CDATA[diary]]></category>
            <category><![CDATA[motivation]]></category>
            <category><![CDATA[lifestyle]]></category>
            <category><![CDATA[people]]></category>
            <dc:creator><![CDATA[Chanaka Balasooriya]]></dc:creator>
            <pubDate>Sun, 02 Jul 2017 09:15:32 GMT</pubDate>
            <atom:updated>2017-07-02T09:15:32.647Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BE-Zgxmu9qeL-3Zj.jpg" /><figcaption>http://i.huffpost.com/gen/1883707/images/o-DIARY-facebook.jpg</figcaption></figure><p>Recently when I was cleaning my book-rack, some of my old diaries caught my eye. I love them very much because even though I started to write a diary to plan my studies it eventually became a daily habit of mine. So I sat down at my table and started to read them one by one appreciating myself for writing down them because I was so excited to read my own autobiography.</p><p>I’ve been writing diaries since I was 16 and I was preparing for O/L exam at that time. As a teenager and a pupil I had lots of dreams which I don’t remember most of them today. But when I was reading them I felt that those diaries are logbooks of my dreams. I have heard that once late Indian president Dr. Abdul Kalam had said “You have to dream before your dreams can come true”. I started to think that my diaries are some real proofs of that utterance. My biggest childhood dream was to become an engineer and I saw that all my other dreams were converging to that big dream. Do you remember the Stanford speech of Steve Jobs? He said “You cannot connect the dots looking forward. You can only connect them looking backwards”. I started to believe that statement. <strong>So if you don’t want to connect your dots, don’t keep a diary.</strong></p><p>A diary can embarrass yourself<strong>. </strong>Have you ever found any book you used to write or any painting you drew or any kind of handicraft you made when you were in kindergarten or primary school. I am pretty sure if you could find you would laugh at yourself. I felt shameful of some of my past thoughts and activities. It is because the way we see the world, the way we think and the way we define tend to change with experiences. Some decisions we take today might be felt totally wrong tomorrow. <strong>So if you don’t have a diary you can just forget all your stupidities.</strong></p><p>A famous American Basketball player has said that “I missed more than 9000 shots in my career. 26 times I was trusted to take the game winning shot and missed. I’ve failed over and over and over again in my life. And that is why I succeed”. Our failures are the teachers of our success. When I read my diary I found sometimes I had failed and sometimes I had succeeded. But the interesting thing is that I can understand why I failed and why I succeed by just reading the diary. <strong>So if you don’t want to figure out your mistakes, don’t keep a diary.</strong></p><p>I remember the interview which I faced for my internship. The first question I was asked was to describe myself. That’s the most difficult question that anybody has to answer. Understanding ourselves is a tricky task even though it seems trivial. It is true that nobody does not know about yourself than you but most of the time you are the last one who identifies your faults. We go before a mirror to make sure we are perfect in outer appearance. The diary is the mirror that reflects your thoughts and behaviours. <strong>So if you don’t need to see the reflection of yourself there’s no point of having a diary.</strong></p><p>It is a common thing to be stuck yourself in your tight schedules and having high stress. One thing I do when I am in stress is listing down all the activities I have to do in a paper. It gives me an overall idea of what to do and releases the stress. Diaries can do the same thing. You can mention what you have done so far and what you are going to do next in your diary. Actually it increases your confidence level. When you are on sick bed it makes some comfort to read your previous diaries. <strong>So if you are good at stress management, you don’t need a diary.</strong></p><p>The great philosopher, Socrates has said “To find yourself think for yourself”. As a leisure activity if will be enjoyable to write about yourself, think about yourself and plan your future. Some psychologists say appreciating yourself increases your mental strength. A diary is a good place to appreciate and salute yourself. It is often to see greetings such as Happy New Year, Good Evening, Good Night and Happy Holiday in my diaries and when I am reading them back again I can’t help smiling.<strong> So if you have rich leisure activities you better do them instead of worrying to keep a diary.</strong></p><p>That’s all I wanted to share with you and thank you for reading this. You are always welcome to share your thoughts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61bda6a6bf1a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Overhead of Parallelism]]></title>
            <link>https://medium.com/@chanakadkb/overhead-of-parallelism-d1d3c43abadd?source=rss-667e7af8d35e------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1d3c43abadd</guid>
            <category><![CDATA[parallelism]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[parallel-computing]]></category>
            <dc:creator><![CDATA[Chanaka Balasooriya]]></dc:creator>
            <pubDate>Mon, 08 May 2017 12:48:44 GMT</pubDate>
            <atom:updated>2017-05-08T12:53:17.233Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/832/0*dVfKdOnartAsiJhL.jpg" /><figcaption><a href="https://thestack.com/wp-content/uploads/2015/03/highway-traffic-main-2-832x470-832x333.jpg">https://thestack.com/wp-content/uploads/2015/03/highway-traffic-main-2-832x470-832x333.jpg</a></figcaption></figure><blockquote>Many programmers think that doing multiple tasks simultaneously increases the performance of a computer program. But it is high time to reconsider whether it is true and know the cost of parallelism.</blockquote><p>It is true that parallel computing has lots of advantages and usages. Some problems we meet can be solved only using parallelism. Rendering animations, weather prediction, cloud computing and traffic controlling are some of them. We can see various real world examples of parallelism such as bee or ant colony. We can use parallelism as a mechanism to fully utilize our computers since our computers are implemented to do things simultaneously .</p><p>Lets do some funny calculations using <a href="https://en.wikipedia.org/wiki/Amdahl%27s_law">Amdahl’s Law</a> to see how much parallelism improves the productivity of a computer program. Before that as you know there are two parts of any program known as sequential part (i.e. part that cannot be run parallel) and parallel part. For this calculation lets assume we are using 10 processors to run parallel part simultaneously. If the parallel part is 60% and sequential part is 40%, according to the Amdahl’s low we can gain 2.17 speed up by following equation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/964/0*SC9ChFLXNC9zaFqu.png" /></figure><p>Here is how speed up differing with respect to parallel part of a program,</p><p><em>parallel part 80% — speed up 3.57</em></p><p><em>parallel part 90% — speed up 5.26</em></p><p><em>parallel part 99% — speed up 9.17</em></p><p>As you can see above we could not get 10 times speed up even using 10 processors and 99% of parallelism. But in reality having 99% parallelism is very hard and very rare in many problems and having 10 processors also so costly.</p><p>So we cannot get much efficiency as we expected using multiple cores and parallelism. Instead of that Amdahl’s law we can listed down various other costs we have to overcome when dealing with parallelism as follows,</p><ol><li>Task(Thread or Process) start up and termination cost.</li><li>Synchronization problems</li><li>Cost of communication among multiple tasks.</li><li>Software overhead of libraries, parallel compiler and supportive OS.</li><li>Complexity of designing, coding, debugging and maintenance.</li></ol><p>So if you are designing a system integrating parallelism, you should be more careful about those costs and try to mitigate them as much as possible.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1d3c43abadd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let’s make server-push enabled HTTP/2 server with Netty]]></title>
            <link>https://medium.com/@chanakadkb/lets-make-server-push-enabled-http-2-server-with-netty-1e54134dc90b?source=rss-667e7af8d35e------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e54134dc90b</guid>
            <category><![CDATA[http2]]></category>
            <category><![CDATA[server-push]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Chanaka Balasooriya]]></dc:creator>
            <pubDate>Sun, 26 Mar 2017 14:53:34 GMT</pubDate>
            <atom:updated>2017-03-28T12:26:03.964Z</atom:updated>
            <content:encoded><![CDATA[<p>As a open-source software library,<a href="http://netty.io/"> Apache Netty</a> plays a huge role when implementing servers and clients in Java. Even though they have shown how to implement a simple HTTP/2 server, many programmers have to face some difficulties when they need to catch all HTTP/2 frames that client sends and to enable HTTP/2 specific features like server-push. So, I’m going to implement a simple HTTP/2 server that can send and receive any frame under HTTP/2 spectrum.</p><h3>Here we go …</h3><p>Start Maven project including netty-all as a dependency.</p><p>We will create 4 java classes to build up our server</p><ol><li>FrameListner.java — Listen to each frame data, wrap them with an appropriate object and expose for the rest of the program.</li><li>ServerInitializer.java — Initilize the Connnection and register our listeners and handlers.</li><li>RequestHandler.java — Handle the requests and send responses.</li><li>Server.java — Our application main class.</li></ol><h3>Frame Listener</h3><p>Frame listener inherits netty’s Http2EventAdapter class that exposes events for all HTTP/2 frame types. Since we only care about http/2 GET requests for this application I am going to override onHeadersRead method only. I will create a HTTP2HeadersFrame object with the event data as follows.</p><pre><strong>public void </strong>onHeadersRead(ChannelHandlerContext ctx, <strong>int </strong>streamId, Http2Headers headers, <strong>int </strong>streamDependency, <strong>short </strong>weight, <strong>boolean </strong>exclusive, <strong>int </strong>padding, <strong>boolean </strong>endStream) <strong>throws </strong>Http2Exception {<br>        Http2HeadersFrame frame=<strong>new  </strong>DefaultHttp2HeadersFrame(headers,endStream,padding).setStreamId(streamId);<br>        ctx.fireChannelRead(frame);<br>    }<br>}</pre><p>You can override onDataRead method to accept data frames for our server with the help of DefaultHttp2DataFrame object.</p><h3>Server Initializer</h3><p>Server Initializer inherits ChannelInitializer class and overrides its initChannel method as follows. We create a HTTP2Connection and register our Frame Listener and Request Handler as follows.</p><pre>protected void initChannel(SocketChannel socketChannel) throws Exception {<br>        Http2Connection connection = new DefaultHttp2Connection(true);<br>        FrameListener frameListener = new FrameListener();<br>        Http2ConnectionHandler connectionHandler = new Http2ConnectionHandlerBuilder().connection<br>                (connection).<br>                frameListener(frameListener).frameLogger(logger).build();<br>     RequestHandler requestHandler=new RequestHandler(connection,connectionHandler.encoder());<br>        socketChannel.pipeline().addLast(connectionHandler,<br>                requestHandler);<br>    }<br>}</pre><h3>Request Handler</h3><p>We handle each client request by its request’s URL. we define two URLs to reply including server push and without server push. If client request with URL “/index.html”, server will send index.html data and if the URL is “/main.css”, it will send main.css file. If the URL is “/all” server will response index.html with a server push of main.css file.</p><p>Before sending a server push we need to send a push-promise frame to the client saying we are going to send main.css file as a serverpush as follows,</p><pre><strong>int </strong>prmiseId=<strong>connection</strong>.local().incrementAndGetNextStreamId(); //get next available id.<br>Http2Headers prmiseHeader=<strong>new </strong>DefaultHttp2Headers();<br>prmiseHeader.scheme(frame.headers().scheme()).<br>        path(<strong>&quot;main.css&quot;</strong>).<br>        add(HttpHeaderNames.<strong><em>CONTENT_TYPE</em></strong>,<strong>&quot;text/css&quot;</strong>);</pre><pre>ChannelPromise promise=ctx.newPromise();<br><strong>encoder</strong>.writePushPromise(ctx,frame.streamId(),prmiseId,prmiseHeader,0,promise);</pre><p>Then we write actual data of main.css under above promiseId,</p><pre><strong>encoder</strong>.writeHeaders(ctx,prmiseId,prmiseHeader,0,<strong>false</strong>,promise);<br><strong>encoder</strong>.writeData(ctx,prmiseId,promiseDATABuff,0,<strong>true</strong>,promise);</pre><p>Finally we write requested data (index.html) and flush all bytes.</p><pre><strong>encoder</strong>.writeHeaders(ctx,frame.streamId(),responseHeader,0,<strong>false</strong>,promise);<br><strong>encoder</strong>.writeData(ctx,frame.streamId(),htmlBuf,0,<strong>true</strong>,promise);</pre><pre>ctx.flush();</pre><p>As you can see encoder object can be used to write any frame to the channel.</p><p>Most of the client applications that support HTTP/2, only support for HTTP/2 over TLS or HTTPS connections. In order to use this server with those clients it is better to implement server to establish connections as HTTP/2 over TLS.</p><p>You need to create a SSLContext and register it on the connection while overriding initChannel method in ServerInitilizer class as follows,</p><pre>io.netty.handler.ssl.SslContext sslCtx=createSSLContext();<br>socketChannel.pipeline().addLast(<strong>sslCtx</strong>.newHandler(socketChannel.alloc()), connectionHandler,<br>        reqeustHandler);</pre><p>For this example I have created a self-signed-certificate with jetty ALPN library.</p><pre><strong>private </strong>SslContext createSSLContext(){<br>    SslContext sslCtx;</pre><pre>    <strong>try </strong>{<br>        SslProvider provider = OpenSsl.<em>isAlpnSupported</em>() ? SslProvider.<strong><em>OPENSSL </em></strong>: SslProvider.<strong><em>JDK</em></strong>;<br>        SelfSignedCertificate ssc = <strong>new </strong>SelfSignedCertificate();<br>        sslCtx = SslContextBuilder.<em>forServer</em>(ssc.certificate(), ssc.privateKey())<br>                .sslProvider(provider)<br>                .ciphers(Http2SecurityUtil.<strong><em>CIPHERS</em></strong>, SupportedCipherSuiteFilter.<strong><em>INSTANCE</em></strong>)<br>                .applicationProtocolConfig(<strong>new </strong>ApplicationProtocolConfig(<br>                        ApplicationProtocolConfig.Protocol.<strong><em>ALPN</em></strong>,                     ApplicationProtocolConfig.SelectorFailureBehavior.<strong><em>NO_ADVERTISE</em></strong>,<br>ApplicationProtocolConfig.SelectedListenerFailureBehavior.<strong><em>ACCEPT</em></strong>,<br>                        ApplicationProtocolNames.<strong><em>HTTP_2</em></strong>,<br>                        ApplicationProtocolNames.<strong><em>HTTP_1_1</em></strong>))<br>                .build();<br>    }<strong>catch </strong>(Exception e){<br>        sslCtx=<strong>null</strong>;<br>    }<br>    <strong>return  </strong>sslCtx;<br>}</pre><p>Build the project with maven.</p><p>To start the server you need to download jetty-alpn library compatible with your JDK version and give the xbootclasspath to that jar file.</p><pre>java -Xbootclasspath/p:/home/{path-to-jar}/alpn-boot.jar -jar server-v0.1-1.0.0.jar</pre><p>You can try HTTP/2 behavior by sending a request to <a href="https://0.0.0.0:8888/">https://0.0.0.0:8888</a> using an appropriate client. But most of the browsers don’t support server-push.</p><p>Complete Project will be here : <a href="https://github.com/chanakadinesh/Http2-server">https://github.com/chanakadinesh/Http2-server</a></p><h4>Stay tuned…!</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e54134dc90b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hands on HTTP/2]]></title>
            <link>https://medium.com/@chanakadkb/hands-on-http2-788325617523?source=rss-667e7af8d35e------2</link>
            <guid isPermaLink="false">https://medium.com/p/788325617523</guid>
            <category><![CDATA[http2]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[protocol]]></category>
            <dc:creator><![CDATA[Chanaka Balasooriya]]></dc:creator>
            <pubDate>Tue, 20 Dec 2016 08:40:57 GMT</pubDate>
            <atom:updated>2016-12-20T08:48:41.488Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>HTTP/2 is the newly introduced version of Hypertext Transfer Protocol (HTTP) and it is high time to talk about the importance of HTTP/2, its new features and how to apply those features.</blockquote><p><strong>What made to introduce HTTP/2</strong></p><p>Reducing latency and using resources efficiently are two main objectives of any web service. Even though many techniques were introduces such keep-alive and pipeline in previous HTTP versions were not enough with the improvement of technology of devices and number of users. When loading a web page using HTTP/1.x protocols web browsers has to create multiple connections in order to achieve concurrency of requests. Creating multiple connections is costly in both time and resources wise. As well as most of the header fields are verbose and repetitive and it causes to increase the web traffic. So, as a solution HTTP/2 were introduced.</p><p><strong>Main features of HTTP/2</strong></p><ol><li>Multiplexing requests and responses — <em>Clients can send and receive requests and responses parallel in same connection interleaving each other. Requests are sends as streams and a request is divided into several frames such as HEADER frames and DATA frames. Multiplexing is done using a stream id.</em></li><li>Prioritization of requests — <em>Clients can define which requests should get priority of the connection and it can be used to use multiplexing requests more efficiently. This is achieved using HEADER frame’s priority fields or PRIORITY frames.</em></li><li>Header compression</li><li>Flow controlling — <em>It ensures that the sender sends only enough data that the receiver can receive. HTTP/2 provides flow controlling through WINDOW_UPDATE frames</em></li><li>Server push — <em>When a server receives a request, server can push other resources that are related to that request as a separate response. As an example when a web browser requesting a html page, server can push other resources such as css and javascript files before browser sending requests for them.</em></li></ol><p>The official documentation of HTTP/2 protocol can be found <a href="http://httpwg.org/specs/rfc7540.html">here</a>.</p><p>From next post I’m going to implement a server and a client that support HTTP/2 using <a href="http://netty.io/">Apache Netty</a> library and discuss about how they support for each HTTP/2 specifications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=788325617523" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>