<?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 Lahiru Sampath Abegunawardena on Medium]]></title>
        <description><![CDATA[Stories by Lahiru Sampath Abegunawardena on Medium]]></description>
        <link>https://medium.com/@lahirusabe15?source=rss-4b20e04f6a7a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*vidtXToYsU6duE1lOf5raw.jpeg</url>
            <title>Stories by Lahiru Sampath Abegunawardena on Medium</title>
            <link>https://medium.com/@lahirusabe15?source=rss-4b20e04f6a7a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 18:08:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lahirusabe15/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[Angular — Springboot project from Scratch]]></title>
            <link>https://lahirusabe15.medium.com/angular-springboot-project-from-scratch-9a72f83da31a?source=rss-4b20e04f6a7a------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a72f83da31a</guid>
            <dc:creator><![CDATA[Lahiru Sampath Abegunawardena]]></dc:creator>
            <pubDate>Wed, 22 Oct 2025 13:24:46 GMT</pubDate>
            <atom:updated>2025-10-22T13:24:46.423Z</atom:updated>
            <content:encoded><![CDATA[<h3>Angular — Springboot project from Scratch</h3><p>This is a start of new article series on a web based prroject that uses Java Springboot as BE and Angular as the Fronend. I will guide you through a step by step process to continue the process to a fully operational crud system.</p><h4>System in brief</h4><p>This is a project for a Student Management system. Which allows you to to manage Students Courses and there Enrollments to courses.</p><p>Student and Course entities are linked through a many to many relationship which use a Association Table called enrollment which will also store marks for enrollment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eTIADPutPRPhx-Wirw_3ZA.png" /></figure><p>We will create few API end points using Springboot to perform CRUD operations to these entities which we will build step by step in this article series</p><h4>Springboot setup</h4><p>In this article series I have planned to use Spring Tool Suite as my IDE. You can easily create a new Spring Starter Project</p><p>File -&gt; New -&gt; Spring Starter Project</p><p>This will provide you a dialog box to setup your project with including relevant dependancies</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/553/1*yCIt26rkz1H-0VAnla9RCQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/553/1*_TbXMwKgUZ_dNys2dG-ISA.png" /></figure><p>Then if you click on Next -&gt; Finish it will start to create Spring boot project. It will take few minutes and create new project while importing relevant dependancies. Few minutes later this will create new project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/264/1*X0EFXreI6NjmL8t5udgOkA.png" /></figure><p>Project folder -&gt; pom.xml file containes all the details including pom.xml. If you check the pom.xml dependecies section</p><pre>&lt;dependencies&gt;<br><br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;<br>  &lt;/dependency&gt;<br><br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;<br>   &lt;scope&gt;test&lt;/scope&gt;<br>  &lt;/dependency&gt;<br><br> &lt;/dependencies&gt;</pre><pre>spring-boot-starter-web      =&gt; Creates RESTful web applications or APIs.<br><br>spring-boot-starter-test     =&gt; Provides tools and frameworks for testing <br>                                your application.</pre><p>I need to setup my api to be run in 8081 port. So in orrder to that I have changed application.properties file in src/main/resources folder</p><pre>spring.application.name=LMS-Demo<br>server.port=8081</pre><p>You will see that Spring tool suit has created the main java class that supports with starting this SpringBoot applcation in src/main/java folder -&gt; com.example.lms package</p><pre>package com.example.lms;<br><br>import org.springframework.boot.SpringApplication;<br>import org.springframework.boot.autoconfigure.SpringBootApplication;<br><br>@SpringBootApplication<br>public class LmsDemoApplication {<br><br> public static void main(String[] args) {<br>  SpringApplication.run(LmsDemoApplication.class, args);<br> }<br><br>}</pre><pre>@SpringBootApplication -&gt; is a annotation to identify this class <br>                          as main class for SpringBootApplication<br><br>main method (public static void main(String[] args)) -&gt; main method<br><br></pre><p>main method contains code to run this LmsDemoApplication class to run as main java class -&gt; SpringApplication.run(LmsDemoApplication.class, args);</p><pre>public static void main(String[] args) {<br>  SpringApplication.run(LmsDemoApplication.class, args);<br> }</pre><p>So at the end this will contain all the details to start a Springboot application from start.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/329/1*arh3Vsz3vnal28Lq9ilozA.png" /></figure><p>So in order to run the springboot application for the first time you need to follow below procedure</p><pre>1. Right click on LmsDemoApplication.java on package explorer<br>2. select &quot;Run As -&gt; Java Application</pre><p>This will start the project and it will show as this in console in your IDE</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2rK0MFu5nONB04-79PCCnQ.png" /></figure><p>So let’s create an API end point to get string “Hello World” as outcome</p><ol><li>First create a new Java Class called HelloController in your package named com.example.lms</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*_qoA-lz9Ld9_Ly8xLm32kg.png" /></figure><p>2. Include follwing code in that class</p><pre>package com.example.lms;<br><br>import org.springframework.web.bind.annotation.GetMapping;<br>import org.springframework.web.bind.annotation.RestController;<br><br>@RestController<br>public class HelloController {<br><br> @GetMapping(&quot;/hello&quot;)<br>    public String hello() {<br>      return &quot;.........................     Hello world!     .........................&quot;;<br>    }<br><br><br>}</pre><pre>RestController        =&gt; used to identify thst this class is going to be used<br>                         in order to create Rest Api<br><br>@GetMapping(&quot;/hello&quot;)  =&gt; if this SpringBootApplication get request for <br>                          http://localhost:8081/hello this is going to be<br>                         executed (in this case hello() function)</pre><p>So if you just accessed to browser and typed <a href="http://localhost:8081/hello">http://localhost:8081/hello</a> it will show this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*GXz1CIxnAW8FxSE4mEaJIA.png" /></figure><p>In this article series we will continue with developing few api end points which will connect with a database and it will perform CRUD operations as per request. At the end of each crud operation we will connect this with a Angular project so that fully functional project can be delivered at the end of this article series</p><p>All the codes will be committed on a github repo called <a href="https://github.com/LahiruAbegunawardena/LMS-Demo">LMS-Demo</a>. Codes relevant to each article will be updated on this github repo and you will be able to continue your project along with this aricle series</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a72f83da31a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sorting Algorithms — Quick Sort]]></title>
            <link>https://lahirusabe15.medium.com/sorting-algorithms-quick-sort-8a0676728afe?source=rss-4b20e04f6a7a------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a0676728afe</guid>
            <category><![CDATA[quicksort]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[sorting]]></category>
            <category><![CDATA[sorting-algorithms]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Lahiru Sampath Abegunawardena]]></dc:creator>
            <pubDate>Mon, 26 Apr 2021 06:56:15 GMT</pubDate>
            <atom:updated>2021-04-26T06:56:15.979Z</atom:updated>
            <content:encoded><![CDATA[<h3>Sorting Algorithms — Quick Sort</h3><p>Hi I’m Lahiru Abegunawardena. This is my 4th article on “Sorting Algorithms” topic. You can find previous articles on Sorting algorithms and much more interesting topics <a href="https://lahirusabe15.medium.com/">here</a>. Today we’ll discuss about Quick sort algorithm.</p><p>Quick sort is a sorting algorithm which follows divide and conquer method. First of all we need to understand what is this <em>divide and conquer </em>method<em>.</em></p><h4>Divide and conquer method</h4><p>Think about some problem or a task which has a huge scope, thinking of solving this at onetime is hard and even can’t give the optimum solution. But if you divide this into subtasks with smallest scope, you can solve them one by one and give them the perfect solution.</p><p>So like this in divide and conquer algorithm we divide our task into smallest tasks and solve them one by one. So this can help you to get into solution in quicker way.</p><h4>How we can apply divide &amp; conquer into sorting ?</h4><p>Sorting a list of 100 numbers is a huge task, but think if you can divide them into 10 groups. You can solve each group and rearrange those 10 sorted group accordingly.</p><p>But if you can do this division in much more planned way you can even get into solution within optimum time. This is the basic idea what we are going to do.</p><h4>Quick sort in brief</h4><p>Think of list of numbers you are going to sort. You are going to need a pivot in order to start divide. Pivot is the value we need to divide number list, normally we write numbers less than pivot in left side and higher numbers into right side. There are few popular methods to choose the pivot out of number list.</p><ol><li>Last element of the list ( → arraylist.get(0))</li><li>First element of the list ( → arraylist.get(0))</li><li>middle item of the list ( → arraylist.get( ((arraylist.size()+1)/2)-1 ))</li></ol><p>So every time you divide a number list into to you keep identifying a pivot and continue division until every list contains only one element. After that you can write them according to order from left to right exactly as given below</p><ol><li>left side list</li><li>Pivot</li><li>right side list</li></ol><p>Please refer the example I attached below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*reTfPOJpUTM9wCm-4SsxMA.png" /></figure><h4>Implementation of Quick Sort algorithm</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/859/1*aml5v907uIKVeaRLp2Y3hw.png" /><figcaption>code Quick Sort — 1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*wAbrn5x95m_XOdd22wUjlw.png" /><figcaption>code Quick Sort — 2</figcaption></figure><p>If you understood these steps already, you should be able to understand by now that we need to use recursive function in order to achieve this task. So first let me explain my recursive function.</p><blockquote>public ArrayList&lt;Integer&gt; sortArray(ArrayList&lt;Integer&gt; arr, int firstIndex, int lastIndex) {}</blockquote><p>First of all you can see that in parameter list it includes arraylist of integers which contains number list. So when you call function recursive you add your higher or lesser than pivot lists into this. Next parameter in start index most probably this is value 0 and last index which equals to (arraylist.size()-1).</p><p>In a recursive function you need to check what’s the check points where you no longer call itself recursively or you do. So in here it means where your arraylist is empty. So that means in that instance this function is called by anotherarray list which only has 1 element(pivot of it). Unless (if arraylist is not empty) you have to identify pivot (in this I use last element) and identify lesser than and higher than elements and call functions recursively. I think you can understand this better with comments I added in code.</p><p>Now lets see the result from execution</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*bftglroGIaEEC3AvA2IyPA.png" /><figcaption>Execution — QuickSort</figcaption></figure><h3>Performance</h3><p>Reference: <a href="https://en.wikipedia.org/wiki/Quicksort#:~:text=Mathematical%20analysis%20of%20quicksort%20shows,though%20this%20behavior%20is%20rare.">Quick sort from wikipedia</a></p><p>Let’s look what is time complexity of this.</p><blockquote><em>no of items → n</em></blockquote><blockquote><em>Worst case → O(n²)</em></blockquote><blockquote>BestCase → O(n logn)</blockquote><blockquote>AverageCase → O(n logn)</blockquote><p>So as you can see O (nlogn) is the average case which implies this is one of the quickest sorting algorithms. n is for number of items in arraylist.</p><p>I hope you will find this article very helpful in learning about Quicksort algorithm and my implementation. I would like to suggest you to try implement sorting by descending order for a better understanding on concept.</p><p>Next article will be about another sorting algorithm and its implementation or algorithm explanation. If there is anything to clarify or solve please don’t hesitate to contact me via my <a href="https://lk.linkedin.com/in/lahiru-abegunawardena-96124914a">LinkedIn</a> and <a href="https://www.facebook.com/CodeReaders/">fb page</a>. Try all of this by yourself and if there is anything feel free to comment. Like and please Share with your friends.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a0676728afe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sorting Algorithms -part 3  (Insertion Sorting)]]></title>
            <link>https://lahirusabe15.medium.com/sorting-algorithms-part-3-insertion-sorting-ce10b4b4ba41?source=rss-4b20e04f6a7a------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce10b4b4ba41</guid>
            <dc:creator><![CDATA[Lahiru Sampath Abegunawardena]]></dc:creator>
            <pubDate>Sun, 25 Apr 2021 05:14:22 GMT</pubDate>
            <atom:updated>2021-04-25T05:14:22.149Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Sorting Algorithms -part 3 (Insertion Sorting)</strong></h3><p>Hi I’m Lahiru Abegunawardena. This is my 3rd article on “Sorting Algorithms” topic. You can learn about <a href="https://lahirusabe15.medium.com/sorting-algorithms-part-1-9248fdba1dc5">Bubble Sort</a> and <a href="https://lahirusabe15.medium.com/sorting-algorithms-part-2-b72edc5a323">Selection sort</a> by referring 1st and 2nd articles of this series.</p><h3>Insertion sort</h3><p>Today we are going to discuss about insertion sorting and how we can implement this using java. First of all we need to know that Insertion sort also follows comparison based sorting algorithm.</p><p>How does this work?</p><p>In here we divide array of elements to be sorted into two sub-lists.</p><ol><li>sorted: elements that are sorted (0th to selected index)</li><li>unsorted</li></ol><p>In this article I’m building this algorithm to sort in ascending order. So I planned to sort elements from 0th element to selected index and keep selected index to last index untouched (or you can consider them as remained unsorted).</p><p>Let’s see how this work and we will go for a better explanation</p><blockquote>Sort using Selection sort into ascending order → 8, 5, 9, 3, 6</blockquote><blockquote>1. → sorted:[8], unsorted:[5, 9, 3, 6]</blockquote><blockquote>2. → sorted:[5, 8], unsorted:[9, 3, 6]</blockquote><blockquote>3. → sorted:[5, 8, 9], unsorted:[3, 6]</blockquote><blockquote>4. → sorted:[3, 5, 8, 9], unsorted:[6]</blockquote><blockquote>5. → sorted:[3, 5, 6, 8, 9], unsorted:[]</blockquote><p>So as you can see what we do is we sort sub array from 0th index to selected index and keep the rest untouched. We continue this process until all elements are in sorted list. Let’s see how we can put this into code using java.</p><h4>Implementation -Insertion.java</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/839/1*AyIny-RpATYq6UjHIsBiaQ.png" /><figcaption>Insertion.java</figcaption></figure><p>As you can see I used ArrayList&lt;Integer&gt; in order to achieve this bit easily. Lets go through the code and try to understand what I did.</p><p>In first code block I created an ArrayList <em>arr </em>and added items in array to it. Then I assigned size of arr to a int variable “<em>len”.</em></p><p>And I went through the arr within for loop. As you can see below every round of this for loop index “<em>i” </em>used to represents 2 specific things.</p><blockquote>1. new element that added to be on sorted sub-list.</blockquote><blockquote>2. elements from index 0 to i needed to be sorted</blockquote><p>I created new int variable properIndex to identify proper index of this new element that we added into our sorted sub-list. Let me explain you this more.</p><p>Let’s think about the example we took before to understand insertion sort</p><blockquote>Sort using Selection sort into ascending order → 8, 5, 9, 3, 6</blockquote><blockquote>1. → sorted:[8], unsorted:[5, 9, 3, 6]</blockquote><blockquote>2. → sorted:[5, 8], unsorted:[9, 3, 6]</blockquote><blockquote>3. → sorted:[5, 8, 9], unsorted:[3, 6]</blockquote><blockquote>4. → sorted:[3, 5, 8, 9], unsorted:[6]</blockquote><blockquote>5. → sorted:[3, 5, 6, 8, 9], unsorted:[]</blockquote><p>In here line 2 look into sorted array. we can see there is a new element 5 in the sorted sub-list. But as we see this element 5 was originally in index 2 of array when we declare it, but after we sort it in that sorted sub list now it is in the index 0. So I think you can understand this more by thinking about this in al 5 lines.</p><p>So I declared this new int variable properIndex to identify this index of the new element where it should be on sorted sub-list. Then I iterate through another for loop just to identify what is the suitable index of that arr.get(i) element. So whenever I find index of the first element that is larger than our new one I assign index of that element to properIndex and break the for loop. Or else (this means i th element is the largest in sorted sub-list) keep the element where it was previously by keeping properIndex to i.</p><blockquote>int selected = arr.remove(i);</blockquote><blockquote>arr.add(properIndex, selected);</blockquote><p>in this two lines I complete the task we created by that 2nd for loop. As you can see I remove ith element from arraylist and put it to the index (properIndex) so that element can be placed where it should be. Next few code liness I added to print more illustratable output to identify how we did the sorting step by step.</p><p>So below I attached screenshot of the output of code I described here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*d5RSArWkVtm_Tc9JLvuWVg.png" /><figcaption>Result -Insertion.java</figcaption></figure><h3>Performance</h3><p>Let’s look what is time complexity of this.</p><blockquote><em>no of items → n</em></blockquote><blockquote><em>Worst case → O(n²)</em></blockquote><p>Worst case scenario is based on sorting descending order list into ascending order, because you have to go on both for loops completely, so I think you can understand that this is also not god for large data sets.</p><p>I hope you will find this article very helpful in learning about Insertion sort algorithm and my implementation. I would like to suggest you to try implement sorting by descending order for a better understanding on concept.</p><p>Next article will be about another sorting algorithm and its implementation or algorithm explanation. If there is anything to clarify or solve please don’t hesitate to contact me via my <a href="https://lk.linkedin.com/in/lahiru-abegunawardena-96124914a">LinkedIn</a> and <a href="https://www.facebook.com/CodeReaders/">fb page</a>. Try all of this by yourself and if there is anything feel free to comment. Like and please Share with your friends.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce10b4b4ba41" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sorting Algorithms -Part 2]]></title>
            <link>https://lahirusabe15.medium.com/sorting-algorithms-part-2-b72edc5a323?source=rss-4b20e04f6a7a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b72edc5a323</guid>
            <category><![CDATA[sorting]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[sorting-algorithms]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[selection-sort]]></category>
            <dc:creator><![CDATA[Lahiru Sampath Abegunawardena]]></dc:creator>
            <pubDate>Sat, 12 Dec 2020 07:06:44 GMT</pubDate>
            <atom:updated>2020-12-12T07:20:10.066Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi I’m Lahiru Abegunawardena. This is my 2nd article on “Sorting Algorithms” topic. In <a href="https://lahirusabe15.medium.com/sorting-algorithms-part-1-9248fdba1dc5">1st article</a> of this series I described about Bubble Sorting algorithm and its implementation.</p><h3>Selection Sort</h3><p>Today we will discuss about selection sort algorithm. Selection sort is also follows comparison sorting algorithm. Let’s get a general idea about steps in this sorting.</p><p>In this steps you will understand that there are two parts within the list as <em>unsorted </em>and <em>sorted</em>.<em> </em>So basically you have to identify the smallest item in unsorted list and put it into sorted list until there are no items left in <em>unsorted list</em>.</p><blockquote>Sort using Selection sort into ascending order → 8, 5, 9, 3, 6</blockquote><blockquote>1. → unsorted:[8, 5, 9, 3, 6], sorted:[] → smallest_value=3</blockquote><blockquote>2. → unsorted:[8, 5, 9, 6], sorted:[3] → smallest_value=5</blockquote><blockquote>3. → unsorted:[8, 9, 6], sorted:[3, 5] → smallest_value=6</blockquote><blockquote>4. → unsorted:[8, 9], sorted:[3, 5, 6] → smallest_value=8</blockquote><blockquote>5. → unsorted:[9], sorted:[3, 5, 6, 8] → smallest_value=9</blockquote><blockquote>6. → unsorted:[], sorted:[3, 5, 6, 8, 9]</blockquote><p>As you can see this way it removes smallest item from unsorted part and add into end of sorted part. Even though this is the basic algorithm I have changed the process when I changed this into a java code. I’ve added some comments for a better understanding and explained code after 2nd image on <em>selection.java</em></p><h4>Implentation — Selection.java</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-GSOp68lOu06hfstpBT1mA.png" /><figcaption><strong>Selection.java — sorting segment</strong></figcaption></figure><p>Main method and printArr() function to execute the above function is given below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1MJsQsg-I38GPt2tLCaiYw.png" /><figcaption><strong>Selection.java — Printing and</strong></figcaption></figure><p>I need to get your attention on first image. smlIndx index is for identifying index of smallest item in unsorted part. So as given in first for loop variable i (1st item in unsorted part) is selected as smalIndx in beginning of each iteration. Within this 2nd for loop I identify the index of smallest item in unsorted part and I exchange it with first item in unsorted part for making it easy to implement.</p><p>I printed unsorted array and 2 items to be swapped with their indexes for your understanding.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ylXa9MDpzQ2B1je_j6xYUw.png" /><figcaption><strong>Execution Selection.java</strong></figcaption></figure><p>Last image given is a screenshot on execution of Selection.java class. I hope you understand code given above, however if you have any doubts or questions on any of this please don’t hesitate to contact me as given in end of this article.</p><h4>Performance</h4><p>Let’s look what is time complexity of this.</p><blockquote>Worst case → O(n²) comparisons, O(n) swaps →(eg: descending order array into ascending order sort)</blockquote><blockquote>Best case → O(n²) comparisons, O(1) swaps → (eg: sorting already sorted array)</blockquote><blockquote>Average case → O(n²) comparisons, O(n) swaps</blockquote><p>I hope you will find this article very helpful in learning about Selection sort algorithm. I would like to suggest you to try implement sorting by descending order for a better understanding on concept.</p><p>Next article will be about another sorting algorithm and its implementation or algorithm explanation. If there is anything to clarify or solve please don’t hesitate to contact me via my <a href="https://lk.linkedin.com/in/lahiru-abegunawardena-96124914a">LinkedIn</a> and <a href="https://www.facebook.com/CodeReaders/">fb page</a>. Try all of this by yourself and if there is anything feel free to comment. Like and please Share with your friends.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b72edc5a323" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sorting Algorithms -Part 1]]></title>
            <link>https://lahirusabe15.medium.com/sorting-algorithms-part-1-9248fdba1dc5?source=rss-4b20e04f6a7a------2</link>
            <guid isPermaLink="false">https://medium.com/p/9248fdba1dc5</guid>
            <category><![CDATA[bubble-sort]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[sorting]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[sorting-algorithms]]></category>
            <dc:creator><![CDATA[Lahiru Sampath Abegunawardena]]></dc:creator>
            <pubDate>Tue, 03 Nov 2020 13:30:11 GMT</pubDate>
            <atom:updated>2020-11-03T13:30:11.700Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi I’m Lahiru Abegunawardena. This is my new article series on Sorting Algorithms. First we will see what is an Algorithm.</p><h4>Algorithms</h4><p>Simply an algorithm is a sequence of instructions to solve a problem or perform a computation. This can be written as pseudocode, line by line instructions, even you can use flowchart diagram.</p><h4>Sorting Algorithm</h4><p>A Sorting Algorithm is used to rearrange a given array or list of elements according to a certain order. In this article series we will discuss about sorting a list of numbers according to ascending or descending order. Sorting algorithms are divided into two main sections as “Comparison sort” and “Integer sort”.</p><h4>Comparison Sort</h4><p>Comparison sorts compare elements compare at each step of the algorithm to determine if one element should be to the left or right of another element.</p><h4>Integer Sort</h4><p>Integer sort is also called as counting sort. We will try to understand process of this sorting technique with following example.</p><blockquote>Let’s think there is a list of 10 items. If item “x” is higher than 4 of other elements then x is placed on 5th position in the list. So we can continue the process until the list is sorted.</blockquote><p>In this article series we will discuss about few types of sorting algorithms, their characteristics and there implementation or simplified algorithm level explanation.</p><h3>Bubble Sort</h3><p>Bubble sort is a simple comparison sorting algorithm. This will compare each pair of element in the list and exchange them if they are not in order. Let’s take a simple example on bubble sort and we will continue the discussion.</p><blockquote>Unsorted array → 8, 5, 9, 3 need to sort in ascending order</blockquote><blockquote><strong>8,5</strong>,9,3 → compare 8,5 (8&gt;5) exchange 8&amp;5.</blockquote><blockquote>5,<strong>8,9</strong>,3 → compare 8,9 (9&gt;8)</blockquote><blockquote>5,8,<strong>9,3</strong> → compare 3,9 (9&gt;8)</blockquote><blockquote>5,8,3,9</blockquote><p>This is only the first round that includes 4 steps. If you continue the process correctly you will see that this requires maximum 4 rounds to sort list in ascending order. That means 16 steps(4x4).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/245/1*_v-VgaYlMv1XVh6oev04_g.png" /><figcaption>Bubble Sort example</figcaption></figure><p>So if you have n element list you will need n² steps to complete the sorting. This is how complexity of Bubble sort is calculated as<strong> O(n²)</strong>.</p><p>Now we will see how we can implement bubble sort using Java language.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IKh5gggTAn4z0kE9x8ptmA.png" /><figcaption><strong>Bubble.java</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*F8qjOBho5YaRjFQK4RCelg.png" /><figcaption>Bubble.java execution</figcaption></figure><p>Now we will discuss what I did in this code. Specially we need to focus on usage of “for loops”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/1*I1otVVKlDYlLLOtNJOV2Iw.png" /><figcaption>Nested for loops</figcaption></figure><p>1st for loop iterates (int i) from the 0 to arr.length-1 of array. This helps to iterate the next for loop through the whole array. Second for loop is bit developed from the original Bubble Sort algorithm. In original algorithm iterates from 0 to arr.length-1, so this will iterate through whole array in every time whether the last elements are already sorted or not. How ever in the given code you will see that 2nd for loop iterates only to <strong>arr.length-i-1</strong>. With this change it only iterates to unsorted array items. This small change can increase the efficiency of this sorting. I hope to clarify this to you at the end of the code review.</p><p>In the if loop I check whether arr[j] is higher than arr[j+1] and if it’s true exchange them. I used variable temp to do this exchange easily.</p><p>Now we will see what is the effect we can get with this arr.length-i-1 instead of arr.length-1 in 2nd for loop.</p><p>First you should see “Iteration -image1” given below. In here I wrote a code to identify what are the array items compared when 2nd for loop iterates through 0 to arr.length-1. “Iteration -image2” is the screenshot of result you get when that code executes. You will see that it iterates through all array items in all rounds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*Tq0EJ7RhRPki6_LPicaRlg.png" /><figcaption><strong>Iteration -image1</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/1*-9EAOdQTTxBohasVe31tOw.png" /><figcaption><strong>Iteration -image2</strong></figcaption></figure><p>Now you can see “Iteration -image3” given below. In here I wrote a code to identify what are the array items compared when 2nd for loop iterates through 0 to arr.length-i-1. “Iteration -image4” is the screenshot you get when that code executes. You will see that it iterates only through unsorted array items.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UxdEI82iViRPIRQFwZWC9A.png" /><figcaption>Iteration -image3</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/353/1*83sGL9mRoi9Eh4OGbH90wg.png" /><figcaption><strong>Iteration -image4</strong></figcaption></figure><p>Anyway I hope that you can understand what I meant by increasing the efficiency. Thinking about an array with hundred items and imagine how this efficiency would effect would help you to find this more understandable.</p><p>I hope you will find this article very helpful in learning basics of sorting algorithms. Next article will be about another sorting algorithm and its implementation or algorithm explanation. If there is anything to clarify or solve please don’t hesitate to contact me via my <a href="https://lk.linkedin.com/in/lahiru-abegunawardena-96124914a">LinkedIn</a> and <a href="https://www.facebook.com/CodeReaders/">fb page</a>. Try all of this by yourself and if there is anything feel free to comment. Like and please Share with your friends.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9248fdba1dc5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Springboot from beginning III]]></title>
            <link>https://lahirusabe15.medium.com/springboot-from-beginning-iii-6e7347d04d21?source=rss-4b20e04f6a7a------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e7347d04d21</guid>
            <dc:creator><![CDATA[Lahiru Sampath Abegunawardena]]></dc:creator>
            <pubDate>Wed, 29 Apr 2020 17:11:53 GMT</pubDate>
            <atom:updated>2020-04-29T17:11:53.538Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi I’m lahiru Abegunawardena. This is the 3rd article on Java Springboot. In my <a href="https://medium.com/@lahirusabe15/springboot-from-the-beginning-25bc3f6b53f4">1st</a> and <a href="https://medium.com/@lahirusabe15/springboot-from-beginning-ii-77430013188d">2nd</a> articles on this series we discussed about storing data into mysql and retrieve all data from that table.</p><p>First of all I need to tell you that I changed responses from Store and getAll endpoints and added tryCatch blocks to prevent application from breaking when a exception occured. Following changes are applied in BookService class.</p><pre>public Object storeBooks(BookModel newBook){<br>    Map&lt;String, Object&gt; responseData = new HashMap&lt;&gt;();<br>    try {<br>        BookModel newBookDta = bookRepository.save(newBook);<br>        responseData.put(&quot;msg&quot;, &quot;New Book stored successfully..&quot;);<br>        responseData.put(&quot;status&quot;, true);<br>        responseData.put(&quot;data&quot;, newBookDta);<br>        return responseData;<br>    } catch (Exception e){<br>        responseData.clear();<br>        responseData.put(&quot;msg&quot;, &quot;New Book store failed..&quot;);<br>        responseData.put(&quot;status&quot;, false);<br>        responseData.put(&quot;data&quot;, null);<br>        return  responseData;<br>    }<br>}<br><br>public Object getAllBooks(){<br>    Map&lt;String, Object&gt; responseData = new HashMap&lt;&gt;();<br>    try {<br>        Iterable&lt;BookModel&gt; allBooks = bookRepository.findAll();<br>        responseData.put(&quot;msg&quot;, &quot;All books retrieved..&quot;);<br>        responseData.put(&quot;status&quot;, true);<br>        responseData.put(&quot;data&quot;, allBooks);<br>        return responseData;<br>    } catch (Exception e){<br>        responseData.put(&quot;msg&quot;, &quot;All books retrieve failed..&quot;);<br>        responseData.put(&quot;status&quot;, false);<br>        responseData.put(&quot;data&quot;, null);<br>        return responseData;<br>    }<br>}</pre><p>Also I had to change return types of those functions in BookControler to Object to accept responses returned from this changed Service class functions. I have returned response as json with data, status and message with using Map in Java. Let’s see how this changed format of the response.</p><pre>@PostMapping(&quot;/store&quot;)<br>public Object storeBooks(@RequestBody BookModel newBook){<br>    return bookService.storeBooks(newBook);<br>}<br><br>@GetMapping(&quot;&quot;)<br>public Object getAllBooks(){<br>    return bookService.getAllBooks();<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*i-GfEuEx48k6roL90zj4rA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*WVoerDfpA2Bbw9HNmEsgzA.png" /></figure><p>Now we will look into today discussion. First we’ll see how to retrieve data by it’s id. First I’ll show you the code in Service class.</p><pre>public Object getBookById(Integer bookId){<br>    Map&lt;String, Object&gt; responseData = new HashMap&lt;&gt;();<br>    try {<br>        if(bookRepository.existsById(bookId)){<br>            Optional&lt;BookModel&gt; existDta = bookRepository.findById(bookId);<br>            responseData.put(&quot;msg&quot;, &quot;Book found by bookId&quot;);<br>            responseData.put(&quot;status&quot;, true);<br>            responseData.put(&quot;data&quot;, existDta);<br>        } else {<br>            responseData.clear();<br>            responseData.put(&quot;msg&quot;, &quot;There is no book exists by this id..&quot;);<br>            responseData.put(&quot;status&quot;, false);<br>            responseData.put(&quot;data&quot;, null);<br>        }<br>        return responseData;<br>    } catch (Exception e){<br>        responseData.clear();<br>        responseData.put(&quot;msg&quot;, e.getMessage());<br>        responseData.put(&quot;status&quot;, false);<br>        responseData.put(&quot;data&quot;, null);<br>        return  responseData;<br>    }<br>}</pre><p>You need to add above code into service class. Optional&lt;BookModel&gt; is the data type of response that returns from findById() function which inherited from CrudRepository interface. I have created this function to get bookId as a parameter to get Book data by Id in “book” relation. Within this try{} block first I check if there is any book exists in passed id in url , then I return object that has true status and success message with dataset. If passed bookId doesn’t exist I return status false response with relevant message. Now we will see how we have created function in BookController to accept the GET api request.</p><pre>@GetMapping(&quot;/{bookId}&quot;)<br>public Object getBookById(@PathVariable Integer bookId){<br>    return bookService.getBookById(bookId);<br>}</pre><p>You can see that I have created this function to listen to GET request on <a href="http://localhost:8080/books/book_id">localhost:8080/books/book_id</a>. I have passed paremeter into getBookById function to get bookId through GET url by using @PathVariable annotation. Let’s see some examples on discussed scenarios.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*wT_0pkgX4xBxsrdJsfmUHQ.png" /><figcaption>Find Book by Id (Non existing)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*wQDP4qoSJ9io4iCBjaCBKg.png" /><figcaption>Find Book by Id (existing)</figcaption></figure><p>Now we will discuss about updating a data on book entity. As we discussed on the first aricle I created a function on BookController to accept PUT request on <a href="http://localhost:8080/books/update/id">http://localhost:8080/books/update/id</a>.</p><pre>@PutMapping(&quot;/update/{bookId}&quot;)<br>public Object updateBook(@PathVariable Integer bookId, @RequestBody BookModel updtBkDta){<br>    return bookService.updateBook(bookId, updtBkDta);<br>}</pre><p>As our previous discussions you must identify usages of @PathVariable and @RequestBody annotations. I have also created updateBook function on BookService business service class.</p><pre>public Object updateBook(Integer bookId, BookModel updtBkDta){<br>    try {<br>        Map&lt;String, Object&gt; responseData = new HashMap&lt;&gt;();<br><br>        if(bookRepository.existsById(bookId)){<br>            BookModel updatedDta = bookRepository.save(updtBkDta);<br>            responseData.put(&quot;msg&quot;, &quot;Book updated successfully&quot;);<br>            responseData.put(&quot;status&quot;, true);<br>            responseData.put(&quot;data&quot;, updatedDta);<br>            return responseData;<br>        } else {<br>            responseData.put(&quot;msg&quot;, &quot;There is no book exists by this id..&quot;);<br>            responseData.put(&quot;status&quot;, false);<br>            responseData.put(&quot;data&quot;, null);<br>            return responseData;<br>        }<br>    } catch (Exception e){<br>        Map&lt;String, Object&gt; responseData = new HashMap&lt;&gt;();<br>        responseData.put(&quot;msg&quot;, e.getMessage());<br>        responseData.put(&quot;status&quot;, false);<br>        responseData.put(&quot;data&quot;, null);<br>        return  responseData;<br>    }<br>}</pre><p>I have created this function to get bookId as a parameter and details that need to be updated. Within this try{} block first I check if there is any book exists in passed id in url, then after perform update I return object that has true status and success message with updated dataset. If you passed bookId that doesn’t exist I followed same scenario I used for getById functionality. I attached few screenshots below on discussed scenarios.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*-AVwCfrdXc8LoQiSsPzQXw.png" /><figcaption>PUT request Update book by bookId: 1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*QVH5w9ZuMSyGH5ifNKD6Og.png" /><figcaption>View updated book by calling GET books/1 url</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*MW7wH75SiKo3rU58R3m5LA.png" /><figcaption>Trying to update a book that doesn’t exist</figcaption></figure><p>So I hope you will find this article very helpful in learning springboot. Always remember to restart application after changing code. I’ll bring the next article on delete operations and some other functionalities. As promised on last article I have updated <a href="https://github.com/LahiruAbegunawardena/SpringBoot-Blog">repo</a> with today code. If there is anything to clarify or solve please don’t hesitate to contact me via my <a href="https://lk.linkedin.com/in/lahiru-abegunawardena-96124914a">linkedin</a> and <a href="https://www.facebook.com/CodeReaders/">fbpage</a>.</p><p>Try all of this by yourself and if there is anything feel free to comment. Like and Share with your friends.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e7347d04d21" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Springboot from beginning II]]></title>
            <link>https://lahirusabe15.medium.com/springboot-from-beginning-ii-77430013188d?source=rss-4b20e04f6a7a------2</link>
            <guid isPermaLink="false">https://medium.com/p/77430013188d</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java8]]></category>
            <category><![CDATA[api-development]]></category>
            <category><![CDATA[spring-framework]]></category>
            <dc:creator><![CDATA[Lahiru Sampath Abegunawardena]]></dc:creator>
            <pubDate>Tue, 28 Apr 2020 16:14:35 GMT</pubDate>
            <atom:updated>2020-04-28T16:30:47.342Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi I’m lahiru Abegunawardena. This is the 2nd article on Java Springboot. If you did everything right as given in <a href="https://medium.com/@lahirusabe15/springboot-from-the-beginning-25bc3f6b53f4">1st article</a> you should have a rest api that returns Hello world in <a href="http://localhost:8080/">http://localhost:8080/</a> by now. I have created a <a href="https://github.com/LahiruAbegunawardena/SpringBoot-Blog">github repo</a> for this project and this repo will be updated. You can check it and continue with this tutorial.</p><p>So today I’ll continue from the last point we finished. Today we will discuss about creating api to store data into database and retrieve all data from it. You will find springboot gives all of this in very easy progress. Always remember to restart application after code changes.</p><p>So in order to create a database connection first you need to add 2 more dependencies into pom.xml</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-starter-data-jpa&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><p>This is the 1st dependency we need. JPA is short term for “Java Persistent API”. It gives object-relational mapping. So we can use relational databases such as mysql databases. So next dependency is for mysql connection.</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;mysql&lt;/groupId&gt;<br>    &lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><p>So we will see final outcome of our pom.xml as this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*onfOqxPCAlvLSJ1_Cs08rw.png" /><figcaption>adding dependencies for JPA and MySQl connection pom.xml</figcaption></figure><p><strong>Usage of Application.properties</strong></p><p>Now we need to create connection to database in our Springboot application. In order to do this we need a special file called application.properties in our src/main/resources folder and copy following lines into it.</p><pre>spring.jpa.hibernate.ddl-auto=update<br>spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/springboot_blogdb<br>spring.datasource.username=root<br>spring.datasource.password=<br>spring.jpa.show-sql=true</pre><p>Let&#39;s go through above properties one by one.</p><blockquote>spring.jpa.hibernate.ddl-auto=update</blockquote><p>There are four status that available for spring.jpa.hibernate.ddl-auto such as “create, update, create-drop, none, validate”.</p><p>create: Create the schema and deletes previous data (creates tables and removes data every time you run application)</p><p>update: Updates schema only if needs (Tables will be created only it needs, data will be not deleted)</p><p>create-drop: creates schema and it will delete when the session is end.</p><blockquote>spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/springtrial_db</blockquote><p>jdbc:mysql://${MYSQL_HOST:localhost}:db_port(3306)/db_name.</p><blockquote>spring.jpa.show-sql=true</blockquote><p>If this is true you will see executed sql queries through the application. You can remove this line if you don’t need it.</p><p><strong>Books Api Collection introduction</strong></p><p>So let’s start building our api. Once we finished this, we will be able to manage books. These are the api routes that we are going to create at end of this article series.</p><p>POST request <a href="http://localhost:8080/books/store">http://localhost:8080/books/store</a> : add Book.</p><p>GET request <a href="http://localhost:8080/books">http://localhost:8080/books</a> : Get all books</p><p>GET request <a href="http://localhost:8080/books">http://localhost:8080/books</a>/id : Get book by Id</p><p>PUT request <a href="http://localhost:8080/books/store">http://localhost:8080/books/update/i</a>d : update Book</p><p>DELETE request <a href="http://localhost:8080/books/id">http://localhost:8080/books/id</a>: delete Book by Id.</p><p>Let’s look into Books table. We need to create a Bookmodel according Books table. So in this model file we initialise column name and data type. Let’s see how we can do this.</p><p><strong>BookModel.java (Database Table/Entity model)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*LA3Cmk939gle0130ZZ010A.png" /></figure><p>I have created a new Class named BookModel on new directory Books. I have added book_id, book_name, author_name and descriptrion. As you can see I have added two annotations @Entity, @Table(name=”book”). @entity is for notifying Springboot that this is a model class, in simple terms that is for identify this class as a table/entity in mysql and table name should be book (@Table(name=”book”)) and as you can see I have generated constructors, getters and setters.</p><p>I have annotated @Id to set book_id as primary key and by annotating “@GeneratedValue(strategy = GenerationType.<em>AUTO</em>)” springboot identifies it need to be autofilled automatically.</p><p>Now start your mysql server and create a db as you initialised in application.properties (I gave as springboot_blogdb) and run your springboot application you will see that table name</p><p><strong>@RestController BookController</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*tXZ5vffGCJBxsmMOIVwyyw.png" /><figcaption>RestController example -&gt; BookController</figcaption></figure><p>Let’s see what I’ve done in here.</p><p>@RestController: This is the annotation that we use in order to introduce this as a Controller class into SpringApplication.</p><p>@RequestMapping: I used this to add “books” as common part in above mentioned api collection. But I should mention that we can remove this and set @PostMapping(books/store) to accept a POST request that comes through <a href="http://localhost:8080/books/store">localhost:8080/books/store</a> url.</p><p>@PostMapping: this is the annotation we use to inform SpringAplication that this request should be a POST request.</p><p>@Autowired: This annotation is used to inject Class instances in Springboot.</p><p>@RequestBody: using this annotation we can get data that passed in request body in POST, PUT requests.</p><p><strong>Repository Interface</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*BZeW56QLYXeqd5CI4CPBSg.png" /><figcaption>CrudRepository</figcaption></figure><p>This is a interface class That we extend into CrudRepository interface. CrudRepository includes pre defined methods that can perform all sort of crud operations with Springboot. CrudRepository is a interface for generic operations on a repository for specific type. It needs to pass relevant entity class and data type for primary_key before extends this CrudRepository into your repository class.</p><pre>public interface BookRepository extends CrudRepository&lt;BookModel, Integer&gt;</pre><p><strong>BookService: Business Service classes</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*zD2p50o1D-c2pkErJ0kBFw.png" /></figure><p>@Service annotation is used to notify Bookservice that this is a BusinessService class. You can see that I used @Autowired annotation before injecting bookRepository instance. Using save method through bookRepository allows us to save data into “book” relation and this returns object of that saved data. So storeBooks method returns object of saved data.</p><p>So if you go step by step we can see that <a href="http://localhost:8080/books/store">localhost:8080/books/store</a> returns saved data according to data that we pass through body. So I added screenshot on POST response using Postman application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H9n3gQF2vJmAZddp9gTr0w.png" /></figure><p>Now I’ll show you breefly how to create another api endpoint to view all data in book relation.</p><p>Add this code into BookController</p><pre>@GetMapping(&quot;&quot;)<br>public Iterable&lt;BookModel&gt; getAllBooks(){<br>    return bookService.getAllBooks();<br></pre><p>Then add following part into BookService class</p><pre>public Iterable&lt;BookModel&gt; getAllBooks(){<br>    return bookRepository.findAll();<br>}</pre><p>So if you restart your application you will find that GET request on <a href="http://localhost:8080/books">http://localhost:8080/books</a> returns all books.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*BOjSWmrThVfOoFPLumFSBg.png" /></figure><p>So I hope you will find this article very helpful in learning springboot. Always remember to restart application after changing code. I’ll bring the next article on findingBookById, update and delete operations. <a href="https://github.com/LahiruAbegunawardena/SpringBoot-Blog">I have updated repo with today code.</a></p><p>Try all of this by yourself and if there is anything feel free to comment. Like and Share with your friends. Here are my <a href="https://lk.linkedin.com/in/lahiru-abegunawardena-96124914a">linkedin</a> and <a href="https://www.facebook.com/CodeReaders/">fbpage</a>. So you can contact me easily.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77430013188d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Springboot from the beginning]]></title>
            <link>https://lahirusabe15.medium.com/springboot-from-the-beginning-25bc3f6b53f4?source=rss-4b20e04f6a7a------2</link>
            <guid isPermaLink="false">https://medium.com/p/25bc3f6b53f4</guid>
            <category><![CDATA[restful-service]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Lahiru Sampath Abegunawardena]]></dc:creator>
            <pubDate>Sun, 27 Oct 2019 06:14:24 GMT</pubDate>
            <atom:updated>2019-10-27T06:48:47.758Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi I’m lahiru Abegunawardena and this a new series of articles I start on Springboot. I hope you will find this articles helpful. So let’s begin.</p><h4>What is Springboot?</h4><p>As you already know when we develop a web application we can use a RESTful web services for managing our database and do required CRUD operation. This type of web services can use sucessfully with frameworks such as Angular and libraries such as React. All you need to do is run them with different ports in a server and call to service using api end-points and perform correct CRUD operation.</p><p>So Spring boot is one of most popular RESTful web service used around the world. So in this tutorial I use Springboot for creating my service and use Mysql as my database server.</p><h4>Build your project..</h4><p>Let’s start from the beginning. Springboot is based on Java. So you need Java to start this. If you don’t have <a href="https://www.oracle.com/technetwork/java/javase/downloads/index.html">Java</a> installed in your Computer please install and continue this. I’m using Java 1.8 in my computer with IntelliJ as my IDE.</p><p>There are few ways to <a href="https://spring.io/guides">start developing a Spring project</a> but I will discuss with you about how to start this as a Maven Project.</p><p>Go to File-&gt;New-&gt;Project. Then you will get following dialog box.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*exK20MOq7AVt8zmI6un49A.png" /></figure><p>Don’t tick “create from archtype” and press Next..</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/1*DGn3xTT_LVEad8uFkpTI-g.png" /></figure><p>You can add details for group Id and ArtifactId then click Next..</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*62QtNsUfbj0hlh6OMx2NlQ.png" /></figure><p>Then Click on finish. You will now looking at the generated pom.xml file in your Maven Project. Now add following block.</p><pre>&lt;parent&gt;<br>    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt;<br>    &lt;version&gt;2.1.2.RELEASE&lt;/version&gt;<br>&lt;/parent&gt;<br><br>&lt;dependencies&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>        &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;<br>    &lt;/dependency&gt;<br>&lt;/dependencies&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*MRDdLD6TQjqo-Okv8S9MXQ.png" /></figure><p>Now your IDE will ask to import required so allow them and it’ll install all dependencies to run your project. This will take some time.</p><h4>Let’s Start Coding..</h4><p>So Now we can start our project and run it. You need to create a new package with name as you give in group id. So I create it as “com.springboot.blog” and Java Class as “ApplicationMain” in that newly created package. And you have to tell java that this is main class that executes a SpringBoot application, so we use Annotation in order to achieve this, annotation we need here is “@SpringBootApplication”. So as you can believe we also need Main method in this class, because this is the main class that executes whole RESTful Service in our computer.</p><p>Now we need to start our Springboot application from this class, we need a small function in order to continue this as “SpringApplication.<em>run</em>(ApplicationMain.class, args);”.</p><p>So if you follw all this steps correctly you will find that class like this at the end.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*wID5Y_QAo-WwqYuUSWJhnA.png" /></figure><p>So let’s start our service. You can right click on your file and click on “Run ApplicationMain” to execute your project easily on IntelliJ. And you will find your IDE shows a result as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q9p4JGjrD65sy0HnGPB5tQ.png" /></figure><p>You will find out that Spring application runs in apache port 8080. But if you open your browser and set url to “ <a href="http://localhost:8080/">http://localhost:8080/</a>” you will find out page like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CECZUVRTAT68Pdok5-g-Ww.png" /></figure><p>This is because we didn’t set any listeners to this api-end. What we should do. We need to write a Controller to accept this url and return something meaningful.</p><p>Let’s create new package named ‘com.springboot.blog/Controllers’ and Create another class named “HomeController” in that package.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*ooq8MEiYqtFHqA-eBbKP9g.png" /></figure><p>We can indicate this as a controller class to spring by using annotation “@RestController”.</p><p>Let’s make this contoller to listen this url and return meaningful straing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*0Xal2ZgUCh74JbuPrdF_FA.png" /></figure><p>Now I’ll explain you what this code does.</p><p><strong>GetMapping(“/”)</strong></p><p>You can listen to getrequest comes from url “<a href="http://localhost:8080/">http://localhost:8080/</a>” and this function Home() returns string as “Hello World”.</p><p>If you saved the code and restart project from pressing Ctrl+F5. Then you can below response in your browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/509/1*TYySuf3AZsJhPn1FVZo0Mw.png" /></figure><p>You can also get this response by sending get request through Postman as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*2dW5ne420_an5HAMB7TxPw.png" /></figure><p>So as you saw you can easily start a Spring project and start your RESTful service. From next week onwards we will discuss about how to perform CRUD operations with this beatiful framework.</p><p>Hope you will find this interesting. If there is something feel free to comment. Like and Share with your friends. Here are my <a href="https://lk.linkedin.com/in/lahiru-abegunawardena-96124914a">linkedin</a> and <a href="https://www.facebook.com/CodeReaders/">fbpage</a>. So you can contact me easily.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25bc3f6b53f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MEANStack Web development from beginning]]></title>
            <link>https://lahirusabe15.medium.com/meanstack-web-development-from-beginning-ffd06169ed3a?source=rss-4b20e04f6a7a------2</link>
            <guid isPermaLink="false">https://medium.com/p/ffd06169ed3a</guid>
            <category><![CDATA[mongoose]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[mean-stack]]></category>
            <dc:creator><![CDATA[Lahiru Sampath Abegunawardena]]></dc:creator>
            <pubDate>Tue, 18 Dec 2018 04:14:44 GMT</pubDate>
            <atom:updated>2018-12-18T04:14:44.305Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi I’m Lahiru Abegunawardena. This is the beginning of a new article series on MEANSTACK web development. At the end of this we will create a web application with Angular frontend, node backend and MongoDB database.</p><p>You will be wondering about what does it mean by MEANSTACK development.</p><p>M — Mongo</p><p>E — ExpressJS</p><p>A — Angular</p><p>N — Node</p><p>This is the list of main programming environment we use in MEANStack web development. So that’s how we get this name “MEANStack” web development.</p><p>If you are creating a web application using this technologies you need to start building backend first.</p><p>In order proceed first of all you need to install node. You can get the latest node installer <a href="https://nodejs.org/en/download/">here</a>. You can check whether you have installed node already by running “node -v” or “”npm -v” and see whether you get output, not an error. Then you can install latest angular version into your computer. Remember: you don’t need to do this steps if you already did them. In order to install angular open your cmd and run command “npm install -g @angular/cli”. This will take a while and if you already have the latest npm and node versions you will get latest version of angular. I use Angular 5 in this tutorial set. In order to install MongoDB you can use this <a href="https://www.mongodb.com/download-center">link</a>.</p><p>I use “Visual Studio Code” as my IDE in this tute set. Let’s move on to the system development. First of all you can create a folder. I create a folder named “AngApp”. I create building a “index.js” file too. Now I open my folder and run cmd in that folder. You can easily do it by entering cmd instead of this address bar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/0*ZmgNbBrAQNxZZTOd.jpg" /></figure><p>Now just type “npm init” and run the code. Here I showed what are the my inputs. You just need to press enter button each input if you don’t need to set any change.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/0*X4NTXLil4CPypxFq.jpg" /></figure><p>If you successfully completed this process you can see that new generated as “package.json”. Now open vscode and open the project in above folder. You can view all files folders included and open files. Now open package.json file. You will see something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*yNkFMS-9f9HlVX6j.jpg" /></figure><p>Now this is the file that containes all node based packages you install and use through out the backend. You can see that index.js is the main file. That means in order to run your backend you need to run index.js. In order to run this we need to install “express js” which is also a nodejs framework.</p><p>So open the terminal in vs code. You open it using “ctrl + ‘ “ keys.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/0*E-KxnYN0YryBk6HE.jpg" /></figure><p>Then run code “npm install express — save”. This will take few seconds and you will get bunch of folders named node modules. This is the place where keeps all npm libraries you install in this backend.</p><p>Now let’s open the index.js file. And write following piece of code over there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/471/0*tG5D_8bvLXJ4D-ZT.jpg" /></figure><p>Now you can start running this program. You can run this by typing “node index.js” through cmd or terminal in your editor after getting into the correct folder. And you can get the following output using your web browser through the url “http://localhost:3000&quot;.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*TLBbWQMbXJCHXv9j.jpg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/353/0*ynRsa5bIGKb6jezc.jpg" /></figure><p>So let me explain you what is written in that piece of code in index.js.</p><p>var express = require(‘express’);</p><p>const app = express();</p><p>app.listen(3000, function(){</p><p>console.log(“listening to port 3000”);</p><p>});</p><p>app.get(“/”,function (req,res){</p><p>res.send(“hello world”);</p><p>});</p><p>first it sets variable express to use express module which installed previously. Then we set it to listen into port: 3000.</p><p>By calling “http://localhost:3000/&quot; in browser it sends http request of “get” through port: 3000.</p><p>So by the last code segment we send response to the above mentioned get request as “listening to port 3000” and we can see it through the browser.</p><p>So I hope you could understand initialisation of meanstack web project. We will proceed from next article. You can contact me via my <a href="https://www.facebook.com/Lahiruabe_blog-165879124098546/">fb page</a> and <a href="https://www.linkedin.com/in/lahiru-abegunawardena-96124914a/">linkedIn</a> profile. Please feel free to like, comment share your ideas. Thank you..!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ffd06169ed3a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MVC Architecture]]></title>
            <link>https://lahirusabe15.medium.com/mvc-architecture-59b1dbdaad09?source=rss-4b20e04f6a7a------2</link>
            <guid isPermaLink="false">https://medium.com/p/59b1dbdaad09</guid>
            <category><![CDATA[framework]]></category>
            <category><![CDATA[mvc]]></category>
            <category><![CDATA[mvc-frameworks]]></category>
            <category><![CDATA[java8]]></category>
            <category><![CDATA[codeigniter]]></category>
            <dc:creator><![CDATA[Lahiru Sampath Abegunawardena]]></dc:creator>
            <pubDate>Thu, 21 Jun 2018 05:04:42 GMT</pubDate>
            <atom:updated>2018-06-21T05:04:42.485Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi I’m Lahiru Abegunawardena. From this blog I would like to talk about MVC architecture.</p><p>As you already know we use programming languages to solve our problems using computers. Programming architecture is a something that helps you to keep your code neat and understandable. Mostly the requirement of using a coding architecture is applicable to any system you design with a database or a one with large set of components. If you clearly works on some architecture that would be an extra advantage to your maintenance periods too. There are a lot of programming architectures that popularly used around the world which are perfectly matching according to programmer’s choose.</p><p>MVC is one of mostly used popular programming architecture. A lot of web based applications and some Standalone applications (specially on Java) can be coded using this architecture. There are some programming frameworks which are mainly based on MVC architecture.</p><p>Now let’s see deep into the MVC architecture. What does it mean and what are the specific facts that can be seen in this architecture. If you use MVC architecture in your program we can identify clearly 3 sections named as</p><ol><li><strong>M</strong>odel</li><li><strong>V</strong>iew</li><li><strong>C</strong>ontroller</li></ol><p>So now let’s see what are these 3 sections do and their specifications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/0*bfgP8np85NsvXeIQ.jpg" /></figure><ul><li><strong>Controller</strong></li></ul><p>This is the section where your web page getting controlled. Loading views, models. Most of the functions are written here. If you want to perform action when button clicked you can write functions through this.</p><ul><li><strong>View</strong></li></ul><p>This is where you can edit your front end. Each and every page you loaded is written in this section.</p><ul><li><strong>Model</strong></li></ul><p>This is mainly used for DB connectivity. If you wan’t you can avoid using this, because connecting with DB and perform CRUD operations also can be done through Controllers. Update, delete, data selection, insertion can be done here.</p><p>Let’s see a brief explanation..</p><p>Think you are using a website that works in MVC architecture. The front end of home page of website is written in ‘view’ block. But it’s loaded through a function written in ‘controller’ section. Think that you are going to login to system. When you filled login forum (eg- username and password) and clicks ‘login’ button, it activates relevant controller file. It gets data you entered. Calls ‘model’ section and gets relevant data set from DB. Controller checks whether data you entered is matching with data from DB. If it’s matching ‘controller’ calls function it self and creates session, and loads relevant page from ‘view’ section.</p><p>So I think this will be a help for you to get a good knowledge on MVC architecture. Please be free to comment your ideas, share for friends and like it. Thank you..!!!</p><p>You can contact me via my <a href="https://www.facebook.com/CodeReaders/">facebook</a> and <a href="https://www.linkedin.com/in/lahiru-abegunawardena-96124914a/">linkedin</a> profiles..</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59b1dbdaad09" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>